1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam 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
// Moonbeam 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 Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16
use bip32::ExtendedPrivateKey;
17
use bip39::{Language, Mnemonic, Seed};
18
use libsecp256k1::{PublicKey, PublicKeyFormat};
19
use log::debug;
20
use moonbeam_cli_opt::account_key::Secp256k1SecretKey;
21
pub use moonbeam_core_primitives::AccountId;
22
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
23
use serde::{Deserialize, Serialize};
24
use sha3::{Digest, Keccak256};
25
use sp_core::{ecdsa, Pair, Public, H160, H256};
26

            
27
#[cfg(feature = "moonbase-native")]
28
pub mod moonbase;
29
#[cfg(feature = "moonbeam-native")]
30
pub mod moonbeam;
31
#[cfg(feature = "moonriver-native")]
32
pub mod moonriver;
33

            
34
pub type RawChainSpec = sc_service::GenericChainSpec<Extensions>;
35

            
36
#[derive(Default, Clone, Serialize, Deserialize, ChainSpecExtension, ChainSpecGroup)]
37
#[serde(rename_all = "camelCase")]
38
pub struct Extensions {
39
	/// The relay chain of the Parachain.
40
	pub relay_chain: String,
41
	/// The id of the Parachain.
42
	pub para_id: u32,
43
}
44

            
45
impl Extensions {
46
	/// Try to get the extension from the given `ChainSpec`.
47
940
	pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {
48
940
		sc_chain_spec::get_extension(chain_spec.extensions())
49
940
	}
50
}
51

            
52
/// Helper function to derive `num_accounts` child pairs from mnemonics
53
/// Substrate derive function cannot be used because the derivation is different than Ethereum's
54
/// https://substrate.dev/rustdocs/v2.0.0/src/sp_core/ecdsa.rs.html#460-470
55
2
pub fn derive_bip44_pairs_from_mnemonic<TPublic: Public>(
56
2
	mnemonic: &str,
57
2
	num_accounts: u32,
58
2
) -> Vec<TPublic::Pair> {
59
2
	let seed = Mnemonic::from_phrase(mnemonic, Language::English)
60
2
		.map(|x| Seed::new(&x, ""))
61
2
		.expect("Wrong mnemonic provided");
62
2

            
63
2
	let mut childs = Vec::new();
64
20
	for i in 0..num_accounts {
65
20
		if let Some(child_pair) = format!("m/44'/60'/0'/0/{}", i)
66
20
			.parse()
67
20
			.ok()
68
20
			.and_then(|derivation_path| {
69
20
				ExtendedPrivateKey::<Secp256k1SecretKey>::derive_from_path(&seed, &derivation_path)
70
20
					.ok()
71
20
			})
72
20
			.and_then(|extended| {
73
20
				TPublic::Pair::from_seed_slice(&extended.private_key().0.serialize()).ok()
74
20
			}) {
75
20
			childs.push(child_pair);
76
20
		} else {
77
			log::error!("An error ocurred while deriving key {} from parent", i)
78
		}
79
	}
80
2
	childs
81
2
}
82

            
83
/// Helper function to get an `AccountId` from an ECDSA Key Pair.
84
20
pub fn get_account_id_from_pair(pair: ecdsa::Pair) -> Option<AccountId> {
85
20
	let decompressed = PublicKey::parse_slice(&pair.public().0, Some(PublicKeyFormat::Compressed))
86
20
		.ok()?
87
20
		.serialize();
88
20

            
89
20
	let mut m = [0u8; 64];
90
20
	m.copy_from_slice(&decompressed[1..65]);
91
20

            
92
20
	Some(H160::from(H256::from_slice(Keccak256::digest(&m).as_slice())).into())
93
20
}
94

            
95
/// Function to generate accounts given a mnemonic and a number of child accounts to be generated
96
/// Defaults to a default mnemonic if no mnemonic is supplied
97
2
pub fn generate_accounts(mnemonic: String, num_accounts: u32) -> Vec<AccountId> {
98
2
	let childs = derive_bip44_pairs_from_mnemonic::<ecdsa::Public>(&mnemonic, num_accounts);
99
2
	debug!("Account Generation");
100
2
	childs
101
2
		.iter()
102
20
		.filter_map(|par| {
103
20
			let account = get_account_id_from_pair(par.clone());
104
20
			debug!(
105
				"private_key {} --------> Account {:x?}",
106
				sp_core::hexdisplay::HexDisplay::from(&par.clone().seed()),
107
				account
108
			);
109
20
			account
110
20
		})
111
2
		.collect()
112
2
}
113

            
114
/// Helper function to generate a crypto pair from seed
115
942
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
116
942
	TPublic::Pair::from_string(&format!("//{}", seed), None)
117
942
		.expect("static values are valid; qed")
118
942
		.public()
119
942
}