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
2 changes: 2 additions & 0 deletions Cargo.lock

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

8 changes: 8 additions & 0 deletions core/sr-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ pub type Justification = Vec<u8>;

use traits::{Verify, Lazy};

/// A module identifier. These are per module and should be stored in a registry somewhere.
#[derive(Clone, Copy, Eq, PartialEq, Encode, Decode)]
pub struct ModuleId(pub [u8; 8]);

impl traits::TypeId for ModuleId {
const TYPE_ID: [u8; 4] = *b"modl";
}

/// A String that is a `&'static str` on `no_std` and a `Cow<'static, str>` on `std`.
#[cfg(feature = "std")]
pub type RuntimeString = ::std::borrow::Cow<'static, str>;
Expand Down
104 changes: 104 additions & 0 deletions core/sr-primitives/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,110 @@ pub trait OpaqueKeys: Clone {
fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool { true }
}

struct TrailingZeroInput<'a>(&'a [u8]);
impl<'a> codec::Input for TrailingZeroInput<'a> {
fn read(&mut self, into: &mut [u8]) -> usize {
let len = into.len().min(self.0.len());
into[..len].copy_from_slice(&self.0[..len]);
for i in &mut into[len..] {
*i = 0;
}
self.0 = &self.0[len..];
into.len()
}
}

/// This type can be converted into and possibly from an AccountId (which itself is generic).
pub trait AccountIdConversion<AccountId>: Sized {
/// Convert into an account ID. This is infallible.
fn into_account(&self) -> AccountId;

/// Try to convert an account ID into this type. Might not succeed.
fn try_from_account(a: &AccountId) -> Option<Self>;
}

/// Provide a simply 4 byte identifier for a type.
pub trait TypeId {
/// Simple 4 byte identifier.
const TYPE_ID: [u8; 4];
}

/// Format is TYPE_ID ++ encode(parachain ID) ++ 00.... where 00... is indefinite trailing zeroes to fill AccountId.
impl<T: Encode + Decode + Default, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
fn into_account(&self) -> T {
(Id::TYPE_ID, self).using_encoded(|b|
T::decode(&mut TrailingZeroInput(b))
).unwrap_or_default()
}

fn try_from_account(x: &T) -> Option<Self> {
x.using_encoded(|d| {
if &d[0..4] != Id::TYPE_ID { return None }
let mut cursor = &d[4..];
let result = Decode::decode(&mut cursor)?;
if cursor.iter().all(|x| *x == 0) {
Some(result)
} else {
None
}
})
}
}

#[cfg(test)]
mod tests {
use super::AccountIdConversion;
use crate::codec::{Encode, Decode};

#[derive(Encode, Decode, Default, PartialEq, Debug)]
struct U32Value(u32);
impl super::TypeId for U32Value {
const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
}
// cafef00d

#[derive(Encode, Decode, Default, PartialEq, Debug)]
struct U16Value(u16);
impl super::TypeId for U16Value {
const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
}
// f00dcafe

type AccountId = u64;

#[test]
fn into_account_should_work() {
let r: AccountId = U32Value::into_account(&U32Value(0xdeadbeef));
assert_eq!(r, 0x_deadbeef_cafef00d);
}

#[test]
fn try_from_account_should_work() {
let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
}

#[test]
fn into_account_with_fill_should_work() {
let r: AccountId = U16Value::into_account(&U16Value(0xc0da));
assert_eq!(r, 0x_0000_c0da_f00dcafe);
}

#[test]
fn try_from_account_with_fill_should_work() {
let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
assert_eq!(r.unwrap(), U16Value(0xc0da));
}

#[test]
fn bad_try_from_account_should_fail() {
let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
assert!(r.is_none());
let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
assert!(r.is_none());
}
}

/// Calls a given macro a number of times with a set of fixed params and an incrementing numeral.
/// e.g.
/// ```nocompile
Expand Down
1 change: 1 addition & 0 deletions core/test-runtime/wasm/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 node-template/runtime/wasm/Cargo.lock

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

30 changes: 29 additions & 1 deletion node/executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ mod tests {
use system::{EventRecord, Phase};
use node_runtime::{Header, Block, UncheckedExtrinsic, CheckedExtrinsic, Call, Runtime, Balances,
BuildStorage, GenesisConfig, BalancesConfig, SessionConfig, StakingConfig, System,
SystemConfig, GrandpaConfig, IndicesConfig, Event, SessionKeys};
SystemConfig, GrandpaConfig, IndicesConfig, Event, SessionKeys, Treasury};
use wabt;
use primitives::map;

Expand Down Expand Up @@ -566,6 +566,34 @@ mod tests {
event: Event::system(system::Event::ExtrinsicSuccess),
topics: vec![],
},
EventRecord {
phase: Phase::ApplyExtrinsic(1),
event: Event::indices(
indices::RawEvent::NewAccountIndex(Treasury::account_id(), 6)
),
topics: vec![],
},
EventRecord {
phase: Phase::ApplyExtrinsic(1),
event: Event::balances(
balances::RawEvent::NewAccount(Treasury::account_id(), 0)
),
topics: vec![],
},
EventRecord {
phase: Phase::ApplyExtrinsic(1),
event: Event::indices(
indices::RawEvent::NewAccountIndex(Default::default(), 7)
),
topics: vec![],
},
EventRecord {
phase: Phase::ApplyExtrinsic(1),
event: Event::balances(
balances::RawEvent::NewAccount(Default::default(), 1)
),
topics: vec![],
},
EventRecord {
phase: Phase::ApplyExtrinsic(1),
event: Event::balances(balances::RawEvent::Transfer(
Expand Down
2 changes: 2 additions & 0 deletions node/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ offchain-primitives = { package = "substrate-offchain-primitives", path = "../..
version = { package = "sr-version", path = "../../core/sr-version", default-features = false }
support = { package = "srml-support", path = "../../srml/support", default-features = false }
aura = { package = "srml-aura", path = "../../srml/aura", default-features = false }
authorship = { package = "srml-authorship", path = "../../srml/authorship", default-features = false }
balances = { package = "srml-balances", path = "../../srml/balances", default-features = false }
contracts = { package = "srml-contracts", path = "../../srml/contracts", default-features = false }
council = { package = "srml-council", path = "../../srml/council", default-features = false }
Expand Down Expand Up @@ -48,6 +49,7 @@ std = [
"runtime_primitives/std",
"support/std",
"aura/std",
"authorship/std",
"balances/std",
"contracts/std",
"council/std",
Expand Down
40 changes: 36 additions & 4 deletions node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
#![recursion_limit="256"]

use rstd::prelude::*;
use support::{construct_runtime, parameter_types};
use support::{
construct_runtime, parameter_types, traits::{SplitTwoWays, Currency, OnUnbalanced}
};
use substrate_primitives::u32_trait::{_1, _2, _3, _4};
use node_primitives::{
AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, Signature, AuraId
Expand Down Expand Up @@ -58,8 +60,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("node"),
impl_name: create_runtime_str!("substrate-node"),
authoring_version: 10,
spec_version: 99,
impl_version: 106,
spec_version: 100,
impl_version: 100,
apis: RUNTIME_API_VERSIONS,
};

Expand All @@ -72,6 +74,23 @@ pub fn native_version() -> NativeVersion {
}
}

type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;

pub struct Author;

impl OnUnbalanced<NegativeImbalance> for Author {
fn on_unbalanced(amount: NegativeImbalance) {
Balances::resolve_creating(&Authorship::author(), amount);
}
}

pub type DealWithFees = SplitTwoWays<
Balance,
NegativeImbalance,
_4, Treasury, // 4 parts (80%) goes to the treasury.
_1, Author, // 1 part (20%) goes to the block author.
>;

pub struct CurrencyToVoteHandler;

impl CurrencyToVoteHandler {
Expand Down Expand Up @@ -115,7 +134,7 @@ impl balances::Trait for Runtime {
type OnFreeBalanceZero = ((Staking, Contracts), Session);
type OnNewAccount = Indices;
type Event = Event;
type TransactionPayment = ();
type TransactionPayment = DealWithFees;
type DustRemoval = ();
type TransferPayment = ();
}
Expand All @@ -125,6 +144,18 @@ impl timestamp::Trait for Runtime {
type OnTimestampSet = Aura;
}

parameter_types! {
pub const UncleGenerations: u64 = 0;
}

// TODO: #2986 implement this properly
impl authorship::Trait for Runtime {
type FindAuthor = ();
type UncleGenerations = UncleGenerations;
type FilterUncle = ();
type EventHandler = ();
}

parameter_types! {
pub const Period: BlockNumber = 10 * MINUTES;
pub const Offset: BlockNumber = 0;
Expand Down Expand Up @@ -250,6 +281,7 @@ construct_runtime!(
System: system::{Module, Call, Storage, Config, Event},
Aura: aura::{Module, Config<T>, Inherent(Timestamp)},
Timestamp: timestamp::{Module, Call, Storage, Config<T>, Inherent},
Authorship: authorship::{Module, Call, Storage},
Indices: indices,
Balances: balances,
Session: session::{Module, Call, Storage, Event, Config<T>},
Expand Down
15 changes: 15 additions & 0 deletions node/runtime/wasm/Cargo.lock

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

15 changes: 13 additions & 2 deletions srml/authorship/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
//!
//! This tracks the current author of the block and recent uncles.

#![cfg_attr(not(feature = "std"), no_std)]

use rstd::prelude::*;
use rstd::collections::btree_set::BTreeSet;
use srml_support::{decl_module, decl_storage, for_each_tuple, StorageValue};
Expand Down Expand Up @@ -102,6 +104,15 @@ pub trait FilterUncle<Header, Author> {
-> Result<(Option<Author>, Self::Accumulator), &'static str>;
}

impl<H, A> FilterUncle<H, A> for () {
type Accumulator = ();
fn filter_uncle(_: &H, acc: Self::Accumulator)
-> Result<(Option<A>, Self::Accumulator), &'static str>
{
Ok((None, acc))
}
}

/// A filter on uncles which verifies seals and does no additional checks.
/// This is well-suited to consensus modes such as PoW where the cost of
/// equivocating is high.
Expand Down Expand Up @@ -201,8 +212,8 @@ decl_module! {

fn on_finalize() {
// ensure we never go to trie with these values.
let _ = <Self as Store>::Author::take();
let _ = <Self as Store>::DidSetUncles::take();
<Self as Store>::Author::kill();
<Self as Store>::DidSetUncles::kill();
}

/// Provide a set of uncles.
Expand Down
Loading