Skip to content

Commit

Permalink
Feature/block producer (paritytech#99)
Browse files Browse the repository at this point in the history
* cx system init
* provide a new inherent tx for block_producer
  • Loading branch information
Aton authored and gguoss committed Nov 16, 2018
1 parent c808b6f commit 296df2e
Show file tree
Hide file tree
Showing 12 changed files with 207 additions and 12 deletions.
18 changes: 18 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ members = [
"pool",
"rpc",
"api",
"cxrml/system",
"cxrml/support",
"cxrml/tokenbalances",
"cxrml/staking",
Expand Down
26 changes: 18 additions & 8 deletions consensus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,12 @@ impl<C> bft::Proposer<Block> for Proposer<C>
)
}

let block_producer: AccountId = self.local_key.public().0.into();

let inherent_data = InherentData {
timestamp,
offline_indices,
block_producer: block_producer.clone(),
};

let mut block_builder = self.client.build_block(&self.parent_id, inherent_data)?;
Expand Down Expand Up @@ -259,15 +262,15 @@ impl<C> bft::Proposer<Block> for Proposer<C>
}

let block = block_builder.bake()?;

info!("generate a new block#{:}, producer:[{:}]", block.header.number, block_producer);
trace!("Proposing block [number: {}; hash: {}; parent_hash: {}; extrinsics: [{}]]",
block.header.number,
Hash::from(block.header.hash()),
block.header.parent_hash,
block.extrinsics.iter()
.map(|xt| format!("{}", BlakeTwo256::hash_of(xt)))
.collect::<Vec<_>>()
.join(", ")
block.header.number,
Hash::from(block.header.hash()),
block.header.parent_hash,
block.extrinsics.iter()
.map(|xt| format!("{}", BlakeTwo256::hash_of(xt)))
.collect::<Vec<_>>()
.join(", ")
);

let substrate_block = Decode::decode(&mut block.encode().as_slice())
Expand Down Expand Up @@ -337,6 +340,13 @@ impl<C> bft::Proposer<Block> for Proposer<C>
return Box::new(futures::empty());
}

// check block_producer
match proposal.block_producer() {
Some(a) => { info!("current block#{:}, producer is [{:}]", self.parent_number + 1, a); }
None => { info!("current block#{:}, not set producer", self.parent_number + 1); }
}


// evaluate whether the block is actually valid.
// TODO: is it better to delay this until the delays are finished?
let evaluated = self.client
Expand Down
34 changes: 34 additions & 0 deletions cxrml/system/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[package]
name = "cxrml-system"
version = "0.1.0"
authors = ["Chainpool <http://chainx.org>"]


[dependencies]
hex-literal = "0.1.0"
serde = { version = "1.0", default_features = false }
serde_derive = { version = "1.0", optional = true }
parity-codec = { version = "2.0", default-features = false }
parity-codec-derive = { version = "2.0", default-features = false }
substrate-primitives = { git = "https://github.com/paritytech/substrate", default_features = false }
sr-std = { git = "https://github.com/paritytech/substrate", default_features = false }
sr-io = { git = "https://github.com/paritytech/substrate", default_features = false }
sr-primitives = { git = "https://github.com/paritytech/substrate", default_features = false }
srml-support = { git = "https://github.com/paritytech/substrate", default_features = false }
srml-system = { git = "https://github.com/paritytech/substrate", default_features = false }


[features]
default = ["std"]
std=[
"serde/std",
"serde_derive",
"parity-codec/std",
"parity-codec-derive/std",
"substrate-primitives/std",
"sr-std/std",
"sr-io/std",
"sr-primitives/std",
"srml-support/std",
"srml-system/std",
]
78 changes: 78 additions & 0 deletions cxrml/system/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//! this module is for bch-bridge

#![cfg_attr(not(feature = "std"), no_std)]
// for encode/decode
// Needed for deriving `Serialize` and `Deserialize` for various types.
// We only implement the serde traits for std builds - they're unneeded
// in the wasm runtime.
#[cfg(feature = "std")]
#[macro_use]
extern crate serde_derive;

// Needed for deriving `Encode` and `Decode` for `RawEvent`.
//#[macro_use]
//extern crate parity_codec_derive;
extern crate parity_codec as codec;

// for substrate
// Needed for the set of mock primitives used in our tests.
#[cfg(feature = "std")]
extern crate substrate_primitives;

// for substrate runtime
// map!, vec! marco.
extern crate sr_std as rstd;
// Needed for tests (`with_externalities`).
#[cfg(feature = "std")]
extern crate sr_io as runtime_io;
extern crate sr_primitives as runtime_primitives;
// for substrate runtime module lib
// Needed for type-safe access to storage DB.
#[macro_use]
extern crate srml_support as runtime_support;
extern crate srml_system as system;

#[cfg(test)]
mod tests;

//use codec::{Codec, Decode, Encode};
use rstd::prelude::*;
//use rstd::marker::PhantomData;
//use rstd::result::Result as StdResult;
use runtime_support::dispatch::Result;
use runtime_support::StorageValue;
use runtime_primitives::traits::OnFinalise;

use system::ensure_inherent;


pub trait Trait: system::Trait {}


decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn set_block_producer(origin, producer: T::AccountId) -> Result;
}
}

impl<T: Trait> OnFinalise<T::BlockNumber> for Module<T> {
fn on_finalise(_: T::BlockNumber) {
BlockProdocer::<T>::kill();
}
}

decl_storage! {
trait Store for Module<T: Trait> as CXSystem {
pub BlockProdocer get(block_producer) config(): Option<T::AccountId>;
}
}

impl<T: Trait> Module<T> {
fn set_block_producer(origin: T::Origin, producer: T::AccountId) -> Result {
ensure_inherent(origin)?;
BlockProdocer::<T>::put(producer);
Ok(())
}
}


4 changes: 4 additions & 0 deletions cxrml/system/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
2 changes: 2 additions & 0 deletions primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ pub struct InherentData {
pub timestamp: Timestamp,
/// Indices of offline validators.
pub offline_indices: Vec<u32>,
/// block producer
pub block_producer: AccountId,
}

/// Candidate receipt type.
Expand Down
2 changes: 2 additions & 0 deletions runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ sr-version = { git = "https://github.com/paritytech/substrate" }
chainx-primitives = { path = "../primitives" }

# chainx runtime module
cxrml-system = { path = "../cxrml/system" }
cxrml-support = { path = "../cxrml/support" }
cxrml-staking = { path = "../cxrml/staking" }
cxrml-tokenbalances = { path = "../cxrml/tokenbalances" }
Expand Down Expand Up @@ -65,6 +66,7 @@ std = [
"serde_derive",
"serde/std",
"safe-mix/std",
"cxrml-system/std",
"cxrml-support/std",
"cxrml-staking/std",
"cxrml-tokenbalances/std",
Expand Down
13 changes: 12 additions & 1 deletion runtime/src/checked_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

//! Typesafe block interaction.

use super::{Call, Block, TIMESTAMP_SET_POSITION, NOTE_OFFLINE_POSITION};
use super::{Call, Block, AccountId, TIMESTAMP_SET_POSITION, NOTE_OFFLINE_POSITION, BLOCK_PRODUCER_POSITION};
use timestamp::Call as TimestampCall;
//use session::Call as SessionCall;
use cxsystem::Call as CXSystemCall;

/// Provides a type-safe wrapper around a structurally valid block.
pub struct CheckedBlock {
Expand Down Expand Up @@ -73,6 +74,16 @@ impl CheckedBlock {
.unwrap_or(&[])
}

pub fn block_producer(&self) -> Option<AccountId> {
self.inner
.extrinsics
.get(BLOCK_PRODUCER_POSITION as usize)
.and_then(|xt| match xt.function {
Call::CXSystem(CXSystemCall::set_block_producer(x)) => Some(x),
_ => None,
})
}

/// Convert into inner block.
pub fn into_inner(self) -> Block {
self.inner
Expand Down
21 changes: 18 additions & 3 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ extern crate srml_system as system;
extern crate srml_timestamp as timestamp;
extern crate srml_treasury as treasury;
// cx runtime module
extern crate cxrml_system as cxsystem;
extern crate cxrml_support as cxsupport;
extern crate cxrml_staking as staking;
extern crate cxrml_tokenbalances as tokenbalances;
Expand All @@ -60,14 +61,15 @@ mod checked_block;
pub use balances::address::Address as RawAddress;
#[cfg(feature = "std")]
pub use checked_block::CheckedBlock;
pub use consensus::Call as ConsensusCall;
pub use runtime_primitives::{Permill, Perbill};
pub use tokenbalances::Token;

use rstd::prelude::*;
use substrate_primitives::u32_trait::{_2, _4};
use chainx_primitives::{AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, SessionKey, Signature};
use timestamp::Call as TimestampCall;
pub use consensus::Call as ConsensusCall;
use cxsystem::Call as CXSystemCall;
use chainx_primitives::InherentData;
use runtime_primitives::generic;
use runtime_primitives::traits::{Convert, BlakeTwo256, DigestItem};
Expand All @@ -90,6 +92,10 @@ pub fn inherent_extrinsics(data: InherentData) -> Vec<UncheckedExtrinsic> {
Call::Timestamp(TimestampCall::set(data.timestamp))
)];

inherent.push(generic::UncheckedMortalExtrinsic::new_unsigned(
Call::CXSystem(CXSystemCall::set_block_producer(data.block_producer))
));

if !data.offline_indices.is_empty() {
inherent.push(generic::UncheckedMortalExtrinsic::new_unsigned(
Call::Consensus(ConsensusCall::note_offline(data.offline_indices))
Expand All @@ -110,6 +116,8 @@ pub const TIMESTAMP_SET_POSITION: u32 = 0;
/// The position of the offline nodes noting extrinsic.
pub const NOTE_OFFLINE_POSITION: u32 = 2;

pub const BLOCK_PRODUCER_POSITION: u32 = 1;

/// Runtime version.
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: ver_str!("chainx"),
Expand Down Expand Up @@ -215,6 +223,12 @@ impl council::motions::Trait for Runtime {
type Event = Event;
}

// cxrml trait

impl cxsystem::Trait for Runtime {}

impl cxsupport::Trait for Runtime {}

impl tokenbalances::Trait for Runtime {
const CHAINX_SYMBOL: tokenbalances::SymbolString = b"pcx";
const CHAINX_TOKEN_DESC: tokenbalances::DescString = b"pcx token for ChainX";
Expand Down Expand Up @@ -250,8 +264,6 @@ impl matchorder::Trait for Runtime {
type Event = Event;
}

impl cxsupport::Trait for Runtime {}


impl DigestItem for Log {
type Hash = Hash;
Expand Down Expand Up @@ -286,6 +298,7 @@ construct_runtime!(
CouncilMotions: council_motions::{Module, Call, Storage, Event<T>, Origin},
Treasury: treasury,
Contract: contract::{Module, Call, Config, Event<T>},
// chainx runtime module
TokenBalances: tokenbalances,
MultiSig: multisig,
// funds
Expand All @@ -299,6 +312,8 @@ construct_runtime!(

// put end of this marco
CXSupport: cxsupport::{Module},
// must put end of all chainx runtime module
CXSystem: cxsystem::{Module, Call, Storage},
}
);

Expand Down
18 changes: 18 additions & 0 deletions runtime/wasm/Cargo.lock

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

2 changes: 2 additions & 0 deletions runtime/wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ sr-version = { git = "https://github.com/paritytech/substrate", default-features
chainx-primitives = { path = "../../primitives", default-features = false }

# chainx runtime module
cxrml-system = { path = "../../cxrml/system", default-features = false }
cxrml-support = { path = "../../cxrml/support", default-features = false }
cxrml-staking = { path = "../../cxrml/staking", default-features = false }
cxrml-tokenbalances = { path = "../../cxrml/tokenbalances", default-features = false }
Expand Down Expand Up @@ -64,6 +65,7 @@ std = [
"srml-treasury/std",
"sr-version/std",
"chainx-primitives/std",
"cxrml-system/std",
"cxrml-support/std",
"cxrml-staking/std",
"cxrml-tokenbalances/std",
Expand Down

0 comments on commit 296df2e

Please sign in to comment.