inital commit, which is clearly not initial

Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
This commit is contained in:
Uncle Stretch
2024-10-03 15:38:52 +03:00
commit 66719626bb
178 changed files with 41709 additions and 0 deletions

204
service/src/benchmarking.rs Normal file
View File

@@ -0,0 +1,204 @@
use primitives::AccountId;
use sc_client_api::UsageProvider;
use sp_runtime::OpaqueExtrinsic;
use keyring::Sr25519Keyring;
use crate::*;
macro_rules! identify_chain {
(
$chain:expr,
$nonce:ident,
$current_block:ident,
$period:ident,
$genesis:ident,
$signer:ident,
$generic_code:expr $(,)*
) => {
match $chain {
Chain::Ghost => {
#[cfg(feature = "ghost-native")]
{
use ghost_runtime as runtime;
let call = $generic_code;
Ok(ghost_sign_call(call, $nonce, $current_block, $period, $genesis, $signer))
}
#[cfg(not(feature = "ghost-native"))]
{
Err("`ghost-native` feature not enabled")
}
},
Chain::Casper => {
#[cfg(feature = "casper-native")]
{
use casper_runtime as runtime;
let call = $generic_code;
Ok(casper_sign_call(call, $nonce, $current_block, $period, $genesis, $signer))
}
#[cfg(not(feature = "casper-native"))]
{
Err("`casper-native` feature not enabled")
}
},
Chain::Unknown => {
let _ = $nonce;
let _ = $current_block;
let _ = $period;
let _ = $genesis;
let _ = $signer;
Err("Unknown chain")
},
}
};
}
pub struct RemarkBuilder {
client: Arc<FullClient>,
chain: Chain,
}
impl RemarkBuilder {
pub fn new(client: Arc<FullClient>, chain: Chain) -> Self {
Self { client, chain }
}
}
impl frame_benchmarking_cli::ExtrinsicBuilder for RemarkBuilder {
fn pallet(&self) -> &str {
"system"
}
fn extrinsic(&self) -> &str {
"remark"
}
fn build(&self, nonce: u32) -> std::result::Result<OpaqueExtrinsic, &'static str> {
let period = 128;
let genesis = self.client.usage_info().chain.best_hash;
let signer = Sr25519Keyring::Bob.pair();
let current_block = 0;
identify_chain! {
self.chain,
nonce,
current_block,
period,
genesis,
signer,
{
runtime::RuntimeCall::System(
runtime::SystemCall::remark { remark: vec![] }
)
},
}
}
}
pub struct TransferKeepAliveBuilder {
client: Arc<FullClient>,
dest: AccountId,
chain: Chain,
}
impl TransferKeepAliveBuilder {
pub fn new(client: Arc<FullClient>, dest: AccountId, chain: Chain) -> Self {
Self { client, dest, chain }
}
}
impl frame_benchmarking_cli::ExtrinsicBuilder for TransferKeepAliveBuilder {
fn pallet(&self) -> &str {
"balances"
}
fn extrinsic(&self) -> &str {
"transfer_keep_alive"
}
fn build(&self, nonce: u32) -> std::result::Result<OpaqueExtrinsic, &'static str> {
let signer = Sr25519Keyring::Bob.pair();
let period = 128;
let genesis = self.client.usage_info().chain.best_hash;
let current_block = 0;
let _dest = self.dest.clone();
identify_chain! {
self.chain,
nonce,
current_block,
period,
genesis,
signer,
{
runtime::RuntimeCall::Balances(runtime::BalancesCall::transfer_keep_alive {
dest: _dest.into(),
value: runtime::ExistentialDeposit::get(),
})
},
}
}
}
#[cfg(feature = "casper-native")]
fn casper_sign_call(
call: casper_runtime::RuntimeCall,
nonce: u32,
current_block: u64,
period: u64,
genesis: sp_core::H256,
acc: sp_core::sr25519::Pair,
) -> OpaqueExtrinsic {
use codec::Encode;
use sp_core::Pair;
let extra: casper_runtime::SignedExtra = (
frame_system::CheckNonZeroSender::<casper_runtime::Runtime>::new(),
frame_system::CheckSpecVersion::<casper_runtime::Runtime>::new(),
frame_system::CheckTxVersion::<casper_runtime::Runtime>::new(),
frame_system::CheckGenesis::<casper_runtime::Runtime>::new(),
frame_system::CheckMortality::<casper_runtime::Runtime>::from(sp_runtime::generic::Era::mortal(
period,
current_block,
)),
frame_system::CheckNonce::<casper_runtime::Runtime>::from(nonce),
frame_system::CheckWeight::<casper_runtime::Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<casper_runtime::Runtime>::from(0),
);
let payload = casper_runtime::SignedPayload::from_raw(
call.clone(),
extra.clone(),
(
(),
casper_runtime::VERSION.spec_version,
casper_runtime::VERSION.transaction_version,
genesis,
genesis,
(),
(),
(),
),
);
let signature = payload.using_encoded(|p| acc.sign(p));
casper_runtime::UncheckedExtrinsic::new_signed(
call,
sp_runtime::AccountId32::from(acc.public()).into(),
primitives::Signature::Sr25519(signature),
extra,
).into()
}
pub fn benchmark_inherent_data() -> std::result::Result<inherents::InherentData, inherents::Error> {
use inherents::InherentDataProvider;
let mut inherent_data = inherents::InherentData::new();
let d = std::time::Duration::from_millis(0);
let timestamp = sp_timestamp::InherentDataProvider::new(d.into());
futures::executor::block_on(timestamp.provide_inherent_data(&mut inherent_data))?;
Ok(inherent_data)
}

513
service/src/chain_spec.rs Executable file
View File

@@ -0,0 +1,513 @@
//! Ghost chain configuration.
use codec::Encode;
use ghost_slow_clap::sr25519::AuthorityId as SlowClapId;
use primitives::{AccountId, AccountPublic};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use grandpa_primitives::AuthorityId as GrandpaId;
use babe_primitives::AuthorityId as BabeId;
#[cfg(feature = "casper-native")]
use pallet_staking::Forcing;
#[cfg(feature = "casper-native")]
use casper_runtime as casper;
#[cfg(feature = "casper-native")]
use casper_runtime_constants::currency::CSPR;
use sc_chain_spec::ChainSpecExtension;
#[cfg(feature = "casper-native")]
use sc_chain_spec::ChainType;
use serde::{Deserialize, Serialize};
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::IdentifyAccount;
#[cfg(feature = "casper-native")]
use sp_runtime::Perbill;
#[cfg(feature = "casper-native")]
use telemetry::TelemetryEndpoints;
#[cfg(feature = "casper-native")]
const CASPER_TELEMETRY_URL: &str = "wss://telemetry.ghostchain.io/submit/";
#[cfg(feature = "casper-native")]
const DEFAULT_PROTOCOL_ID: &str = "cspr";
/// Node `ChainSpec` extensions.
///
/// Additional parameters for some substrate core modules,
/// customizable from the chain spec.
#[derive(Default, Clone, Serialize, Deserialize, ChainSpecExtension)]
#[serde(rename_all = "camelCase")]
pub struct Extensions {
/// Block number with known hashes.
pub fork_blocks: sc_client_api::ForkBlocks<primitives::Block>,
/// Known bad block hashes.
pub bad_blocks: sc_client_api::BadBlocks<primitives::Block>,
/// The light sync state.
/// This value will be set by the `sync-state rpc` implementation.
pub light_sync_state: sc_sync_state_rpc::LightSyncStateExtension,
}
// Generic chain spec, in case when we don't have the native runtime.
pub type GenericChainSpec = sc_service::GenericChainSpec<(), Extensions>;
/// The `ChainSpec` parametrized for the ghost runtime.
#[cfg(feature = "casper-native")]
pub type CasperChainSpec = sc_service::GenericChainSpec<(), Extensions>;
#[cfg(not(feature = "casper-native"))]
pub type CasperChainSpec = GenericChainSpec;
pub fn casper_config() -> Result<CasperChainSpec, String> {
CasperChainSpec::from_json_bytes(&include_bytes!("../chain-specs/casper.json")[..])
}
// #[derive(Encode, Clone)]
// struct PreparedNetworkData {
// chain_name: Vec<u8>,
// default_endpoint: Vec<u8>,
// finality_delay: Option<u64>,
// release_delay: Option<u64>,
// network_type: u8,
// gatekeeper: Vec<u8>,
// topic_name: Vec<u8>,
// incoming_fee: u32,
// outgoing_fee: u32,
// }
#[cfg(feature = "casper-native")]
fn casper_session_keys(
babe: BabeId,
grandpa: GrandpaId,
authority_discovery: AuthorityDiscoveryId,
slow_clap: SlowClapId,
) -> casper::opaque::SessionKeys {
casper::opaque::SessionKeys {
babe,
grandpa,
authority_discovery,
slow_clap,
}
}
pub fn casper_chain_spec_properties() -> serde_json::map::Map<String, serde_json::Value> {
serde_json::json!({
"ss58Format": 1996,
"tokenDecimals": 18,
"tokenSymbol": "CSPR",
})
.as_object()
.expect("Map given; qed")
.clone()
}
/// Helper function to generate a crypto pair from seed.
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}
/// Helper function to generate account ID from seed.
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Helper function to generate stash, controller and session key from seed
pub fn generate_authority_keys_from_seed(
seed: &str,
) -> (
AccountId,
AccountId,
BabeId,
GrandpaId,
AuthorityDiscoveryId,
SlowClapId,
) {
let keys = get_authority_keys_from_seed(seed);
(keys.0, keys.1, keys.2, keys.3, keys.4, keys.5)
}
/// Helper function to generate stash, controller and session key from seed
pub fn get_authority_keys_from_seed(
seed: &str,
) -> (
AccountId,
AccountId,
BabeId,
GrandpaId,
AuthorityDiscoveryId,
SlowClapId,
) {
(
get_account_id_from_seed::<sr25519::Public>(&format!("{}//stash", seed)),
get_account_id_from_seed::<sr25519::Public>(seed),
get_from_seed::<BabeId>(seed),
get_from_seed::<GrandpaId>(seed),
get_from_seed::<AuthorityDiscoveryId>(seed),
get_from_seed::<SlowClapId>(seed),
)
}
#[cfg(feature = "casper-native")]
fn casper_testnet_accounts() -> Vec<AccountId> {
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Feride"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Feride//stash"),
]
}
#[cfg(feature = "casper-native")]
fn casper_testnet_evm_accounts() -> Vec<(AccountId, u128, u8)> {
vec![
// 01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198
(get_account_id_from_seed::<sr25519::Public>("1A69d2D5568D1878023EeB121a73d33B9116A760"), 1337 * CSPR, 1),
// b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139
(get_account_id_from_seed::<sr25519::Public>("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12"), 1337 * CSPR, 2),
// d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc
(get_account_id_from_seed::<sr25519::Public>("e83f67361Ac74D42A48E2DAfb6706eb047D8218D"), 69 * CSPR, 3),
// c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4
(get_account_id_from_seed::<sr25519::Public>("827ee4ad9b259b6fa1390ed60921508c78befd63"), 69 * CSPR, 4),
]
}
#[cfg(feature = "casper-native")]
fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
vec![
(1, ghost_networks::NetworkData {
chain_name: "ethereum-mainnet".into(),
default_endpoint: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
finality_delay: Some(40u64),
release_delay: Some(80u64),
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0x4d224452801aced8b2f0aebe155379bb5d594381".into(),
topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".into(),
incoming_fee: 0u32,
outgoing_fee: 0u32,
}.encode()),
(56, ghost_networks::NetworkData {
chain_name: "bnb-mainnet".into(),
default_endpoint: "https://bsc-mainnet.core.chainstack.com/35848e183f3e3303c8cfeacbea831cab/".into(),
finality_delay: Some(20u64),
release_delay: Some(40u64),
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82".into(),
topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".into(),
incoming_fee: 0u32,
outgoing_fee: 0u32,
}.encode())
]
}
/// Helper function to create casper `GenesisConfig` for testing
#[cfg(feature = "casper-native")]
pub fn testnet_config_genesis(
initial_authorities: Vec<(
AccountId,
AccountId,
BabeId,
GrandpaId,
AuthorityDiscoveryId,
SlowClapId,
)>,
endowed_accounts: Option<Vec<AccountId>>,
ghost_accounts: Option<Vec<(AccountId, u128, u8)>>,
evm_networks: Option<Vec<(u32, Vec<u8>)>>,
) -> serde_json::Value {
let endowed_accounts: Vec<AccountId> = endowed_accounts
.unwrap_or_else(casper_testnet_accounts);
let ghost_accounts: Vec<(AccountId, u128, u8)> = ghost_accounts
.unwrap_or_default();
let evm_networks: Vec<(u32, Vec<u8>)> = evm_networks
.unwrap_or_default();
const ENDOWMENT: u128 = 1_000 * CSPR;
const STASH: u128 = 500 * CSPR;
serde_json::json!({
"balances": {
"balances": endowed_accounts
.iter()
.map(|k| (k.clone(), ENDOWMENT))
.chain(ghost_accounts
.iter()
.map(|k| (k.0.clone(), k.1.clone())))
.collect::<Vec<_>>(),
},
"session": {
"keys": initial_authorities
.iter()
.map(|x| {
(
x.0.clone(),
x.0.clone(),
casper_session_keys(
x.2.clone(),
x.3.clone(),
x.4.clone(),
x.5.clone(),
),
)
})
.collect::<Vec<_>>(),
},
"staking": {
"validatorCount": initial_authorities.len() as u32,
"minimumValidatorCount": 1,
"invulnerables": initial_authorities
.iter()
.map(|x| x.0.clone())
.collect::<Vec<_>>(),
"forceEra": Forcing::NotForcing,
"slashRewardFraction": Perbill::from_percent(10),
"stakers": initial_authorities
.iter()
.map(|x| (x.0.clone(), x.0.clone(), STASH, casper::StakerStatus::<AccountId>::Validator))
.collect::<Vec<_>>(),
},
"babe": {
"epochConfig": Some(casper::BABE_GENESIS_EPOCH_CONFIG),
},
"ghostNetworks": {
"networks": evm_networks,
},
"ghostClaims": {
"total": ghost_accounts.iter().fold(0, |acc, k| acc + k.1),
"membersAndRanks": ghost_accounts
.iter()
.map(|k| (k.0.clone(), k.2.clone()))
.collect::<Vec<_>>(),
},
})
}
#[cfg(feature = "casper-native")]
fn casper_staging_config_genesis() -> serde_json::Value {
use hex_literal::hex;
use sp_core::crypto::UncheckedInto;
// Following keys are used in genesis config for development chains.
// DO NOT use them in production chains as the secret seed is public.
//
// SECRET_SEED="fall cargo frown step audit cover various urge urge six pattern leisure"
// ghostkey inspect -n casper "$SECRET_SEED"
let endowed_accounts = vec![
// sfFmPT1hi3iySSwEdLpNRMJWo5pvFAKpfgjhDYAgL2i2qyEWx
hex!["5afaf4bba29ed7557a0112d9664c6c3d4acd96440f1b43f3bddeffdc2b3bc800"].into(),
];
// SECRET=$SECRET_SEED ./scripts/prepare-test-net.sh 4
let initial_authorities: Vec<(
AccountId,
AccountId,
BabeId,
GrandpaId,
AuthorityDiscoveryId,
SlowClapId,
)> = vec![
(
//sfEdnhKt7YcjUP8iuvxNqTqUu7YpbARBeqFjAPRMH6yFuuPco
hex!["28f303d3b1f821edda19bf6c97ee886edd85d7dc80e2500ab5f4888a19e40a50"].into(),
//sfJxZKUmPStRqKF1sq5dpdgeCSCx5zRVa53c4q6d8SgfUUf7W
hex!["e83494e12531b122043315d780c4b5b1153c52b7a94c42b5d61cd91b1f188e31"].into(),
//sfFJMwRUaHrHPFL48SqQbvr39HFYvhgX4YKRmrN61i5vqmxnJ
hex!["465e3f1220c774ba014defd7273c3a6e57336eb87c2bea9f04419c2eb6ee895c"].unchecked_into(),
//sfEpnU74Gr7bRfTBR7pEKZdxx6SRXmw55atd9x4uJSWRJMGby
hex!["3155f271b9ca868a2eb980e35f17ee13525cb59e90848c1b0cc2ff306956c916"].unchecked_into(),
//sfEM1Bj59N9gnscE7t6fqBF1xvR4wvhmrxfviCQYDfrTY9dvJ
hex!["1c25e311eade248d63ff2103d3a0bd8909ad618e5878b423c99bd043b47fd535"].unchecked_into(),
//sfFyrauZLXLR44mBB58i73ZTnsgSHBjbgGxtXwoDTH751LaHE
hex!["647d3fc5c00e3dd975838a92a72e06edc6d060c2e79e23672425da61812a8011"].unchecked_into(),
),
(
//sfJEs3nDW3aemaCWeSjeuFtiGR3Zx5nD3uMAPvLoRkATdUicY
hex!["c867f4f1417b0aa0c1cf9805866ea3e75d810a47a1ee8d302477768d95306542"].into(),
//sfHf6BwnPaRkMqLivmsTrHGWPQ1DsPM5pVzaeodUvpUGDEuhT
hex!["aea5d94e3837022ddd3b006d77d38b70b87ebaa5423b358b871a3e05d9157e77"].into(),
//sfDzomQME6PRxB5LTEJsLYz7wxJUNNAnMop88Uj4E3wWVyu9x
hex!["0cbe89b4ea4fd1d618f9d0db15522f2ca335893abb806a638c3e9bc43f022c78"].unchecked_into(),
//sfK6CJTmSa5cGk51KFibhvbm1di6EPBnefGeCzXcprUQVokeV
hex!["ee07cb1fd2fbc6b079ec3abb6c4866a35a3f1a25aef0bd5e50d8c188a98148c9"].unchecked_into(),
//sfK9Kq2pXUW5JZBMYSFRwKCWZoMEzqkq8wRVTtpo6zxdDENqG
hex!["f06ade37706f898adce54b09f7e973e718b20fbec06eebf34e6d23046aa51d63"].unchecked_into(),
//sfEBQtB12x7xi5RPGXJiLWugdwAdDBsYePwssMLFBtr43dZiC
hex!["14d534940143dc260894c7ebfd013a0d5c65c2cd85ae89decb32d663a2628e66"].unchecked_into(),
),
(
//sfF4sfGLNyVtYMYZbte6A6kcncFi4hG65vPpbftQZxcBVbavS
hex!["3c14dca7697cd193184708b00abf3c148c2d78eae6d8c102b84683ec6936123b"].into(),
//sfJUHCESTjHwXKmHbzhApCDRgzUTcP5kcUUCATeBaTUwtyx8X
hex!["d2a36dc75ef7933c2934b0855e2568a85c11347a48f0a1bfbcf1fc3757db1a07"].into(),
//sfGS5ypMSqG3VSWyhKghZzCxSUdp4JC3Qaw3eu2oe8iaSy1TM
hex!["787eb8a2780f422382474cfa7e44493fffd86824963a0da22d0f0c82f9d39860"].unchecked_into(),
//sfFH1EKd6KCqCJ9HPPW5oBr5gigsEKBkHtFT4GoBqu5iUdYzZ
hex!["45554a1b748fed1f2f51f06970c8cd764edbdefd82d697993ddfe7f97290918c"].unchecked_into(),
//sfG28QRqEgkAgvpjZc3N86xDTebiwKiSvKYfg1NdwW2GNDbP6
hex!["6638fe19b4331656dacf3be9d6a81506fa71db1fbe4bd9db0ab8c9cc0e364f1b"].unchecked_into(),
//sfFUfGqByAJGfe3e4vxiDJv5A1v1dp2piSNGpR8Kz5U9dFvMp
hex!["4e390dd2dad59ff8709e0cb714bfccdbadde8b4e91d5931cb98ba6e6eb48a93b"].unchecked_into(),
),
(
//sfG7zdnf5t6JHbi9tBfkKesz13x7B9mSiYwDJfnDQ1LQwXwAi
hex!["6ab24f598a38e1d91004487faedadc8c338a7cb2a07e29899eccc7d106a2195e"].into(),
//sfDu1voz5vmiKXeiCHutmCp96C6LqLogsWE4rkaUZeZyhdt1B
hex!["085401d14ff3c620c76347a9e9a7e020fd3575d081c8352728db56ea6cc52677"].into(),
//sfH9hH4P98SohVs3Aj4cBoDXZvgYbF8dPXi3NfyEng5eMry9G
hex!["983a9aa148f94a54f313aca8537fb00f3c3353f70fafa8c14d4de22b44366f3c"].unchecked_into(),
//sfJQChmUKaDDQgzsAyZvuRNQZxV4CQ2qmxzmZk27tdWczKtRa
hex!["cf875474e8dfe94f4e9e0e2a4743e02c18cebf87b2c763710c9630f3fc94c9c4"].unchecked_into(),
//sfEMDH3w5xvZCwhXaMKYV7hsSL36evqHhqianntoiNDEtewLT
hex!["1c4e97776053b47b5b48035bab5f5f4afb3e6e13b15d1964195502cf40124c2a"].unchecked_into(),
//sfEPb5wWLKAHZH8k8KXpBtfnbBQPBBTkyv2ZQ1YP3GRKKpP1w
hex!["1e1e7f0781828178bd1237d9a8c2e057bbb15f2f46d1fc5fb316ebd9f5d1ad04"].unchecked_into(),
),
];
let ghost_accounts: Vec<(AccountId, u128, u8)> = casper_testnet_evm_accounts();
let evm_networks = casper_testnet_evm_networks();
const ENDOWMENT: u128 = 5_000 * CSPR;
const STASH: u128 = 500 * CSPR;
serde_json::json!({
"balances": {
"balances": endowed_accounts
.iter()
.map(|k: &AccountId| (k.clone(), ENDOWMENT))
.chain(initial_authorities.iter().map(|x| (x.0.clone(), STASH)))
.collect::<Vec<_>>(),
},
"session": {
"keys": initial_authorities
.iter()
.map(|x| {
(
x.0.clone(),
x.0.clone(),
casper_session_keys(
x.2.clone(),
x.3.clone(),
x.4.clone(),
x.5.clone(),
),
)
})
.collect::<Vec<_>>(),
},
"staking": {
"validatorCount": 50,
"minimumValidatorCount": 4,
"stakers": initial_authorities
.iter()
.map(|x| {
(
x.0.clone(),
x.0.clone(),
STASH,
casper::StakerStatus::<AccountId>::Validator,
)
})
.collect::<Vec<_>>(),
"invulnerables": initial_authorities.iter().map(|x| x.0.clone()).collect::<Vec<_>>(),
"forceEra": Forcing::ForceNone,
"slashRewardFraction": Perbill::from_percent(10)
},
"babe": {
"epochConfig": Some(casper::BABE_GENESIS_EPOCH_CONFIG),
},
"ghostNetworks": {
"networks": evm_networks,
},
"ghostClaims": {
"total": ghost_accounts
.iter()
.fold(0, |acc, k| acc + k.1),
"membersAndRanks": ghost_accounts
.iter()
.map(|k| (k.0.clone(), k.2.clone()))
.collect::<Vec<_>>(),
},
})
}
#[cfg(feature = "casper-native")]
fn casper_development_config_genesis() -> serde_json::Value {
testnet_config_genesis(
vec![get_authority_keys_from_seed("Alice")],
None, None, None,
)
}
#[cfg(feature = "casper-native")]
fn casper_local_config_genesis() -> serde_json::Value {
testnet_config_genesis(
vec![
get_authority_keys_from_seed("Alice"),
get_authority_keys_from_seed("Bob"),
],
Some(casper_testnet_accounts()),
Some(casper_testnet_evm_accounts()),
Some(casper_testnet_evm_networks()),
)
}
#[cfg(feature = "casper-native")]
pub fn casper_development_config() -> Result<CasperChainSpec, String> {
Ok(CasperChainSpec::builder(
casper::WASM_BINARY.ok_or("Casper development wasm not available")?,
Default::default(),
)
.with_name("Development")
.with_id("casper_dev")
.with_chain_type(ChainType::Development)
.with_genesis_config_patch(casper_development_config_genesis())
.with_protocol_id(DEFAULT_PROTOCOL_ID)
.build())
}
#[cfg(feature = "casper-native")]
pub fn casper_local_testnet_config() -> Result<CasperChainSpec, String> {
Ok(CasperChainSpec::builder(
casper::WASM_BINARY.ok_or("Casper local testnet wasm not available")?,
Default::default(),
)
.with_name("Casper Local Testnet")
.with_id("casper_local_testnet")
.with_chain_type(ChainType::Local)
.with_genesis_config_patch(casper_local_config_genesis())
.with_protocol_id(DEFAULT_PROTOCOL_ID)
.build())
}
#[cfg(feature = "casper-native")]
pub fn casper_staging_testnet_config() -> Result<CasperChainSpec, String> {
Ok(CasperChainSpec::builder(
casper::WASM_BINARY.ok_or("Casper staging testnet wasm not available")?,
Default::default(),
)
.with_name("Casper Staging Testnet")
.with_id("casper_staging_testnet")
.with_chain_type(ChainType::Live)
.with_genesis_config_patch(casper_staging_config_genesis())
.with_telemetry_endpoints(
TelemetryEndpoints::new(vec![(CASPER_TELEMETRY_URL.to_string(), 0)])
.expect("Casper Staging telemetry url is valid; qed"),
)
.with_protocol_id(DEFAULT_PROTOCOL_ID)
.build())
}

760
service/src/lib.rs Executable file
View File

@@ -0,0 +1,760 @@
#![deny(unused_results)]
pub mod benchmarking;
pub mod chain_spec;
#[cfg(feature = "full-node")]
use {
grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider},
sc_client_api::BlockBackend,
tx_pool_api::OffchainTransactionPoolFactory,
sp_blockchain::HeaderBackend,
sc_service::{KeystoreContainer, RpcHandlers},
telemetry::{Telemetry, TelemetryWorkerHandle},
};
use std::{sync::Arc, time::Duration};
use telemetry::TelemetryWorker;
use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
pub use chain_spec::GenericChainSpec;
pub use consensus_common::{Proposal, SelectChain};
pub use primitives::{Block, BlockId, BlockNumber, Hash};
pub use sc_client_api::{Backend, CallExecutor};
pub use sc_consensus::BlockImport;
pub use sc_executor::NativeExecutionDispatch;
pub use sp_api::{ApiRef, ConstructRuntimeApi, Core as CoreApi, ProvideRuntimeApi};
pub use sc_service::{
config::{DatabaseSource, PrometheusConfig},
ChainSpec, Configuration, Error as SubstrateServiceError, PruningMode, Role,
RuntimeGenesis, TFullBackend, TFullCallExecutor, TFullClient, TaskManager,
TransactionPoolOptions,
};
pub use sp_runtime::{
generic,
traits::{
self as runtime_traits, BlakeTwo256, Block as BlockT, Header as HeaderT,
NumberFor,
},
};
#[cfg(feature = "casper-native")]
pub use chain_spec::CasperChainSpec;
#[cfg(feature = "casper-native")]
pub use {casper_runtime, casper_runtime_constants};
#[cfg(feature = "casper-native")]
use casper_runtime::RuntimeApi;
#[cfg(feature = "full-node")]
pub type FullBackend = sc_service::TFullBackend<Block>;
#[cfg(feature = "full-node")]
pub type FullClient = sc_service::TFullClient<
Block,
RuntimeApi,
WasmExecutor<(
sp_io::SubstrateHostFunctions,
frame_benchmarking::benchmarking::HostFunctions,
)>,
>;
const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512;
pub trait HeaderProvider<Block, Error = sp_blockchain::Error>: Send + Sync + 'static
where
Block: BlockT,
Error: std::fmt::Debug + Send + Sync + 'static,
{
fn header(
&self,
hash: <Block as BlockT>::Hash,
) -> Result<Option<<Block as BlockT>::Header>, Error>;
fn number(
&self,
hash: <Block as BlockT>::Hash,
) -> Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>, Error>;
}
impl<Block, T> HeaderProvider<Block> for T
where
Block: BlockT,
T: sp_blockchain::HeaderBackend<Block> + 'static,
{
fn header(
&self,
hash: Block::Hash,
) -> sp_blockchain::Result<Option<<Block as BlockT>::Header>> {
<Self as sp_blockchain::HeaderBackend<Block>>::header(self, hash)
}
fn number(
&self,
hash: Block::Hash,
) -> sp_blockchain::Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>> {
<Self as sp_blockchain::HeaderBackend<Block>>::number(self, hash)
}
}
pub trait HeaderProviderProvider<Block>: Send + Sync + 'static
where
Block: BlockT,
{
type Provider: HeaderProvider<Block> + 'static;
fn header_provider(&self) -> &Self::Provider;
}
impl<Block, T> HeaderProviderProvider<Block> for T
where
Block: BlockT,
T: sc_client_api::Backend<Block> + 'static,
{
type Provider = <T as sc_client_api::Backend<Block>>::Blockchain;
fn header_provider(&self) -> &Self::Provider {
self.blockchain()
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
AddrFormatInvalid(#[from] std::net::AddrParseError),
#[error(transparent)]
Sub(#[from] SubstrateServiceError),
#[error(transparent)]
Blockchain(#[from] sp_blockchain::Error),
#[error(transparent)]
Consensus(#[from] consensus_common::Error),
#[error(transparent)]
Prometheus(#[from] prometheus_endpoint::PrometheusError),
#[error(transparent)]
Telemetry(#[from] telemetry::Error),
#[cfg(feature = "full-node")]
#[error("Creating a custom database is required for validators")]
DatabasePathRequired,
#[cfg(feature = "full-node")]
#[error("Expected at least one of ghost or casper runtime feature")]
NoRuntime,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Chain {
Ghost,
Casper,
Unknown,
}
pub trait IdentifyVariant {
fn is_ghost(&self) -> bool;
fn is_casper(&self) -> bool;
fn is_dev(&self) -> bool;
fn identify_chain(&self) -> Chain;
}
impl IdentifyVariant for Box<dyn ChainSpec> {
fn is_ghost(&self) -> bool {
self.id().starts_with("ghost")
}
fn is_casper(&self) -> bool {
self.id().starts_with("casper")
}
fn is_dev(&self) -> bool {
self.id().ends_with("dev")
}
fn identify_chain(&self) -> Chain {
if self.is_ghost() { Chain::Ghost }
else if self.is_casper() { Chain::Casper }
else { Chain::Unknown }
}
}
#[cfg(feature = "full-node")]
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
#[cfg(feature = "full-node")]
type FullGrandpaBlockImport<ChainSelection = FullSelectChain> =
grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, ChainSelection>;
#[cfg(feature = "full-node")]
struct Basics {
task_manager: TaskManager,
client: Arc<FullClient>,
backend: Arc<FullBackend>,
keystore_container: KeystoreContainer,
telemetry: Option<Telemetry>,
}
#[cfg(feature = "full-node")]
fn new_partial_basics(
config: &mut Configuration,
telemetry_worker_handle: Option<TelemetryWorkerHandle>,
) -> Result<Basics, Error> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(move |endpoints| -> Result<_, telemetry::Error> {
let (worker, mut worker_handle) = if let Some(worker_handle) = telemetry_worker_handle {
(None, worker_handle)
} else {
let worker = TelemetryWorker::new(16)?;
let worker_handle = worker.handle();
(Some(worker), worker_handle)
};
let telemetry = worker_handle.new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let heap_pages = config
.default_heap_pages
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
let executor = WasmExecutor::builder()
.with_execution_method(config.wasm_method)
.with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages)
.with_max_runtime_instances(config.max_runtime_instances)
.with_runtime_cache_size(config.runtime_cache_size)
.build();
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
&config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
let client = Arc::new(client);
let telemetry = telemetry.map(|(worker, telemetry)| {
if let Some(worker) = worker {
task_manager.spawn_handle().spawn(
"telemetry",
Some("telemetry"),
Box::pin(worker.run()),
);
}
telemetry
});
Ok(Basics { task_manager, client, backend, keystore_container, telemetry })
}
#[cfg(feature = "full-node")]
fn new_partial<ChainSelection>(
config: &mut Configuration,
Basics { task_manager, backend, client, keystore_container, telemetry }: Basics,
select_chain: ChainSelection,
) -> Result<
sc_service::PartialComponents<
FullClient,
FullBackend,
ChainSelection,
sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, FullClient>,
(
impl Fn(
ghost_rpc::DenyUnsafe,
ghost_rpc::SubscriptionTaskExecutor,
) -> Result<ghost_rpc::RpcExtension, SubstrateServiceError>,
(
babe::BabeBlockImport<
Block,
FullClient,
FullGrandpaBlockImport<ChainSelection>,
>,
grandpa::LinkHalf<Block, FullClient, ChainSelection>,
babe::BabeLink<Block>,
),
grandpa::SharedVoterState,
Option<Telemetry>,
),
>,
Error,
>
where
ChainSelection: 'static + SelectChain<Block>,
{
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(),
config.role.is_authority().into(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
);
let (grandpa_block_import, grandpa_link) =
grandpa::block_import(
client.clone(),
GRANDPA_JUSTIFICATION_PERIOD,
&(client.clone() as Arc<_>),
select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()),
)?;
let justification_import = grandpa_block_import.clone();
let babe_config = babe::configuration(&*client)?;
let (block_import, babe_link) =
babe::block_import(babe_config.clone(), grandpa_block_import, client.clone())?;
let slot_duration = babe_link.config().slot_duration();
let (import_queue, babe_worker_handle) =
babe::import_queue(babe::ImportQueueParams {
link: babe_link.clone(),
block_import: block_import.clone(),
justification_import: Some(Box::new(justification_import)),
client: client.clone(),
select_chain: select_chain.clone(),
create_inherent_data_providers: move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
babe_primitives::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
spawner: &task_manager.spawn_essential_handle(),
registry: config.prometheus_registry(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()),
})?;
let justification_stream = grandpa_link.justification_stream();
let shared_authority_set = grandpa_link.shared_authority_set().clone();
let shared_voter_state = grandpa::SharedVoterState::empty();
let finality_proof_provider = GrandpaFinalityProofProvider::new_for_service(
backend.clone(),
Some(shared_authority_set.clone()),
);
let import_setup = (block_import, grandpa_link, babe_link);
let rpc_setup = shared_voter_state.clone();
let rpc_extensions_builder = {
let client = client.clone();
let keystore = keystore_container.keystore();
let transaction_pool = transaction_pool.clone();
let select_chain = select_chain.clone();
let chain_spec = config.chain_spec.cloned_box();
let backend = backend.clone();
move |
deny_unsafe,
subscription_executor: ghost_rpc::SubscriptionTaskExecutor,
| -> Result<ghost_rpc::RpcExtension, sc_service::Error> {
let deps = ghost_rpc::FullDeps {
client: client.clone(),
pool: transaction_pool.clone(),
select_chain: select_chain.clone(),
chain_spec: chain_spec.cloned_box(),
deny_unsafe,
babe: ghost_rpc::BabeDeps {
babe_worker_handle: babe_worker_handle.clone(),
keystore: keystore.clone(),
},
grandpa: ghost_rpc::GrandpaDeps {
shared_voter_state: shared_voter_state.clone(),
shared_authority_set: shared_authority_set.clone(),
justification_stream: justification_stream.clone(),
subscription_executor: subscription_executor.clone(),
finality_provider: finality_proof_provider.clone(),
},
backend: backend.clone(),
};
ghost_rpc::create_full_rpc(deps).map_err(Into::into)
}
};
Ok(sc_service::PartialComponents {
client,
backend,
task_manager,
keystore_container,
select_chain,
import_queue,
transaction_pool,
other: (rpc_extensions_builder, import_setup, rpc_setup, telemetry),
})
}
#[cfg(feature = "full-node")]
pub struct NewFullParams {
/// Whether to enable the block authoring backoff on production networks
/// where it isn't enabled by default.
pub force_authoring_backoff: bool,
pub telemetry_worker_handle: Option<TelemetryWorkerHandle>,
pub hwbench: Option<sc_sysinfo::HwBench>,
}
#[cfg(feature = "full-node")]
pub struct NewFull {
pub task_manager: TaskManager,
pub client: Arc<FullClient>,
pub network: Arc<dyn sc_network::service::traits::NetworkService>,
pub sync_service: Arc<sc_network_sync::SyncingService<Block>>,
pub rpc_handlers: RpcHandlers,
pub backend: Arc<FullBackend>,
}
#[cfg(feature = "full-node")]
pub fn new_full<Network: sc_network::NetworkBackend<Block, <Block as BlockT>::Hash>>(
mut config: Configuration,
NewFullParams {
force_authoring_backoff,
telemetry_worker_handle,
hwbench,
}: NewFullParams,
) -> Result<NewFull, Error> {
use sc_network_sync::WarpSyncParams;
let role = config.role.clone();
let force_authoring = config.force_authoring;
let backoff_authoring_blocks = if !force_authoring_backoff {
None
} else {
let mut backoff =
sc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging::default();
if config.chain_spec.is_dev() {
backoff.max_interval = 10;
}
Some(backoff)
};
let disable_grandpa = config.disable_grandpa;
let name = config.network.node_name.clone();
let basics = new_partial_basics(&mut config, telemetry_worker_handle)?;
let prometheus_registry = config.prometheus_registry().cloned();
let select_chain = sc_consensus::LongestChain::new(basics.backend.clone());
let sc_service::PartialComponents::<_, _, sc_consensus::LongestChain<FullBackend, Block>, _, _, _,> {
client,
backend,
mut task_manager,
keystore_container,
select_chain,
import_queue,
transaction_pool,
other: (
rpc_extensions_builder,
import_setup,
rpc_setup,
mut telemetry,
),
} = new_partial::<sc_consensus::LongestChain<FullBackend, Block>>(
&mut config,
basics,
select_chain,
)?;
let metrics = Network::register_notification_metrics(
config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
);
let shared_voter_state = rpc_setup;
let auth_disc_publish_non_global_ips = config.network.allow_non_globals_in_dht;
let auth_disc_public_addresses = config.network.public_addresses.clone();
let mut net_config =
sc_network::config::FullNetworkConfiguration::<_, _, Network>::new(&config.network);
let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed");
let peer_store_handle = net_config.peer_store_handle();
let grandpa_protocol_name = grandpa::protocol_standard_name(&genesis_hash, &config.chain_spec);
let (grandpa_protocol_config, grandpa_notification_service) =
grandpa::grandpa_peers_set_config::<_, Network>(
grandpa_protocol_name.clone(),
metrics.clone(),
Arc::clone(&peer_store_handle),
);
net_config.add_notification_protocol(grandpa_protocol_config);
let warp_sync = Arc::new(grandpa::warp_proof::NetworkProvider::new(
backend.clone(),
import_setup.1.shared_authority_set().clone(),
Vec::new(),
));
let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
sc_service::build_network(sc_service::BuildNetworkParams {
config: &config,
net_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue,
block_announce_validator_builder: None,
warp_sync_params: Some(WarpSyncParams::WithProvider(warp_sync)),
block_relay: None,
metrics,
})?;
if config.offchain_worker.enabled {
use futures::FutureExt;
task_manager.spawn_handle().spawn(
"offchain-workers-runner",
"offchain-worker",
sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
runtime_api_provider: client.clone(),
keystore: Some(keystore_container.keystore()),
offchain_db: backend.offchain_storage(),
transaction_pool: Some(OffchainTransactionPoolFactory::new(
transaction_pool.clone(),
)),
network_provider: Arc::new(network.clone()),
is_validator: role.is_authority(),
enable_http_requests: true,
custom_extensions: move |_| vec![],
})
.run(client.clone(), task_manager.spawn_handle())
.boxed(),
);
}
let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
config,
backend: backend.clone(),
client: client.clone(),
keystore: keystore_container.keystore(),
network: network.clone(),
sync_service: sync_service.clone(),
rpc_builder: Box::new(rpc_extensions_builder),
transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager,
system_rpc_tx,
tx_handler_controller,
telemetry: telemetry.as_mut(),
})?;
if let Some(hwbench) = hwbench {
sc_sysinfo::print_hwbench(&hwbench);
match ghost_machine_primitives::GHOST_NODE_REFERENCE_HARDWARE.check_hardware(&hwbench) {
Err(err) if role.is_authority() => {
log::warn!(
"⚠️ The hardware does not meet the minimal requirements {} for role 'Authority'",
err
);
},
_ => {},
}
if let Some(ref mut telemetry) = telemetry {
let telemetry_handle = telemetry.handle();
task_manager.spawn_handle().spawn(
"telemetry_hwbench",
None,
sc_sysinfo::initialize_hwbench_telemetry(
telemetry_handle,
hwbench,
),
);
}
}
let (block_import, link_half, babe_link) = import_setup;
if role.is_authority() {
use futures::StreamExt;
use sc_network::{Event, NetworkEventStream};
let authority_discovery_role =
sc_authority_discovery::Role::PublishAndDiscover(keystore_container.keystore());
let dht_event_stream =
network.event_stream("authority-discovery").filter_map(|e| async move {
match e {
Event::Dht(e) => Some(e),
_ => None,
}
});
let (worker, _service) = sc_authority_discovery::new_worker_and_service_with_config(
sc_authority_discovery::WorkerConfig {
publish_non_global_ips: auth_disc_publish_non_global_ips,
public_addresses: auth_disc_public_addresses,
strict_record_validation: true,
..Default::default()
},
client.clone(),
Arc::new(network.clone()),
Box::pin(dht_event_stream),
authority_discovery_role,
prometheus_registry.clone()
);
task_manager.spawn_handle().spawn(
"authority-discovery-worker",
Some("authority-discovery"),
Box::pin(worker.run()),
);
}
if role.is_authority() {
let proposer = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(),
client.clone(),
transaction_pool.clone(),
prometheus_registry.as_ref(),
telemetry.as_ref().map(|x| x.handle()),
);
let slot_duration = babe_link.config().slot_duration();
let babe_config = babe::BabeParams {
keystore: keystore_container.keystore(),
client: client.clone(),
select_chain,
block_import,
env: proposer,
sync_oracle: sync_service.clone(),
justification_sync_link: sync_service.clone(),
create_inherent_data_providers: move |_, ()| {
async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
babe_primitives::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
}
},
force_authoring,
backoff_authoring_blocks,
babe_link,
block_proposal_slot_portion: babe::SlotProportion::new(2f32 / 3f32),
max_block_proposal_slot_portion: None,
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
let babe = babe::start_babe(babe_config)?;
task_manager.spawn_essential_handle().spawn_blocking("babe", None, babe);
}
let keystore_opt = if role.is_authority() {
Some(keystore_container.keystore())
} else {
None
};
let config = grandpa::Config {
gossip_duration: Duration::from_millis(1000),
justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD,
name: Some(name),
observer_enabled: false,
keystore: keystore_opt,
local_role: role,
telemetry: telemetry.as_ref().map(|x| x.handle()),
protocol_name: grandpa_protocol_name,
};
let enable_grandpa = !disable_grandpa;
if enable_grandpa {
let voting_rules_builder = grandpa::VotingRulesBuilder::default();
let granpda_config = grandpa::GrandpaParams {
config,
link: link_half,
network: network.clone(),
sync: sync_service.clone(),
voting_rule: voting_rules_builder.build(),
prometheus_registry: prometheus_registry.clone(),
shared_voter_state,
telemetry: telemetry.as_ref().map(|x| x.handle()),
notification_service: grandpa_notification_service,
offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()),
};
task_manager.spawn_essential_handle().spawn_blocking(
"granpda-voter",
None,
grandpa::run_grandpa_voter(granpda_config)?,
);
}
network_starter.start_network();
Ok(NewFull {
task_manager,
client,
network,
sync_service,
rpc_handlers,
backend,
})
}
#[cfg(feature = "full-node")]
macro_rules! chain_ops {
($config:expr, $telemetry_worker_handle:expr) => {{
let telemetry_worker_handle = $telemetry_worker_handle;
let mut config = $config;
let basics = new_partial_basics(config, telemetry_worker_handle)?;
let chain_selection = sc_consensus::LongestChain::new(basics.backend.clone());
let sc_service::PartialComponents { client, backend, import_queue, task_manager, .. } =
new_partial::<sc_consensus::LongestChain<FullBackend, Block>>(&mut config, basics, chain_selection)?;
Ok((client, backend, import_queue, task_manager))
}};
}
#[cfg(feature = "full-node")]
pub fn new_chain_ops(
config: &mut Configuration,
) -> Result<(Arc<FullClient>, Arc<FullBackend>, sc_consensus::BasicQueue<Block>, TaskManager), Error>
{
config.keystore = sc_service::config::KeystoreConfig::InMemory;
chain_ops!(config, None)
}
#[cfg(feature = "full-node")]
pub fn build_full(
config: Configuration,
params: NewFullParams,
) -> Result<NewFull, Error> {
match config.network.network_backend {
sc_network::config::NetworkBackendType::Libp2p =>
new_full::<sc_network::NetworkWorker<Block, Hash>>(config, params),
sc_network::config::NetworkBackendType::Litep2p =>
new_full::<sc_network::Litep2pNetworkBackend>(config, params),
}
}
#[cfg(feature = "full-node")]
pub fn revert_backend(
client: Arc<FullClient>,
backend: Arc<FullBackend>,
blocks: BlockNumber,
) -> Result<(), Error> {
let best_number = client.info().best_number;
let finalized = client.info().finalized_number;
let revertible = blocks.min(best_number - finalized);
if revertible == 0 {
return Ok(())
}
babe::revert(client.clone(), backend, blocks)?;
grandpa::revert(client, blocks)?;
Ok(())
}