mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-08 04:09:23 +00:00
Add an initial Substrate instantiation
Consensus has been nuked for an AcceptAny currently routed throough PoW (when it doesn't have to be, doing so just took care of a few pieces of leg work). Updates AGPL handling.
This commit is contained in:
33
substrate/consensus/Cargo.toml
Normal file
33
substrate/consensus/Cargo.toml
Normal file
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "serai-consensus"
|
||||
version = "0.1.0"
|
||||
description = "Serai consensus module"
|
||||
license = "AGPL-3.0-only"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
sp-core = { version = "6.0.0", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-trie = { version = "6.0.0", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-timestamp = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-consensus = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-consensus = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-transaction-pool = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-basic-authorship = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-consensus-pow = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-consensus-pow = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
sc-network = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-service = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai", features = ["wasmtime"] }
|
||||
sc-executor = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai", features = ["wasmtime"] }
|
||||
sp-runtime = { version = "6.0.0", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
substrate-prometheus-endpoint = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
sc-client-api = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-api = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
serai-runtime = { path = "../runtime" }
|
||||
|
||||
tokio = "1.15"
|
||||
15
substrate/consensus/LICENSE
Normal file
15
substrate/consensus/LICENSE
Normal file
@@ -0,0 +1,15 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2022 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
published by the Free Software Foundation.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
27
substrate/consensus/src/algorithm.rs
Normal file
27
substrate/consensus/src/algorithm.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use sp_core::U256;
|
||||
|
||||
use sc_consensus_pow::{Error, PowAlgorithm};
|
||||
use sp_consensus_pow::Seal;
|
||||
|
||||
use sp_runtime::{generic::BlockId, traits::Block as BlockT};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AcceptAny;
|
||||
impl<B: BlockT> PowAlgorithm<B> for AcceptAny {
|
||||
type Difficulty = U256;
|
||||
|
||||
fn difficulty(&self, _: B::Hash) -> Result<Self::Difficulty, Error<B>> {
|
||||
Ok(U256::one())
|
||||
}
|
||||
|
||||
fn verify(
|
||||
&self,
|
||||
_: &BlockId<B>,
|
||||
_: &B::Hash,
|
||||
_: Option<&[u8]>,
|
||||
_: &Seal,
|
||||
_: Self::Difficulty,
|
||||
) -> Result<bool, Error<B>> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
137
substrate/consensus/src/lib.rs
Normal file
137
substrate/consensus/src/lib.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use substrate_prometheus_endpoint::Registry;
|
||||
|
||||
use sc_consensus_pow as sc_pow;
|
||||
use sc_client_api::call_executor::ExecutorProvider;
|
||||
use sc_executor::NativeElseWasmExecutor;
|
||||
use sc_service::TaskManager;
|
||||
|
||||
use serai_runtime::{self, opaque::Block, RuntimeApi};
|
||||
|
||||
mod algorithm;
|
||||
|
||||
pub struct ExecutorDispatch;
|
||||
impl sc_executor::NativeExecutionDispatch for ExecutorDispatch {
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
|
||||
#[cfg(not(feature = "runtime-benchmarks"))]
|
||||
type ExtendHostFunctions = ();
|
||||
|
||||
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
|
||||
serai_runtime::api::dispatch(method, data)
|
||||
}
|
||||
|
||||
fn native_version() -> sc_executor::NativeVersion {
|
||||
serai_runtime::native_version()
|
||||
}
|
||||
}
|
||||
|
||||
pub type FullClient = sc_service::TFullClient<
|
||||
Block,
|
||||
RuntimeApi,
|
||||
NativeElseWasmExecutor<ExecutorDispatch>
|
||||
>;
|
||||
|
||||
type Db = sp_trie::PrefixedMemoryDB<sp_runtime::traits::BlakeTwo256>;
|
||||
|
||||
pub fn import_queue<S: sp_consensus::SelectChain<Block> + 'static>(
|
||||
task_manager: &TaskManager,
|
||||
client: Arc<FullClient>,
|
||||
select_chain: S,
|
||||
registry: Option<&Registry>
|
||||
) -> Result<sc_pow::PowImportQueue<Block, Db>, sp_consensus::Error> {
|
||||
let pow_block_import = Box::new(
|
||||
sc_pow::PowBlockImport::new(
|
||||
client.clone(),
|
||||
client.clone(),
|
||||
algorithm::AcceptAny,
|
||||
0,
|
||||
select_chain.clone(),
|
||||
|_, _| { async { Ok(sp_timestamp::InherentDataProvider::from_system_time()) } },
|
||||
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone())
|
||||
)
|
||||
);
|
||||
|
||||
sc_pow::import_queue(
|
||||
pow_block_import,
|
||||
None,
|
||||
algorithm::AcceptAny,
|
||||
&task_manager.spawn_essential_handle(),
|
||||
registry
|
||||
)
|
||||
}
|
||||
|
||||
// Produce a block every 5 seconds
|
||||
async fn produce<
|
||||
Block: sp_api::BlockT<Hash = sp_core::H256>,
|
||||
Algorithm: sc_pow::PowAlgorithm<Block, Difficulty = sp_core::U256> +
|
||||
'static + Send + std::marker::Sync,
|
||||
C: sp_api::ProvideRuntimeApi<Block> + 'static,
|
||||
Link: sc_consensus::JustificationSyncLink<Block> + 'static,
|
||||
P: Send + 'static
|
||||
>(worker: sc_pow::MiningHandle<Block, Algorithm, C, Link, P>)
|
||||
where sp_api::TransactionFor<C, Block>: Send + 'static {
|
||||
loop {
|
||||
let worker_clone = worker.clone();
|
||||
std::thread::spawn(move || {
|
||||
tokio::runtime::Runtime::new().unwrap().handle().block_on(
|
||||
async { worker_clone.submit(vec![]).await; }
|
||||
);
|
||||
});
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// If we're an authority, produce blocks
|
||||
pub fn authority<S: sp_consensus::SelectChain<Block> + 'static>(
|
||||
task_manager: &TaskManager,
|
||||
client: Arc<FullClient>,
|
||||
network: Arc<sc_network::NetworkService<Block, <Block as sp_runtime::traits::Block>::Hash>>,
|
||||
pool: Arc<sc_transaction_pool::FullPool<Block, FullClient>>,
|
||||
select_chain: S,
|
||||
registry: Option<&Registry>
|
||||
) {
|
||||
let proposer = sc_basic_authorship::ProposerFactory::new(
|
||||
task_manager.spawn_handle(),
|
||||
client.clone(),
|
||||
pool,
|
||||
registry,
|
||||
None
|
||||
);
|
||||
|
||||
let can_author_with = sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());
|
||||
|
||||
let pow_block_import = Box::new(sc_pow::PowBlockImport::new(
|
||||
client.clone(),
|
||||
client.clone(),
|
||||
algorithm::AcceptAny,
|
||||
0, // Block to start checking inherents at
|
||||
select_chain.clone(),
|
||||
move |_, _| { async { Ok(sp_timestamp::InherentDataProvider::from_system_time()) } },
|
||||
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone())
|
||||
));
|
||||
|
||||
let (worker, worker_task) = sc_pow::start_mining_worker(
|
||||
pow_block_import,
|
||||
client,
|
||||
select_chain,
|
||||
algorithm::AcceptAny,
|
||||
proposer,
|
||||
network.clone(),
|
||||
network.clone(),
|
||||
None,
|
||||
move |_, _| { async { Ok(sp_timestamp::InherentDataProvider::from_system_time()) } },
|
||||
Duration::from_secs(1),
|
||||
Duration::from_secs(2),
|
||||
can_author_with
|
||||
);
|
||||
|
||||
task_manager
|
||||
.spawn_essential_handle()
|
||||
.spawn_blocking("pow", None, worker_task);
|
||||
|
||||
task_manager
|
||||
.spawn_essential_handle()
|
||||
.spawn("producer", None, produce(worker));
|
||||
}
|
||||
60
substrate/node/Cargo.toml
Normal file
60
substrate/node/Cargo.toml
Normal file
@@ -0,0 +1,60 @@
|
||||
[package]
|
||||
name = "serai-node"
|
||||
version = "0.1.0"
|
||||
description = "Serai network node, built over Substrate"
|
||||
license = "AGPL-3.0-only"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[[bin]]
|
||||
name = "serai-node"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "3.1.18", features = ["derive"] }
|
||||
|
||||
sc-cli = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai", features = ["wasmtime"] }
|
||||
sp-core = { version = "6.0.0", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-executor = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai", features = ["wasmtime"] }
|
||||
sc-service = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai", features = ["wasmtime"] }
|
||||
sc-telemetry = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-keystore = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-transaction-pool = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-transaction-pool-api = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-consensus = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-client-api = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-runtime = { version = "6.0.0", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-timestamp = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-inherents = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-keyring = { version = "6.0.0", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
frame-system = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
# These dependencies are used for the node template's RPCs
|
||||
jsonrpsee = { version = "0.14.0", features = ["server"] }
|
||||
sc-rpc = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-api = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sc-rpc-api = { version = "0.10.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-blockchain = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-block-builder = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
substrate-frame-rpc-system = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
pallet-transaction-payment-rpc = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
# These dependencies are used for runtime benchmarking
|
||||
frame-benchmarking = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
frame-benchmarking-cli = { version = "4.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
# Local dependencies
|
||||
serai-consensus = { path = "../consensus" }
|
||||
serai-runtime = { path = "../runtime" }
|
||||
|
||||
# CLI-specific dependencies
|
||||
try-runtime-cli = { version = "0.10.0-dev", optional = true, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
[build-dependencies]
|
||||
substrate-build-script-utils = { version = "3.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
runtime-benchmarks = ["serai-runtime/runtime-benchmarks"]
|
||||
try-runtime = ["serai-runtime/try-runtime", "try-runtime-cli"]
|
||||
15
substrate/node/LICENSE
Normal file
15
substrate/node/LICENSE
Normal file
@@ -0,0 +1,15 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2022 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
published by the Free Software Foundation.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
5
substrate/node/build.rs
Normal file
5
substrate/node/build.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
use substrate_build_script_utils::generate_cargo_keys;
|
||||
|
||||
fn main() {
|
||||
generate_cargo_keys();
|
||||
}
|
||||
74
substrate/node/src/chain_spec.rs
Normal file
74
substrate/node/src/chain_spec.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use sc_service::ChainType;
|
||||
|
||||
use sp_runtime::traits::Verify;
|
||||
use sp_core::{sr25519, Pair, Public};
|
||||
|
||||
use sp_runtime::traits::IdentifyAccount;
|
||||
|
||||
use serai_runtime::{
|
||||
WASM_BINARY, AccountId, Signature, GenesisConfig, SystemConfig, BalancesConfig
|
||||
};
|
||||
|
||||
pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;
|
||||
type AccountPublic = <Signature as Verify>::Signer;
|
||||
|
||||
fn get_from_seed<TPublic: Public>(seed: &'static str) -> <TPublic::Pair as Pair>::Public {
|
||||
TPublic::Pair::from_string(&format!("//{}", seed), None).unwrap().public()
|
||||
}
|
||||
|
||||
fn get_account_id_from_seed<TPublic: Public>(seed: &'static str) -> AccountId
|
||||
where AccountPublic: From<<TPublic::Pair as Pair>::Public> {
|
||||
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
|
||||
}
|
||||
|
||||
fn testnet_genesis(
|
||||
wasm_binary: &[u8],
|
||||
endowed_accounts: Vec<AccountId>
|
||||
) -> GenesisConfig {
|
||||
GenesisConfig {
|
||||
system: SystemConfig {
|
||||
code: wasm_binary.to_vec(),
|
||||
},
|
||||
balances: BalancesConfig {
|
||||
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
|
||||
},
|
||||
transaction_payment: Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn development_config() -> Result<ChainSpec, &'static str> {
|
||||
let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available")?;
|
||||
|
||||
Ok(
|
||||
ChainSpec::from_genesis(
|
||||
// Name
|
||||
"Development Network",
|
||||
// ID
|
||||
"dev",
|
||||
ChainType::Development,
|
||||
|| {
|
||||
testnet_genesis(
|
||||
wasm_binary,
|
||||
vec![
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Bob"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
|
||||
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
|
||||
]
|
||||
)
|
||||
},
|
||||
// Bootnodes
|
||||
vec![],
|
||||
// Telemetry
|
||||
None,
|
||||
// Protocol ID
|
||||
Some("serai"),
|
||||
// Fork ID
|
||||
None,
|
||||
// Properties
|
||||
None,
|
||||
// Extensions
|
||||
None
|
||||
)
|
||||
)
|
||||
}
|
||||
53
substrate/node/src/cli.rs
Normal file
53
substrate/node/src/cli.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use sc_cli::RunCmd;
|
||||
|
||||
#[derive(Debug, clap::Parser)]
|
||||
pub struct Cli {
|
||||
#[clap(subcommand)]
|
||||
pub subcommand: Option<Subcommand>,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub run: RunCmd,
|
||||
}
|
||||
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
pub enum Subcommand {
|
||||
/// Key management CLI utilities
|
||||
#[clap(subcommand)]
|
||||
Key(sc_cli::KeySubcommand),
|
||||
|
||||
/// Build a chain specification
|
||||
BuildSpec(sc_cli::BuildSpecCmd),
|
||||
|
||||
/// Validate blocks
|
||||
CheckBlock(sc_cli::CheckBlockCmd),
|
||||
|
||||
/// Export blocks
|
||||
ExportBlocks(sc_cli::ExportBlocksCmd),
|
||||
|
||||
/// Export the state of a given block into a chain spec
|
||||
ExportState(sc_cli::ExportStateCmd),
|
||||
|
||||
/// Import blocks
|
||||
ImportBlocks(sc_cli::ImportBlocksCmd),
|
||||
|
||||
/// Remove the entire chain
|
||||
PurgeChain(sc_cli::PurgeChainCmd),
|
||||
|
||||
/// Revert the chain to a previous state
|
||||
Revert(sc_cli::RevertCmd),
|
||||
|
||||
/// Sub-commands concerned with benchmarking
|
||||
#[clap(subcommand)]
|
||||
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
|
||||
|
||||
/// Try some command against the runtime state
|
||||
#[cfg(feature = "try-runtime")]
|
||||
TryRuntime(try_runtime_cli::TryRuntimeCmd),
|
||||
|
||||
/// Try some command against the runtime state. Note: `try-runtime` feature must be enabled
|
||||
#[cfg(not(feature = "try-runtime"))]
|
||||
TryRuntime,
|
||||
|
||||
/// DB meta columns information
|
||||
ChainInfo(sc_cli::ChainInfoCmd),
|
||||
}
|
||||
176
substrate/node/src/command.rs
Normal file
176
substrate/node/src/command.rs
Normal file
@@ -0,0 +1,176 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use sc_service::PartialComponents;
|
||||
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
|
||||
use sc_cli::{ChainSpec, RuntimeVersion, SubstrateCli};
|
||||
|
||||
use serai_runtime::Block;
|
||||
|
||||
use crate::{
|
||||
chain_spec,
|
||||
cli::{Cli, Subcommand},
|
||||
command_helper::{BenchmarkExtrinsicBuilder, inherent_benchmark_data},
|
||||
service
|
||||
};
|
||||
|
||||
impl SubstrateCli for Cli {
|
||||
fn impl_name() -> String {
|
||||
"Serai Node".into()
|
||||
}
|
||||
|
||||
fn impl_version() -> String {
|
||||
env!("SUBSTRATE_CLI_IMPL_VERSION").to_string()
|
||||
}
|
||||
|
||||
fn description() -> String {
|
||||
env!("CARGO_PKG_DESCRIPTION").to_string()
|
||||
}
|
||||
|
||||
fn author() -> String {
|
||||
env!("CARGO_PKG_AUTHORS").to_string()
|
||||
}
|
||||
|
||||
fn support_url() -> String {
|
||||
"serai.exchange".to_string()
|
||||
}
|
||||
|
||||
fn copyright_start_year() -> i32 {
|
||||
2022
|
||||
}
|
||||
|
||||
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
|
||||
match id {
|
||||
"dev" => Ok(Box::new(chain_spec::development_config()?)),
|
||||
_ => panic!("Unknown network ID")
|
||||
}
|
||||
}
|
||||
|
||||
fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
|
||||
&serai_runtime::VERSION
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() -> sc_cli::Result<()> {
|
||||
let cli = Cli::from_args();
|
||||
|
||||
match &cli.subcommand {
|
||||
Some(Subcommand::Key(cmd)) => cmd.run(&cli),
|
||||
|
||||
Some(Subcommand::BuildSpec(cmd)) => {
|
||||
cli.create_runner(cmd)?.sync_run(|config| cmd.run(config.chain_spec, config.network))
|
||||
},
|
||||
|
||||
Some(Subcommand::CheckBlock(cmd)) => {
|
||||
cli.create_runner(cmd)?.async_run(|config| {
|
||||
let PartialComponents {
|
||||
client,
|
||||
task_manager,
|
||||
import_queue,
|
||||
..
|
||||
} = service::new_partial(&config)?;
|
||||
Ok((cmd.run(client, import_queue), task_manager))
|
||||
})
|
||||
},
|
||||
|
||||
Some(Subcommand::ExportBlocks(cmd)) => {
|
||||
cli.create_runner(cmd)?.async_run(|config| {
|
||||
let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?;
|
||||
Ok((cmd.run(client, config.database), task_manager))
|
||||
})
|
||||
},
|
||||
|
||||
Some(Subcommand::ExportState(cmd)) => {
|
||||
cli.create_runner(cmd)?.async_run(|config| {
|
||||
let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?;
|
||||
Ok((cmd.run(client, config.chain_spec), task_manager))
|
||||
})
|
||||
},
|
||||
|
||||
Some(Subcommand::ImportBlocks(cmd)) => {
|
||||
cli.create_runner(cmd)?.async_run(|config| {
|
||||
let PartialComponents {
|
||||
client,
|
||||
task_manager,
|
||||
import_queue,
|
||||
..
|
||||
} = service::new_partial(&config)?;
|
||||
Ok((cmd.run(client, import_queue), task_manager))
|
||||
})
|
||||
},
|
||||
|
||||
Some(Subcommand::PurgeChain(cmd)) => {
|
||||
cli.create_runner(cmd)?.sync_run(|config| cmd.run(config.database))
|
||||
},
|
||||
|
||||
Some(Subcommand::Revert(cmd)) => {
|
||||
cli.create_runner(cmd)?.async_run(|config| {
|
||||
let PartialComponents {
|
||||
client,
|
||||
task_manager,
|
||||
backend,
|
||||
..
|
||||
} = service::new_partial(&config)?;
|
||||
Ok((cmd.run(client, backend, None), task_manager))
|
||||
})
|
||||
},
|
||||
|
||||
Some(Subcommand::Benchmark(cmd)) => {
|
||||
cli.create_runner(cmd)?.sync_run(|config| {
|
||||
match cmd {
|
||||
BenchmarkCmd::Pallet(cmd) => {
|
||||
cmd.run::<Block, service::ExecutorDispatch>(config)
|
||||
},
|
||||
|
||||
BenchmarkCmd::Block(cmd) => {
|
||||
cmd.run(service::new_partial(&config)?.client)
|
||||
},
|
||||
|
||||
BenchmarkCmd::Storage(cmd) => {
|
||||
let PartialComponents { client, backend, .. } = service::new_partial(&config)?;
|
||||
cmd.run(config, client, backend.expose_db(), backend.expose_storage())
|
||||
},
|
||||
|
||||
BenchmarkCmd::Overhead(cmd) => {
|
||||
let client = service::new_partial(&config)?.client;
|
||||
cmd.run(
|
||||
config,
|
||||
client.clone(),
|
||||
inherent_benchmark_data()?,
|
||||
Arc::new(BenchmarkExtrinsicBuilder::new(client))
|
||||
)
|
||||
},
|
||||
|
||||
BenchmarkCmd::Machine(cmd) => cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
#[cfg(feature = "try-runtime")]
|
||||
Some(Subcommand::TryRuntime(cmd)) => {
|
||||
cli.create_runner(cmd)?.async_run(|config| {
|
||||
Ok(
|
||||
(
|
||||
cmd.run::<Block, service::ExecutorDispatch>(config),
|
||||
sc_service::TaskManager::new(
|
||||
config.tokio_handle.clone(),
|
||||
config.prometheus_config.as_ref().map(|cfg| &cfg.registry)
|
||||
).map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?
|
||||
)
|
||||
)
|
||||
})
|
||||
},
|
||||
|
||||
#[cfg(not(feature = "try-runtime"))]
|
||||
Some(Subcommand::TryRuntime) => Err("TryRuntime wasn't enabled when building the node".into()),
|
||||
|
||||
Some(Subcommand::ChainInfo(cmd)) => {
|
||||
cli.create_runner(cmd)?.sync_run(|config| cmd.run::<Block>(&config))
|
||||
},
|
||||
|
||||
None => {
|
||||
cli.create_runner(&cli.run)?.run_node_until_exit(|config| async {
|
||||
service::new_full(config).map_err(sc_cli::Error::Service)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
95
substrate/node/src/command_helper.rs
Normal file
95
substrate/node/src/command_helper.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use sp_core::{Encode, Pair};
|
||||
use sp_keyring::Sr25519Keyring;
|
||||
use sp_inherents::{InherentData, InherentDataProvider};
|
||||
|
||||
use sp_runtime::OpaqueExtrinsic;
|
||||
|
||||
use sc_cli::Result;
|
||||
use sc_client_api::BlockBackend;
|
||||
|
||||
use serai_runtime as runtime;
|
||||
use runtime::SystemCall;
|
||||
|
||||
use crate::service::FullClient;
|
||||
|
||||
pub struct BenchmarkExtrinsicBuilder {
|
||||
client: Arc<FullClient>
|
||||
}
|
||||
|
||||
impl BenchmarkExtrinsicBuilder {
|
||||
pub fn new(client: Arc<FullClient>) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
}
|
||||
|
||||
impl frame_benchmarking_cli::ExtrinsicBuilder for BenchmarkExtrinsicBuilder {
|
||||
fn remark(&self, nonce: u32) -> std::result::Result<OpaqueExtrinsic, &'static str> {
|
||||
Ok(
|
||||
OpaqueExtrinsic::from(
|
||||
create_benchmark_extrinsic(
|
||||
self.client.as_ref(),
|
||||
Sr25519Keyring::Bob.pair(),
|
||||
SystemCall::remark { remark: vec![] }.into(),
|
||||
nonce
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_benchmark_extrinsic(
|
||||
client: &FullClient,
|
||||
sender: sp_core::sr25519::Pair,
|
||||
call: runtime::Call,
|
||||
nonce: u32,
|
||||
) -> runtime::UncheckedExtrinsic {
|
||||
let extra = (
|
||||
frame_system::CheckNonZeroSender::<runtime::Runtime>::new(),
|
||||
frame_system::CheckSpecVersion::<runtime::Runtime>::new(),
|
||||
frame_system::CheckTxVersion::<runtime::Runtime>::new(),
|
||||
frame_system::CheckGenesis::<runtime::Runtime>::new(),
|
||||
frame_system::CheckEra::<runtime::Runtime>::from(
|
||||
sp_runtime::generic::Era::mortal(
|
||||
u64::from(
|
||||
runtime::BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2)
|
||||
),
|
||||
client.chain_info().best_number.into(),
|
||||
)
|
||||
),
|
||||
frame_system::CheckNonce::<runtime::Runtime>::from(nonce),
|
||||
frame_system::CheckWeight::<runtime::Runtime>::new(),
|
||||
pallet_transaction_payment::ChargeTransactionPayment::<runtime::Runtime>::from(0)
|
||||
);
|
||||
|
||||
runtime::UncheckedExtrinsic::new_signed(
|
||||
call.clone(),
|
||||
sp_runtime::AccountId32::from(sender.public()).into(),
|
||||
runtime::Signature::Sr25519(
|
||||
runtime::SignedPayload::from_raw(
|
||||
call.clone(),
|
||||
extra.clone(),
|
||||
(
|
||||
(),
|
||||
runtime::VERSION.spec_version,
|
||||
runtime::VERSION.transaction_version,
|
||||
client.block_hash(0).ok().flatten().unwrap(),
|
||||
client.chain_info().best_hash,
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
)
|
||||
).using_encoded(|e| sender.sign(e))
|
||||
),
|
||||
extra,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn inherent_benchmark_data() -> Result<InherentData> {
|
||||
let mut inherent_data = InherentData::new();
|
||||
sp_timestamp::InherentDataProvider::new(Duration::from_millis(0).into())
|
||||
.provide_inherent_data(&mut inherent_data)
|
||||
.map_err(|e| format!("creating inherent data: {:?}", e))?;
|
||||
Ok(inherent_data)
|
||||
}
|
||||
3
substrate/node/src/lib.rs
Normal file
3
substrate/node/src/lib.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod chain_spec;
|
||||
pub mod rpc;
|
||||
pub mod service;
|
||||
13
substrate/node/src/main.rs
Normal file
13
substrate/node/src/main.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
mod chain_spec;
|
||||
#[macro_use]
|
||||
mod service;
|
||||
|
||||
mod command_helper;
|
||||
mod command;
|
||||
|
||||
mod rpc;
|
||||
mod cli;
|
||||
|
||||
fn main() -> sc_cli::Result<()> {
|
||||
command::run()
|
||||
}
|
||||
42
substrate/node/src/rpc.rs
Normal file
42
substrate/node/src/rpc.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use jsonrpsee::RpcModule;
|
||||
|
||||
use sp_blockchain::{Error as BlockchainError, HeaderBackend, HeaderMetadata};
|
||||
use sc_transaction_pool_api::TransactionPool;
|
||||
use sp_block_builder::BlockBuilder;
|
||||
use sp_api::ProvideRuntimeApi;
|
||||
|
||||
pub use sc_rpc_api::DenyUnsafe;
|
||||
|
||||
use serai_runtime::{opaque::Block, AccountId, Balance, Index};
|
||||
|
||||
pub struct FullDeps<C, P> {
|
||||
pub client: Arc<C>,
|
||||
pub pool: Arc<P>,
|
||||
pub deny_unsafe: DenyUnsafe
|
||||
}
|
||||
|
||||
pub fn create_full<
|
||||
C: ProvideRuntimeApi<Block> +
|
||||
HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockchainError> +
|
||||
Send + Sync + 'static,
|
||||
P: TransactionPool + 'static
|
||||
>(
|
||||
deps: FullDeps<C, P>
|
||||
) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
|
||||
where C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index> +
|
||||
pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance> +
|
||||
BlockBuilder<Block> {
|
||||
|
||||
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
|
||||
use substrate_frame_rpc_system::{System, SystemApiServer};
|
||||
|
||||
let mut module = RpcModule::new(());
|
||||
let FullDeps { client, pool, deny_unsafe } = deps;
|
||||
|
||||
module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?;
|
||||
module.merge(TransactionPayment::new(client).into_rpc())?;
|
||||
|
||||
Ok(module)
|
||||
}
|
||||
170
substrate/node/src/service.rs
Normal file
170
substrate/node/src/service.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
|
||||
use sc_executor::NativeElseWasmExecutor;
|
||||
use sc_telemetry::{Telemetry, TelemetryWorker};
|
||||
|
||||
use serai_runtime::{self, opaque::Block, RuntimeApi};
|
||||
pub(crate) use serai_consensus::{ExecutorDispatch, FullClient};
|
||||
|
||||
type FullBackend = sc_service::TFullBackend<Block>;
|
||||
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
|
||||
|
||||
type PartialComponents = sc_service::PartialComponents<
|
||||
FullClient,
|
||||
FullBackend,
|
||||
FullSelectChain,
|
||||
sc_consensus::DefaultImportQueue<Block, FullClient>,
|
||||
sc_transaction_pool::FullPool<Block, FullClient>,
|
||||
Option<Telemetry>,
|
||||
>;
|
||||
|
||||
pub fn new_partial(config: &Configuration) -> Result<PartialComponents, ServiceError> {
|
||||
if config.keystore_remote.is_some() {
|
||||
return Err(ServiceError::Other("Remote Keystores are not supported".to_string()))
|
||||
}
|
||||
|
||||
let telemetry = config
|
||||
.telemetry_endpoints
|
||||
.clone()
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
|
||||
let worker = TelemetryWorker::new(16)?;
|
||||
let telemetry = worker.handle().new_telemetry(endpoints);
|
||||
Ok((worker, telemetry))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(
|
||||
config.wasm_method,
|
||||
config.default_heap_pages,
|
||||
config.max_runtime_instances,
|
||||
config.runtime_cache_size
|
||||
);
|
||||
|
||||
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)| {
|
||||
task_manager.spawn_handle().spawn("telemetry", None, worker.run());
|
||||
telemetry
|
||||
});
|
||||
|
||||
let select_chain = sc_consensus::LongestChain::new(backend.clone());
|
||||
|
||||
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 import_queue = serai_consensus::import_queue(
|
||||
&task_manager,
|
||||
client.clone(),
|
||||
select_chain.clone(),
|
||||
config.prometheus_registry()
|
||||
)?;
|
||||
|
||||
Ok(
|
||||
sc_service::PartialComponents {
|
||||
client,
|
||||
backend,
|
||||
task_manager,
|
||||
import_queue,
|
||||
keystore_container,
|
||||
select_chain,
|
||||
transaction_pool,
|
||||
other: telemetry,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {
|
||||
let sc_service::PartialComponents {
|
||||
client,
|
||||
backend,
|
||||
mut task_manager,
|
||||
import_queue,
|
||||
keystore_container,
|
||||
select_chain,
|
||||
other: mut telemetry,
|
||||
transaction_pool
|
||||
} = new_partial(&config)?;
|
||||
|
||||
let (network, system_rpc_tx, network_starter) = sc_service::build_network(
|
||||
sc_service::BuildNetworkParams {
|
||||
config: &config,
|
||||
client: client.clone(),
|
||||
transaction_pool: transaction_pool.clone(),
|
||||
spawn_handle: task_manager.spawn_handle(),
|
||||
import_queue,
|
||||
block_announce_validator_builder: None,
|
||||
warp_sync: None,
|
||||
}
|
||||
)?;
|
||||
|
||||
if config.offchain_worker.enabled {
|
||||
sc_service::build_offchain_workers(
|
||||
&config,
|
||||
task_manager.spawn_handle(),
|
||||
client.clone(),
|
||||
network.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
let role = config.role.clone();
|
||||
let prometheus_registry = config.prometheus_registry().cloned();
|
||||
|
||||
let rpc_extensions_builder = {
|
||||
let client = client.clone();
|
||||
let pool = transaction_pool.clone();
|
||||
|
||||
Box::new(
|
||||
move |deny_unsafe, _| {
|
||||
crate::rpc::create_full(
|
||||
crate::rpc::FullDeps { client: client.clone(), pool: pool.clone(), deny_unsafe }
|
||||
).map_err(Into::into)
|
||||
}
|
||||
)
|
||||
};
|
||||
|
||||
sc_service::spawn_tasks(
|
||||
sc_service::SpawnTasksParams {
|
||||
network: network.clone(),
|
||||
client: client.clone(),
|
||||
keystore: keystore_container.sync_keystore(),
|
||||
task_manager: &mut task_manager,
|
||||
transaction_pool: transaction_pool.clone(),
|
||||
rpc_builder: rpc_extensions_builder,
|
||||
backend,
|
||||
system_rpc_tx,
|
||||
config,
|
||||
telemetry: telemetry.as_mut(),
|
||||
}
|
||||
)?;
|
||||
|
||||
if role.is_authority() {
|
||||
serai_consensus::authority(
|
||||
&task_manager,
|
||||
client,
|
||||
network,
|
||||
transaction_pool,
|
||||
select_chain,
|
||||
prometheus_registry.as_ref()
|
||||
);
|
||||
}
|
||||
|
||||
network_starter.start_network();
|
||||
Ok(task_manager)
|
||||
}
|
||||
94
substrate/runtime/Cargo.toml
Normal file
94
substrate/runtime/Cargo.toml
Normal file
@@ -0,0 +1,94 @@
|
||||
[package]
|
||||
name = "serai-runtime"
|
||||
version = "0.1.0"
|
||||
description = "Serai network node runtime, built over Substrate"
|
||||
license = "AGPL-3.0-only"
|
||||
authors = ["Luke Parker <lukeparker5132@gmail.com>"]
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
|
||||
|
||||
sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-std = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-version = { version = "5.0.0", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-inherents = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai"}
|
||||
sp-offchain = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-session = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-transaction-pool = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-block-builder = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai"}
|
||||
sp-runtime = { version = "6.0.0", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
sp-api = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
frame-support = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
frame-system = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
frame-executive = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
frame-try-runtime = { version = "0.10.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai", optional = true }
|
||||
|
||||
pallet-timestamp = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
pallet-balances = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
# Used for the node template's RPCs
|
||||
frame-system-rpc-runtime-api = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
pallet-transaction-payment-rpc-runtime-api = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
# Used for runtime benchmarking
|
||||
frame-benchmarking = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai", optional = true }
|
||||
frame-system-benchmarking = { version = "4.0.0-dev", default-features = false, git = "https://github.com/serai-dex/substrate.git", branch = "serai", optional = true }
|
||||
hex-literal = { version = "0.3.4", optional = true }
|
||||
|
||||
[build-dependencies]
|
||||
substrate-wasm-builder = { version = "5.0.0-dev", git = "https://github.com/serai-dex/substrate.git", branch = "serai" }
|
||||
|
||||
[features]
|
||||
std = [
|
||||
"codec/std",
|
||||
"scale-info/std",
|
||||
|
||||
"sp-core/std",
|
||||
"sp-std/std",
|
||||
"sp-version/std",
|
||||
"sp-inherents/std",
|
||||
"sp-offchain/std",
|
||||
"sp-session/std",
|
||||
"sp-transaction-pool/std",
|
||||
"sp-block-builder/std",
|
||||
"sp-runtime/std",
|
||||
"sp-api/std",
|
||||
|
||||
"frame-support/std",
|
||||
"frame-system-rpc-runtime-api/std",
|
||||
"frame-system/std",
|
||||
"frame-executive/std",
|
||||
|
||||
"pallet-timestamp/std",
|
||||
"pallet-balances/std",
|
||||
"pallet-transaction-payment/std",
|
||||
"pallet-transaction-payment-rpc-runtime-api/std"
|
||||
]
|
||||
|
||||
runtime-benchmarks = [
|
||||
"hex-literal",
|
||||
"sp-runtime/runtime-benchmarks",
|
||||
"frame-benchmarking/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
"frame-system-benchmarking",
|
||||
"frame-system/runtime-benchmarks",
|
||||
"pallet-timestamp/runtime-benchmarks",
|
||||
"pallet-balances/runtime-benchmarks"
|
||||
]
|
||||
|
||||
try-runtime = [
|
||||
"frame-executive/try-runtime",
|
||||
"frame-try-runtime",
|
||||
"frame-system/try-runtime",
|
||||
|
||||
"pallet-timestamp/try-runtime",
|
||||
"pallet-balances/try-runtime",
|
||||
"pallet-transaction-payment/try-runtime"
|
||||
]
|
||||
|
||||
default = ["std"]
|
||||
15
substrate/runtime/LICENSE
Normal file
15
substrate/runtime/LICENSE
Normal file
@@ -0,0 +1,15 @@
|
||||
AGPL-3.0-only license
|
||||
|
||||
Copyright (c) 2022 Luke Parker
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License Version 3 as
|
||||
published by the Free Software Foundation.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
9
substrate/runtime/build.rs
Normal file
9
substrate/runtime/build.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use substrate_wasm_builder::WasmBuilder;
|
||||
|
||||
fn main() {
|
||||
WasmBuilder::new()
|
||||
.with_current_project()
|
||||
.export_heap_base()
|
||||
.import_memory()
|
||||
.build()
|
||||
}
|
||||
379
substrate/runtime/src/lib.rs
Normal file
379
substrate/runtime/src/lib.rs
Normal file
@@ -0,0 +1,379 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
|
||||
|
||||
use sp_api::impl_runtime_apis;
|
||||
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
|
||||
use sp_runtime::{
|
||||
create_runtime_str, generic, impl_opaque_keys,
|
||||
traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
|
||||
transaction_validity::{TransactionSource, TransactionValidity},
|
||||
ApplyExtrinsicResult, MultiSignature,
|
||||
Perbill
|
||||
};
|
||||
use sp_std::prelude::*;
|
||||
#[cfg(feature = "std")]
|
||||
use sp_version::NativeVersion;
|
||||
use sp_version::RuntimeVersion;
|
||||
|
||||
use frame_support::{
|
||||
traits::{ConstU8, ConstU32, ConstU64},
|
||||
weights::{constants::{RocksDbWeight, WEIGHT_PER_SECOND}, IdentityFee},
|
||||
parameter_types, construct_runtime
|
||||
};
|
||||
pub use frame_system::Call as SystemCall;
|
||||
pub use pallet_timestamp::Call as TimestampCall;
|
||||
pub use pallet_balances::Call as BalancesCall;
|
||||
use pallet_transaction_payment::CurrencyAdapter;
|
||||
|
||||
/// An index to a block
|
||||
pub type BlockNumber = u32;
|
||||
|
||||
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain
|
||||
pub type Signature = MultiSignature;
|
||||
|
||||
/// Some way of identifying an account on the chain. We intentionally make it equivalent
|
||||
/// to the public key of our transaction signing scheme
|
||||
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
|
||||
|
||||
/// Balance of an account
|
||||
pub type Balance = u64;
|
||||
|
||||
/// Index of a transaction in the chain, for a given account
|
||||
pub type Index = u32;
|
||||
|
||||
/// A hash of some data used by the chain
|
||||
pub type Hash = sp_core::H256;
|
||||
|
||||
pub mod opaque {
|
||||
use super::*;
|
||||
|
||||
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
|
||||
|
||||
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
|
||||
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
|
||||
pub type BlockId = generic::BlockId<Block>;
|
||||
|
||||
impl_opaque_keys! {
|
||||
pub struct SessionKeys {}
|
||||
}
|
||||
}
|
||||
|
||||
#[sp_version::runtime_version]
|
||||
pub const VERSION: RuntimeVersion = RuntimeVersion {
|
||||
spec_name: create_runtime_str!("serai"),
|
||||
impl_name: create_runtime_str!("turoctocrab"),
|
||||
authoring_version: 1,
|
||||
spec_version: 100,
|
||||
impl_version: 1,
|
||||
apis: RUNTIME_API_VERSIONS,
|
||||
transaction_version: 1,
|
||||
state_version: 1
|
||||
};
|
||||
|
||||
pub const MILLISECS_PER_BLOCK: u64 = 6000;
|
||||
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
|
||||
|
||||
/// Measured in blocks
|
||||
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
|
||||
pub const HOURS: BlockNumber = MINUTES * 60;
|
||||
pub const DAYS: BlockNumber = HOURS * 24;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub fn native_version() -> NativeVersion {
|
||||
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
|
||||
}
|
||||
|
||||
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
|
||||
|
||||
parameter_types! {
|
||||
pub const BlockHashCount: BlockNumber = 2400;
|
||||
pub const Version: RuntimeVersion = VERSION;
|
||||
/// Allow for 2 seconds of compute with a 6 second average block time
|
||||
pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights
|
||||
::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO);
|
||||
pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
|
||||
::max_with_normal_ratio(1024 * 1024, NORMAL_DISPATCH_RATIO);
|
||||
pub const SS58Prefix: u8 = 42; // TODO: Remove
|
||||
}
|
||||
|
||||
impl frame_system::Config for Runtime {
|
||||
type BaseCallFilter = frame_support::traits::Everything;
|
||||
type BlockWeights = BlockWeights;
|
||||
type BlockLength = BlockLength;
|
||||
type AccountId = AccountId;
|
||||
type Call = Call;
|
||||
type Lookup = AccountIdLookup<AccountId, ()>;
|
||||
type Index = Index;
|
||||
type BlockNumber = BlockNumber;
|
||||
type Hash = Hash;
|
||||
type Hashing = BlakeTwo256;
|
||||
type Header = Header;
|
||||
type Event = Event;
|
||||
type Origin = Origin;
|
||||
type BlockHashCount = BlockHashCount;
|
||||
type DbWeight = RocksDbWeight;
|
||||
type Version = Version;
|
||||
type PalletInfo = PalletInfo;
|
||||
|
||||
type OnNewAccount = ();
|
||||
type OnKilledAccount = ();
|
||||
type OnSetCode = ();
|
||||
|
||||
type AccountData = pallet_balances::AccountData<Balance>;
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = SS58Prefix; // TODO: Remove
|
||||
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
impl pallet_timestamp::Config for Runtime {
|
||||
type Moment = u64;
|
||||
type OnTimestampSet = ();
|
||||
type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl pallet_balances::Config for Runtime {
|
||||
type MaxLocks = ConstU32<50>;
|
||||
type MaxReserves = ();
|
||||
type ReserveIdentifier = [u8; 8];
|
||||
type Balance = Balance;
|
||||
type Event = Event;
|
||||
type DustRemoval = ();
|
||||
type ExistentialDeposit = ConstU64<500>;
|
||||
type AccountStore = System;
|
||||
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
|
||||
}
|
||||
|
||||
impl pallet_transaction_payment::Config for Runtime {
|
||||
type Event = Event;
|
||||
type OnChargeTransaction = CurrencyAdapter<Balances, ()>;
|
||||
type OperationalFeeMultiplier = ConstU8<5>;
|
||||
type WeightToFee = IdentityFee<Balance>;
|
||||
type LengthToFee = IdentityFee<Balance>;
|
||||
type FeeMultiplierUpdate = ();
|
||||
}
|
||||
|
||||
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
|
||||
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
|
||||
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
|
||||
pub type SignedExtra = (
|
||||
frame_system::CheckNonZeroSender<Runtime>,
|
||||
frame_system::CheckSpecVersion<Runtime>,
|
||||
frame_system::CheckTxVersion<Runtime>,
|
||||
frame_system::CheckGenesis<Runtime>,
|
||||
frame_system::CheckEra<Runtime>,
|
||||
frame_system::CheckNonce<Runtime>,
|
||||
frame_system::CheckWeight<Runtime>,
|
||||
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
|
||||
);
|
||||
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
|
||||
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
|
||||
pub type Executive = frame_executive::Executive<
|
||||
Runtime,
|
||||
Block,
|
||||
frame_system::ChainContext<Runtime>,
|
||||
Runtime,
|
||||
AllPalletsWithSystem,
|
||||
>;
|
||||
|
||||
construct_runtime!(
|
||||
pub enum Runtime where
|
||||
Block = Block,
|
||||
NodeBlock = Block,
|
||||
UncheckedExtrinsic = UncheckedExtrinsic
|
||||
{
|
||||
System: frame_system,
|
||||
Timestamp: pallet_timestamp,
|
||||
Balances: pallet_balances,
|
||||
TransactionPayment: pallet_transaction_payment
|
||||
}
|
||||
);
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
#[macro_use]
|
||||
extern crate frame_benchmarking;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
mod benches {
|
||||
define_benchmarks!(
|
||||
[frame_benchmarking, BaselineBench::<Runtime>]
|
||||
[frame_system, SystemBench::<Runtime>]
|
||||
[pallet_balances, Balances]
|
||||
[pallet_timestamp, Timestamp]
|
||||
);
|
||||
}
|
||||
|
||||
impl_runtime_apis! {
|
||||
impl sp_api::Core<Block> for Runtime {
|
||||
fn version() -> RuntimeVersion {
|
||||
VERSION
|
||||
}
|
||||
|
||||
fn execute_block(block: Block) {
|
||||
Executive::execute_block(block);
|
||||
}
|
||||
|
||||
fn initialize_block(header: &<Block as BlockT>::Header) {
|
||||
Executive::initialize_block(header)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_api::Metadata<Block> for Runtime {
|
||||
fn metadata() -> OpaqueMetadata {
|
||||
OpaqueMetadata::new(Runtime::metadata().into())
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_block_builder::BlockBuilder<Block> for Runtime {
|
||||
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
|
||||
Executive::apply_extrinsic(extrinsic)
|
||||
}
|
||||
|
||||
fn finalize_block() -> <Block as BlockT>::Header {
|
||||
Executive::finalize_block()
|
||||
}
|
||||
|
||||
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
|
||||
data.create_extrinsics()
|
||||
}
|
||||
|
||||
fn check_inherents(
|
||||
block: Block,
|
||||
data: sp_inherents::InherentData,
|
||||
) -> sp_inherents::CheckInherentsResult {
|
||||
data.check_extrinsics(&block)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
|
||||
fn validate_transaction(
|
||||
source: TransactionSource,
|
||||
tx: <Block as BlockT>::Extrinsic,
|
||||
block_hash: <Block as BlockT>::Hash,
|
||||
) -> TransactionValidity {
|
||||
Executive::validate_transaction(source, tx, block_hash)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
|
||||
fn offchain_worker(header: &<Block as BlockT>::Header) {
|
||||
Executive::offchain_worker(header)
|
||||
}
|
||||
}
|
||||
|
||||
impl sp_session::SessionKeys<Block> for Runtime {
|
||||
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
|
||||
opaque::SessionKeys::generate(seed)
|
||||
}
|
||||
|
||||
fn decode_session_keys(
|
||||
encoded: Vec<u8>,
|
||||
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
|
||||
opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
|
||||
}
|
||||
}
|
||||
|
||||
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
|
||||
fn account_nonce(account: AccountId) -> Index {
|
||||
System::account_nonce(account)
|
||||
}
|
||||
}
|
||||
|
||||
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
|
||||
Block,
|
||||
Balance
|
||||
> for Runtime {
|
||||
fn query_info(
|
||||
uxt: <Block as BlockT>::Extrinsic,
|
||||
len: u32,
|
||||
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
|
||||
TransactionPayment::query_info(uxt, len)
|
||||
}
|
||||
fn query_fee_details(
|
||||
uxt: <Block as BlockT>::Extrinsic,
|
||||
len: u32,
|
||||
) -> pallet_transaction_payment::FeeDetails<Balance> {
|
||||
TransactionPayment::query_fee_details(uxt, len)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
impl frame_benchmarking::Benchmark<Block> for Runtime {
|
||||
fn benchmark_metadata(extra: bool) -> (
|
||||
Vec<frame_benchmarking::BenchmarkList>,
|
||||
Vec<frame_support::traits::StorageInfo>,
|
||||
) {
|
||||
use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
|
||||
use frame_support::traits::StorageInfoTrait;
|
||||
use frame_system_benchmarking::Pallet as SystemBench;
|
||||
use baseline::Pallet as BaselineBench;
|
||||
|
||||
let mut list = Vec::<BenchmarkList>::new();
|
||||
list_benchmarks!(list, extra);
|
||||
|
||||
let storage_info = AllPalletsWithSystem::storage_info();
|
||||
|
||||
(list, storage_info)
|
||||
}
|
||||
|
||||
fn dispatch_benchmark(
|
||||
config: frame_benchmarking::BenchmarkConfig
|
||||
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
|
||||
use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch, TrackedStorageKey};
|
||||
|
||||
use frame_system_benchmarking::Pallet as SystemBench;
|
||||
use baseline::Pallet as BaselineBench;
|
||||
|
||||
impl frame_system_benchmarking::Config for Runtime {}
|
||||
impl baseline::Config for Runtime {}
|
||||
|
||||
let whitelist: Vec<TrackedStorageKey> = vec![
|
||||
// Block Number
|
||||
hex_literal::hex!(
|
||||
"26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac"
|
||||
).to_vec().into(),
|
||||
// Total Issuance
|
||||
hex_literal::hex!(
|
||||
"c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80"
|
||||
).to_vec().into(),
|
||||
// Execution Phase
|
||||
hex_literal::hex!(
|
||||
"26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a"
|
||||
).to_vec().into(),
|
||||
// Event Count
|
||||
hex_literal::hex!(
|
||||
"26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850"
|
||||
).to_vec().into(),
|
||||
// System Events
|
||||
hex_literal::hex!(
|
||||
"26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7"
|
||||
).to_vec().into(),
|
||||
];
|
||||
|
||||
let mut batches = Vec::<BenchmarkBatch>::new();
|
||||
let params = (&config, &whitelist);
|
||||
add_benchmarks!(params, batches);
|
||||
|
||||
Ok(batches)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "try-runtime")]
|
||||
impl frame_try_runtime::TryRuntime<Block> for Runtime {
|
||||
fn on_runtime_upgrade() -> (Weight, Weight) {
|
||||
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
|
||||
// have a backtrace here. If any of the pre/post migration checks fail, we shall stop
|
||||
// right here and right now.
|
||||
let weight = Executive::try_runtime_upgrade().unwrap();
|
||||
(weight, BlockWeights::get().max_block)
|
||||
}
|
||||
|
||||
fn execute_block_no_check(block: Block) -> Weight {
|
||||
Executive::execute_block_no_check(block)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user