Skip to content

Commit

Permalink
test staking (paritytech#173)
Browse files Browse the repository at this point in the history
* WIP draft compiles

* Add authorship pallet.

* bump spec version

* cargo fmt

* remove commented code

* add license

* wrap commetn

* Add some notes

* another idea

* rename pallet

* remove pallet authorship. That was a false lead.

* Make it compile

* Event and event handler

* Ditch FindAuthor implementation.

* Inherent is required

* Add the digest. Is it really that easy?

* Wire into standalone node. Lots of duplicate code.

* cargo fmt

* cleanup and fix

* Add to both runtimes

* init

* add check-inherent impl and fix runtime config

* add Call to stake config and fix standalone Cargo lock

* add stakers in genesis and remove repeated timestamp inherent in parachain node

* wired parachain cli with account id param

* move to account_id to RunCmd like in utxo workshop

* parse H160 from string

* clean

* wire standalone node

* make account_id optional

* fix parse h160 impl and return error early if cli run account id is not set

* fix inherent provider registration in standalone, add tests, now an issue generating the chain spec

* split match statement in nodes so account is only required in some branches

* push attempt

* pass tests

* pass

* make author permissions more generic, unit test payout distribution, bump versions

* init stake polkadot js integration tests

* update runtime parameters

* update node genesis with new validator min stake requirements

* and integration tests

* test rewards sent to sole validator for block authoring

* add code docs

* green

* fmt

* Update tests/tests/test-balance.ts

Co-authored-by: Joshy Orndorff <[email protected]>

* Update pallets/author-inherent/src/lib.rs

Co-authored-by: Joshy Orndorff <[email protected]>

* Update pallets/author-inherent/src/lib.rs

Co-authored-by: Joshy Orndorff <[email protected]>

* Update pallets/stake/src/lib.rs

Co-authored-by: Joshy Orndorff <[email protected]>

* Update pallets/stake/src/lib.rs

Co-authored-by: Joshy Orndorff <[email protected]>

* fmt and add back parachain import

* address some comments

* comment use of account as H160 default in when not needed for call

* only register author inherent when running node and otherwise pass in None

* rm outdated comment

Co-authored-by: Joshy Orndorff <[email protected]>
Co-authored-by: Joshy Orndorff <[email protected]>
  • Loading branch information
3 people authored Jan 15, 2021
1 parent 83823ac commit 22c4742
Show file tree
Hide file tree
Showing 29 changed files with 523 additions and 148 deletions.
11 changes: 5 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
members = [
'runtime',
'node/parachain',
'node/rpc',#Temporary
# We do NOT include the standalone node in this main workspace because it builds the
# runtime with the `standalone` feature, which the parachain does not support.
]
Expand Down
2 changes: 1 addition & 1 deletion moonbeam-types-bundle/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions node/parachain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ fc-rpc = { git = "https://github.com/purestake/frontier", branch = "v0.4-hotfixe
fp-rpc = { git = "https://github.com/purestake/frontier", branch = "v0.4-hotfixes" }
fc-consensus = { git = "https://github.com/purestake/frontier", branch = "v0.4-hotfixes" }

author-inherent = { path = "../../pallets/author-inherent"}

# Cumulus dependencies
cumulus-consensus = { git = "https://github.com/paritytech/cumulus", branch = "master" }
cumulus-collator = { git = "https://github.com/paritytech/cumulus", branch = "master" }
Expand Down
8 changes: 7 additions & 1 deletion node/parachain/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ fn testnet_genesis(
accounts: BTreeMap::new(),
}),
pallet_ethereum: Some(EthereumConfig {}),
stake: Some(StakeConfig { stakers: vec![] }),
stake: Some(StakeConfig {
stakers: endowed_accounts
.iter()
.cloned()
.map(|k| (k, None, 100_000))
.collect(),
}),
}
}
12 changes: 11 additions & 1 deletion node/parachain/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moonbeam. If not, see <http://www.gnu.org/licenses/>.

use sp_core::H160;
use std::path::PathBuf;

use structopt::StructOpt;

/// Sub-commands supported by the collator.
Expand Down Expand Up @@ -95,6 +95,16 @@ pub struct RunCmd {
/// Id of the parachain this collator collates for.
#[structopt(long)]
pub parachain_id: Option<u32>,

/// Public identity for participating in staking and receiving rewards
#[structopt(long, parse(try_from_str = parse_h160))]
pub account_id: Option<H160>,
}

fn parse_h160(input: &str) -> Result<H160, String> {
input
.parse::<H160>()
.map_err(|_| "Failed to parse H160".to_string())
}

impl std::ops::Deref for RunCmd {
Expand Down
18 changes: 9 additions & 9 deletions node/parachain/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<V
/// Parse command line arguments into service configuration.
pub fn run() -> Result<()> {
let cli = Cli::from_args();

match &cli.subcommand {
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
Expand All @@ -152,7 +151,7 @@ pub fn run() -> Result<()> {
task_manager,
import_queue,
..
} = crate::service::new_partial(&config)?;
} = crate::service::new_partial(&config, None)?;
Ok((cmd.run(client, import_queue), task_manager))
})
}
Expand All @@ -163,7 +162,7 @@ pub fn run() -> Result<()> {
client,
task_manager,
..
} = crate::service::new_partial(&config)?;
} = crate::service::new_partial(&config, None)?;
Ok((cmd.run(client, config.database), task_manager))
})
}
Expand All @@ -174,7 +173,7 @@ pub fn run() -> Result<()> {
client,
task_manager,
..
} = crate::service::new_partial(&config)?;
} = crate::service::new_partial(&config, None)?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
}
Expand All @@ -186,7 +185,7 @@ pub fn run() -> Result<()> {
task_manager,
import_queue,
..
} = crate::service::new_partial(&config)?;
} = crate::service::new_partial(&config, None)?;
Ok((cmd.run(client, import_queue), task_manager))
})
}
Expand All @@ -202,7 +201,7 @@ pub fn run() -> Result<()> {
task_manager,
backend,
..
} = crate::service::new_partial(&config)?;
} = crate::service::new_partial(&config, None)?;
Ok((cmd.run(client, backend), task_manager))
})
}
Expand Down Expand Up @@ -249,9 +248,10 @@ pub fn run() -> Result<()> {
}
None => {
let runner = cli.create_runner(&*cli.run)?;

let account = cli.run.account_id.ok_or(sc_cli::Error::Input(
"Account ID required but not set".to_string(),
))?;
runner.run_node_until_exit(|config| async move {
// TODO
let key = sp_core::Pair::generate().0;

let extension = chain_spec::Extensions::try_get(&*config.chain_spec);
Expand Down Expand Up @@ -286,7 +286,7 @@ pub fn run() -> Result<()> {
info!("Parachain genesis state: {}", genesis_state);
info!("Is collating: {}", if collator { "yes" } else { "no" });

crate::service::start_node(config, key, polkadot_config, id, collator)
crate::service::start_node(config, key, account, polkadot_config, id, collator)
.await
.map(|r| r.0)
})
Expand Down
36 changes: 29 additions & 7 deletions node/parachain/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ use cumulus_service::{
};
use fc_consensus::FrontierBlockImport;
use moonbeam_runtime::{opaque::Block, RuntimeApi};
use parity_scale_codec::Encode;
use polkadot_primitives::v0::CollatorPair;
use sc_executor::native_executor_instance;
pub use sc_executor::NativeExecutor;
use sc_service::{Configuration, PartialComponents, Role, TFullBackend, TFullClient, TaskManager};
use sp_core::Pair;
use sp_core::{Pair, H160};
use sp_inherents::InherentDataProviders;
use sp_runtime::traits::BlakeTwo256;
use sp_trie::PrefixedMemoryDB;
use std::sync::Arc;
Expand All @@ -35,6 +37,26 @@ native_executor_instance!(
moonbeam_runtime::native_version,
);

/// Build the inherent data providers (timestamp and authorship) for the node.
pub fn build_inherent_data_providers(
author: Option<H160>,
) -> Result<InherentDataProviders, sc_service::Error> {
let providers = InherentDataProviders::new();

providers
.register_provider(sp_timestamp::InherentDataProvider)
.map_err(Into::into)
.map_err(sp_consensus::error::Error::InherentData)?;
if let Some(account) = author {
providers
.register_provider(author_inherent::InherentDataProvider(account.encode()))
.map_err(Into::into)
.map_err(sp_consensus::error::Error::InherentData)?;
}

Ok(providers)
}

type FullClient = TFullClient<Block, RuntimeApi, Executor>;
type FullBackend = TFullBackend<Block>;

Expand All @@ -45,6 +67,7 @@ type FullBackend = TFullBackend<Block>;
#[allow(clippy::type_complexity)]
pub fn new_partial(
config: &Configuration,
author: Option<H160>,
) -> Result<
PartialComponents<
FullClient,
Expand All @@ -56,7 +79,7 @@ pub fn new_partial(
>,
sc_service::Error,
> {
let inherent_data_providers = sp_inherents::InherentDataProviders::new();
let inherent_data_providers = build_inherent_data_providers(author)?;

let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, Executor>(&config)?;
Expand Down Expand Up @@ -102,6 +125,7 @@ pub fn new_partial(
async fn start_node_impl<RB>(
parachain_config: Configuration,
collator_key: CollatorPair,
account_id: H160,
polkadot_config: Configuration,
id: polkadot_primitives::v0::Id,
validator: bool,
Expand All @@ -128,11 +152,7 @@ where
},
)?;

let params = new_partial(&parachain_config)?;
params
.inherent_data_providers
.register_provider(sp_timestamp::InherentDataProvider)
.unwrap();
let params = new_partial(&parachain_config, Some(account_id))?;

let client = params.client.clone();
let backend = params.backend.clone();
Expand Down Expand Up @@ -252,13 +272,15 @@ where
pub async fn start_node(
parachain_config: Configuration,
collator_key: CollatorPair,
account_id: H160,
polkadot_config: Configuration,
id: polkadot_primitives::v0::Id,
validator: bool,
) -> sc_service::error::Result<(TaskManager, Arc<FullClient>)> {
start_node_impl(
parachain_config,
collator_key,
account_id,
polkadot_config,
id,
validator,
Expand Down
10 changes: 6 additions & 4 deletions node/standalone/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions node/standalone/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ structopt = "0.3"
jsonrpc-core = "15.0.0"
jsonrpc-pubsub = "15.0.0"
serde_json = "1.0"
parity-scale-codec = "1.3.0"

sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "master" }
Expand Down Expand Up @@ -59,5 +60,7 @@ moonbeam-runtime = {path = "../../runtime", default-features = false, features =
moonbeam-rpc = { path = "../rpc" }
fc-consensus = { git = "https://github.com/purestake/frontier", branch = "v0.4-hotfixes" }

author-inherent = { path = "../../pallets/author-inherent"}

[build-dependencies]
substrate-build-script-utils = { git = "https://github.com/paritytech/substrate", branch = "master" }
8 changes: 7 additions & 1 deletion node/standalone/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ fn testnet_genesis(
accounts: BTreeMap::new(),
}),
pallet_ethereum: Some(EthereumConfig {}),
stake: Some(StakeConfig { stakers: vec![] }),
stake: Some(StakeConfig {
stakers: endowed_accounts
.iter()
.cloned()
.map(|k| (k, None, 100_000))
.collect(),
}),
}
}
13 changes: 12 additions & 1 deletion node/standalone/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Moonbeam. If not, see <http://www.gnu.org/licenses/>.

use sp_core::H160;
use structopt::StructOpt;

#[allow(missing_docs)]
Expand All @@ -24,8 +25,18 @@ pub struct RunCmd {
pub base: sc_cli::RunCmd,

/// Force using Kusama native runtime.
#[structopt(long = "manual-seal")]
#[structopt(long)]
pub manual_seal: bool,

/// Public identity for participating in staking and receiving rewards
#[structopt(long, parse(try_from_str = parse_h160))]
pub account_id: Option<H160>,
}

fn parse_h160(input: &str) -> Result<H160, String> {
input
.parse::<H160>()
.map_err(|_| "Failed to parse H160".to_string())
}

#[derive(Debug, StructOpt)]
Expand Down
Loading

0 comments on commit 22c4742

Please sign in to comment.