Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 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 @@ -30,6 +30,7 @@ members = [
"substrate/executor",
"substrate/keyring",
"substrate/network",
"substrate/misbehavior-check",
"substrate/primitives",
"substrate/rpc-servers",
"substrate/rpc",
Expand Down
1 change: 1 addition & 0 deletions polkadot/consensus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ parking_lot = "0.4"
tokio-timer = "0.1.2"
ed25519 = { path = "../../substrate/ed25519" }
error-chain = "0.11"
log = "0.4"
polkadot-api = { path = "../api" }
polkadot-collator = { path = "../collator" }
polkadot-primitives = { path = "../primitives" }
Expand Down
78 changes: 71 additions & 7 deletions polkadot/consensus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ extern crate substrate_primitives as primitives;
#[macro_use]
extern crate error_chain;

#[macro_use]
extern crate log;

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

Expand All @@ -55,9 +58,9 @@ use polkadot_api::{PolkadotApi, BlockBuilder};
use polkadot_primitives::{Hash, Timestamp};
use polkadot_primitives::block::Block as PolkadotBlock;
use polkadot_primitives::parachain::{Id as ParaId, DutyRoster, BlockData, Extrinsic, CandidateReceipt};
use primitives::block::{Block as SubstrateBlock, Header as SubstrateHeader, HeaderHash, Id as BlockId};
use primitives::block::{Block as SubstrateBlock, Header as SubstrateHeader, HeaderHash, Id as BlockId, Number as BlockNumber};
use primitives::AuthorityId;
use transaction_pool::TransactionPool;
use transaction_pool::{Ready, TransactionPool};

use futures::prelude::*;
use futures::future;
Expand Down Expand Up @@ -477,17 +480,19 @@ impl<C: PolkadotApi, N: Network> bft::ProposerFactory for ProposerFactory<C, N>
let duty_roster = self.client.duty_roster(&checked_id)?;

let group_info = make_group_info(duty_roster, authorities)?;
let table = Arc::new(SharedTable::new(group_info, sign_with, parent_hash));
let table = Arc::new(SharedTable::new(group_info, sign_with.clone(), parent_hash));
let router = self.network.table_router(table.clone());

// TODO [PoC-2]: kick off collation process.
Ok(Proposer {
parent_hash,
parent_number: parent_header.number,
parent_id: checked_id,
_table: table,
_router: router,
local_key: sign_with,
client: self.client.clone(),
transaction_pool: self.transaction_pool.clone(),
_table: table,
_router: router,
})
}
}
Expand All @@ -503,8 +508,10 @@ fn current_timestamp() -> Timestamp {
/// The Polkadot proposer logic.
pub struct Proposer<C: PolkadotApi, R> {
parent_hash: HeaderHash,
parent_number: BlockNumber,
parent_id: C::CheckedBlockId,
client: Arc<C>,
local_key: Arc<ed25519::Pair>,
transaction_pool: Arc<Mutex<TransactionPool>>,
_table: Arc<SharedTable>,
_router: R,
Expand All @@ -516,8 +523,6 @@ impl<C: PolkadotApi, R: TableRouter> bft::Proposer for Proposer<C, R> {
type Evaluate = Result<bool, Error>;

fn propose(&self) -> Result<SubstrateBlock, Error> {
use transaction_pool::Ready;

// TODO: handle case when current timestamp behind that in state.
let mut block_builder = self.client.build_block(
&self.parent_id,
Expand Down Expand Up @@ -565,6 +570,65 @@ impl<C: PolkadotApi, R: TableRouter> bft::Proposer for Proposer<C, R> {
fn evaluate(&self, proposal: &SubstrateBlock) -> Result<bool, Error> {
evaluate_proposal(proposal, &*self.client, current_timestamp(), &self.parent_hash, &self.parent_id)
}

fn import_misbehavior(&self, misbehavior: Vec<(AuthorityId, bft::Misbehavior)>) {
use bft::generic::Misbehavior as GenericMisbehavior;
use primitives::bft::{MisbehaviorKind, MisbehaviorReport};
use polkadot_primitives::transaction::{Function, Transaction, UncheckedTransaction};

let local_id = self.local_key.public().0;
let mut pool = self.transaction_pool.lock();
let mut next_nonce = {
let readiness_evaluator = Ready::create(self.parent_id.clone(), &*self.client);

let cur_nonce = pool.pending(readiness_evaluator)
.filter(|tx| tx.as_transaction().transaction.signed == local_id)
.last()
.map(|tx| Ok(tx.as_transaction().transaction.nonce))
.unwrap_or_else(|| self.client.nonce(&self.parent_id, local_id));

match cur_nonce {
Ok(cur_nonce) => cur_nonce + 1,
Err(e) => {
warn!(target: "consensus", "Error computing next transaction nonce: {}", e);
return;
}
}
};

for (target, misbehavior) in misbehavior {
let report = MisbehaviorReport {
parent_hash: self.parent_hash,
parent_number: self.parent_number,
target,
misbehavior: match misbehavior {
GenericMisbehavior::ProposeOutOfTurn(_, _, _) => continue,
GenericMisbehavior::DoublePropose(_, _, _) => continue,
Copy link
Contributor Author

@rphmeier rphmeier Mar 4, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these are blocked on paritytech/polkadot#85 -- right now the round proposer can't be evaluated on-chain.

GenericMisbehavior::DoublePrepare(round, (h1, s1), (h2, s2))
=> MisbehaviorKind::BftDoublePrepare(round as u32, (h1, s1.signature), (h2, s2.signature)),
GenericMisbehavior::DoubleCommit(round, (h1, s1), (h2, s2))
=> MisbehaviorKind::BftDoubleCommit(round as u32, (h1, s1.signature), (h2, s2.signature)),
}
};

let tx = Transaction {
signed: local_id,
nonce: next_nonce,
function: Function::ReportMisbehavior(report),
};

next_nonce += 1;

let message = tx.encode();
let signature = self.local_key.sign(&message);
let tx = UncheckedTransaction {
transaction: tx,
signature,
};

pool.import(tx).expect("locally signed transaction is valid; qed");
}
}
}

fn evaluate_proposal<C: PolkadotApi>(
Expand Down
2 changes: 1 addition & 1 deletion polkadot/executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ mod tests {
construct_block(
2,
block1().1,
hex!("c8776c92e8012bf6b3f206448eda3f00bca26d77f220f4714c81cbc92a30e1e2").into(),
hex!("5604fe023cd6effd93aec9b4a008398abdd32afb3fec988a19aa853ab0424a7c").into(),
200_000,
vec![
Transaction {
Expand Down
6 changes: 6 additions & 0 deletions polkadot/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,9 @@ pub type Signature = primitives::hash::H512;

/// A timestamp: seconds since the unix epoch.
pub type Timestamp = u64;

/// The balance of an account.
pub type Balance = u64;

/// The amount of bonding period left in an account. Measured in eras.
pub type Bondage = u64;
23 changes: 20 additions & 3 deletions polkadot/primitives/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

use rstd::vec::Vec;
use codec::{Input, Slicable};
use primitives::bft::MisbehaviorReport;
use ::Signature;

#[cfg(feature = "std")]
Expand Down Expand Up @@ -168,6 +169,8 @@ enum FunctionId {
StakingUnstake = 0x21,
/// Staking subsystem: transfer stake.
StakingTransfer = 0x22,
/// Report misbehavior.
StakingReportMisbehavior = 0x23,
/// Make a proposal for the governance system.
GovernancePropose = 0x30,
/// Approve a proposal for the governance system.
Expand All @@ -178,9 +181,16 @@ impl FunctionId {
/// Derive `Some` value from a `u8`, or `None` if it's invalid.
fn from_u8(value: u8) -> Option<FunctionId> {
use self::*;
let functions = [FunctionId::StakingStake, FunctionId::StakingUnstake,
FunctionId::StakingTransfer, FunctionId::SessionSetKey, FunctionId::TimestampSet,
FunctionId::GovernancePropose, FunctionId::GovernanceApprove];
let functions = [
FunctionId::StakingStake,
FunctionId::StakingUnstake,
FunctionId::StakingTransfer,
FunctionId::StakingReportMisbehavior,
FunctionId::SessionSetKey,
FunctionId::TimestampSet,
FunctionId::GovernancePropose,
FunctionId::GovernanceApprove,
];
functions.iter().map(|&f| f).find(|&f| value == f as u8)
}
}
Expand Down Expand Up @@ -222,6 +232,8 @@ pub enum Function {
StakingUnstake,
/// Staking subsystem: transfer stake.
StakingTransfer(::AccountId, u64),
/// Staking subsystem: report misbehavior of a validator.
ReportMisbehavior(MisbehaviorReport),
/// Make a proposal for the governance system.
GovernancePropose(Proposal),
/// Approve a proposal for the governance system.
Expand Down Expand Up @@ -269,6 +281,7 @@ impl Slicable for Function {

Function::StakingTransfer(to, amount)
}
FunctionId::StakingReportMisbehavior => Function::ReportMisbehavior(MisbehaviorReport::decode(input)?),
FunctionId::GovernancePropose =>
Function::GovernancePropose(try_opt!(Slicable::decode(input))),
FunctionId::GovernanceApprove =>
Expand All @@ -293,6 +306,10 @@ impl Slicable for Function {
Function::StakingUnstake => {
(FunctionId::StakingUnstake as u8).using_encoded(|s| v.extend(s));
}
Function::ReportMisbehavior(ref report) => {
(FunctionId::StakingReportMisbehavior as u8).using_encoded(|s| v.extend(s));
report.using_encoded(|s| v.extend(s));
}
Function::StakingTransfer(ref to, ref amount) => {
(FunctionId::StakingTransfer as u8).using_encoded(|s| v.extend(s));
to.using_encoded(|s| v.extend(s));
Expand Down
2 changes: 2 additions & 0 deletions polkadot/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ substrate-runtime-std = { path = "../../substrate/runtime-std" }
substrate-runtime-io = { path = "../../substrate/runtime-io" }
substrate-runtime-support = { path = "../../substrate/runtime-support" }
substrate-primitives = { path = "../../substrate/primitives" }
substrate-misbehavior-check = { path = "../../substrate/misbehavior-check" }
polkadot-primitives = { path = "../primitives" }

[dev-dependencies]
Expand All @@ -25,6 +26,7 @@ std = [
"substrate-runtime-io/std",
"substrate-runtime-support/std",
"substrate-primitives/std",
"substrate-misbehavior-check/std",
"polkadot-primitives/std",
"log"
]
2 changes: 0 additions & 2 deletions polkadot/runtime/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ pub struct Environment {
pub parent_hash: Hash,
/// The current block digest.
pub digest: Digest,
/// The current transaction index
pub transaction_index: u64,
}

/// Do something with the environment and return its value. Keep the function short.
Expand Down
3 changes: 1 addition & 2 deletions polkadot/runtime/src/genesismap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ use std::collections::HashMap;
use runtime_io::twox_128;
use runtime_support::Hashable;
use primitives::Block;
use polkadot_primitives::{BlockNumber, AccountId};
use runtime::staking::Balance;
use polkadot_primitives::{Balance, BlockNumber, AccountId};

/// Configuration of a general Polkadot genesis block.
pub struct GenesisConfig {
Expand Down
26 changes: 18 additions & 8 deletions polkadot/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,33 @@
#![cfg_attr(not(feature = "std"), no_std)]

extern crate substrate_runtime_std as rstd;
#[macro_use] extern crate substrate_runtime_io as runtime_io;
extern crate substrate_runtime_support as runtime_support;
#[cfg(all(feature = "std", test))] extern crate substrate_keyring as keyring;

#[cfg(feature = "std")] extern crate rustc_hex;

extern crate substrate_codec as codec;
#[cfg(feature = "std")] #[macro_use] extern crate substrate_primitives as primitives;
extern crate substrate_misbehavior_check as misbehavior_check;
extern crate polkadot_primitives;

#[cfg(test)] #[macro_use] extern crate hex_literal;
#[cfg(all(feature = "std", test))]
extern crate substrate_keyring as keyring;

#[cfg(feature = "std")]
extern crate rustc_hex;

#[cfg_attr(any(test, feature = "std"), macro_use)]
extern crate substrate_primitives as primitives;

#[macro_use]
extern crate substrate_runtime_io as runtime_io;

#[cfg(test)]
#[macro_use]
extern crate hex_literal;

pub mod api;
pub mod environment;
pub mod runtime;

#[cfg(feature = "std")] pub mod genesismap;
#[cfg(feature = "std")]
pub mod genesismap;

/// Type definitions and helpers for transactions.
pub mod transaction {
Expand Down
4 changes: 2 additions & 2 deletions polkadot/runtime/src/runtime/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use polkadot_primitives::SessionKey;
struct AuthorityStorageVec {}
impl StorageVec for AuthorityStorageVec {
type Item = SessionKey;
const PREFIX: &'static[u8] = b":auth:";
const PREFIX: &'static [u8] = b":auth:";
}

/// Get the current set of authorities. These are the session keys.
Expand All @@ -37,7 +37,7 @@ pub mod internal {
/// Set the current set of authorities' session keys.
///
/// Called by `next_session` only.
pub fn set_authorities(authorities: &[SessionKey]) {
pub fn set_authorities<'a, I: IntoIterator<Item=&'a SessionKey>>(authorities: I) {
AuthorityStorageVec::set_items(authorities);
}

Expand Down
Loading