main.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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::chain_spec::{self, chain_spec_properties, AccountId};
  21. use sr_keystore::Store as Keystore;
  22. use sr_primitives::{
  23. crypto::{Public, Ss58Codec},
  24. sr25519,
  25. traits::BareCryptoStore,
  26. };
  27. use substrate_telemetry::TelemetryEndpoints;
  28. const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
  29. /// A utility to easily create a testnet chain spec definition with a given set
  30. /// of authorities and endowed accounts and/or generate random accounts.
  31. #[derive(StructOpt)]
  32. #[structopt(rename_all = "kebab-case")]
  33. enum ChainSpecBuilder {
  34. /// Create a new chain spec with the given authorities, endowed and sudo
  35. /// accounts.
  36. New {
  37. /// Authority key seed.
  38. #[structopt(long, short, required = true)]
  39. authority_seeds: Vec<String>,
  40. /// Endowed account address (SS58 format).
  41. #[structopt(long, short)]
  42. endowed_accounts: Vec<String>,
  43. /// Sudo account address (SS58 format).
  44. #[structopt(long, short)]
  45. sudo_account: String,
  46. /// The path where the chain spec should be saved.
  47. #[structopt(long, short, default_value = "./chain_spec.json")]
  48. chain_spec_path: PathBuf,
  49. },
  50. /// Create a new chain spec with the given number of authorities and endowed
  51. /// accounts. Random keys will be generated as required.
  52. Generate {
  53. /// The number of authorities.
  54. #[structopt(long, short)]
  55. authorities: usize,
  56. /// The number of endowed accounts.
  57. #[structopt(long, short, default_value = "0")]
  58. endowed: usize,
  59. /// The path where the chain spec should be saved.
  60. #[structopt(long, short, default_value = "./chain_spec.json")]
  61. chain_spec_path: PathBuf,
  62. /// Path to use when saving generated keystores for each authority.
  63. ///
  64. /// At this path, a new folder will be created for each authority's
  65. /// keystore named `auth-$i` where `i` is the authority index, i.e.
  66. /// `auth-0`, `auth-1`, etc.
  67. #[structopt(long, short)]
  68. keystore_path: Option<PathBuf>,
  69. },
  70. }
  71. impl ChainSpecBuilder {
  72. /// Returns the path where the chain spec should be saved.
  73. fn chain_spec_path(&self) -> &Path {
  74. match self {
  75. ChainSpecBuilder::New {
  76. chain_spec_path, ..
  77. } => chain_spec_path.as_path(),
  78. ChainSpecBuilder::Generate {
  79. chain_spec_path, ..
  80. } => chain_spec_path.as_path(),
  81. }
  82. }
  83. }
  84. fn genesis_constructor(
  85. authority_seeds: &[String],
  86. endowed_accounts: &[AccountId],
  87. sudo_account: &AccountId,
  88. ) -> chain_spec::GenesisConfig {
  89. let authorities = authority_seeds
  90. .iter()
  91. .map(AsRef::as_ref)
  92. .map(chain_spec::get_authority_keys_from_seed)
  93. .collect::<Vec<_>>();
  94. // let enable_println = true;
  95. chain_spec::testnet_genesis(
  96. authorities,
  97. sudo_account.clone(),
  98. endowed_accounts.to_vec(),
  99. // enable_println,
  100. )
  101. }
  102. fn generate_chain_spec(
  103. authority_seeds: Vec<String>,
  104. endowed_accounts: Vec<String>,
  105. sudo_account: String,
  106. ) -> Result<String, String> {
  107. let parse_account = |address: &String| {
  108. AccountId::from_string(address)
  109. .map_err(|err| format!("Failed to parse account address: {:?}", err))
  110. };
  111. let endowed_accounts = endowed_accounts
  112. .iter()
  113. .map(parse_account)
  114. .collect::<Result<Vec<_>, String>>()?;
  115. let sudo_account = parse_account(&sudo_account)?;
  116. // let boot_nodes = vec![String::from(
  117. // "/dns4/tesnet.joystream.org/tcp/30333/p2p/QmaTTdEF6YVCtynSjsXmGPSGcEesAahoZ8pmcCmmBwSE7S",
  118. // )];
  119. let chain_spec = chain_spec::ChainSpec::from_genesis(
  120. "Joystream Testnet",
  121. "joy_testnet",
  122. move || genesis_constructor(&authority_seeds, &endowed_accounts, &sudo_account),
  123. // below can be manually modified in chainspec file, they don't affect genesis state
  124. // but we set some default values here for convenience.
  125. vec![],
  126. Some(TelemetryEndpoints::new(vec![(
  127. STAGING_TELEMETRY_URL.to_string(),
  128. 0,
  129. )])),
  130. // protocol_id
  131. Some(&*"/joy/testnet/0"),
  132. // Properties
  133. Some(chain_spec_properties()),
  134. // Extensions
  135. None, // Default::default(),
  136. );
  137. chain_spec.to_json(false).map_err(|err| err.to_string())
  138. }
  139. fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> {
  140. for (n, seed) in seeds.into_iter().enumerate() {
  141. let keystore = Keystore::open(keystore_path.join(format!("auth-{}", n)), None)
  142. .map_err(|err| err.to_string())?;
  143. let (_, _, grandpa, babe, im_online) = chain_spec::get_authority_keys_from_seed(seed);
  144. let insert_key = |key_type, public| {
  145. keystore
  146. .write()
  147. .insert_unknown(key_type, &format!("//{}", seed), public)
  148. .map_err(|_| format!("Failed to insert key: {}", grandpa))
  149. };
  150. insert_key(sr_primitives::crypto::key_types::BABE, babe.as_slice())?;
  151. insert_key(
  152. sr_primitives::crypto::key_types::GRANDPA,
  153. grandpa.as_slice(),
  154. )?;
  155. insert_key(
  156. sr_primitives::crypto::key_types::IM_ONLINE,
  157. im_online.as_slice(),
  158. )?;
  159. }
  160. Ok(())
  161. }
  162. fn print_seeds(authority_seeds: &[String], endowed_seeds: &[String], sudo_seed: &str) {
  163. let header = Style::new().bold().underline();
  164. let entry = Style::new().bold();
  165. println!("{}", header.paint("Authority seeds"));
  166. for (n, seed) in authority_seeds.iter().enumerate() {
  167. println!("{} //{}", entry.paint(format!("auth-{}:", n)), seed,);
  168. }
  169. println!();
  170. if !endowed_seeds.is_empty() {
  171. println!("{}", header.paint("Endowed seeds"));
  172. for (n, seed) in endowed_seeds.iter().enumerate() {
  173. println!("{} //{}", entry.paint(format!("endowed-{}:", n)), seed,);
  174. }
  175. println!();
  176. }
  177. println!("{}", header.paint("Sudo seed"));
  178. println!("//{}", sudo_seed);
  179. }
  180. fn main() -> Result<(), String> {
  181. #[cfg(build_type = "debug")]
  182. println!(
  183. "The chain spec builder builds a chain specification that includes a Substrate runtime compiled as WASM. To \
  184. ensure proper functioning of the included runtime compile (or run) the chain spec builder binary in \
  185. `--release` mode.\n",
  186. );
  187. let builder = ChainSpecBuilder::from_args();
  188. let chain_spec_path = builder.chain_spec_path().to_path_buf();
  189. let (authority_seeds, endowed_accounts, sudo_account) = match builder {
  190. ChainSpecBuilder::Generate {
  191. authorities,
  192. endowed,
  193. keystore_path,
  194. ..
  195. } => {
  196. let authorities = authorities.max(1);
  197. let rand_str = || -> String { OsRng.sample_iter(&Alphanumeric).take(32).collect() };
  198. let authority_seeds = (0..authorities).map(|_| rand_str()).collect::<Vec<_>>();
  199. let endowed_seeds = (0..endowed).map(|_| rand_str()).collect::<Vec<_>>();
  200. let sudo_seed = rand_str();
  201. print_seeds(&authority_seeds, &endowed_seeds, &sudo_seed);
  202. if let Some(keystore_path) = keystore_path {
  203. generate_authority_keys_and_store(&authority_seeds, &keystore_path)?;
  204. }
  205. let endowed_accounts = endowed_seeds
  206. .iter()
  207. .map(|seed| {
  208. chain_spec::get_account_id_from_seed::<sr25519::Public>(seed).to_ss58check()
  209. })
  210. .collect();
  211. let sudo_account =
  212. chain_spec::get_account_id_from_seed::<sr25519::Public>(&sudo_seed).to_ss58check();
  213. (authority_seeds, endowed_accounts, sudo_account)
  214. }
  215. ChainSpecBuilder::New {
  216. authority_seeds,
  217. endowed_accounts,
  218. sudo_account,
  219. ..
  220. } => (authority_seeds, endowed_accounts, sudo_account),
  221. };
  222. let json = generate_chain_spec(authority_seeds, endowed_accounts, sudo_account)?;
  223. fs::write(chain_spec_path, json).map_err(|err| err.to_string())
  224. }