Bump Substrate (#816)

* Amalgamate pieces of balance module

* Fixes for vesting split

* Refactoring for vesting/balances split

* Build fixes

* Remove on_free_balance_zero and some docs.

* Indentation.

* Revert branch

* Fix.

* Update substrate: fixes after CLI refactoring

* Reverting removal of exit

* Removed too much again

* Update Cargo.lock

* Cargo.lock

* Update Substrate, ready for #4820

* Fixes

* Update to latest substrate master

* Fix network tests

* Update lock

* Fix tests

* Update futures to get bug fixes

* Fix tests for new balances/vesting logic

* Cargo fix

* Another fix

Co-authored-by: Cecile Tonglet <cecile.tonglet@cecton.com>
Co-authored-by: Robert Habermeier <rphmeier@gmail.com>
Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Gavin Wood
2020-02-09 17:50:17 +01:00
committed by GitHub
parent 9a2bba3ba1
commit 703ac8bbbc
27 changed files with 1449 additions and 1509 deletions
+1160 -1205
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -11,8 +11,7 @@ edition = "2018"
[dependencies]
cli = { package = "polkadot-cli", path = "cli" }
futures = "0.3.1"
ctrlc = { version = "3.1.3", features = ["termination"] }
futures = "0.3.4"
service = { package = "polkadot-service", path = "service" }
[build-dependencies]
+1 -1
View File
@@ -11,7 +11,7 @@ polkadot-erasure-coding = { path = "../erasure-coding" }
parking_lot = "0.9.0"
derive_more = "0.99"
log = "0.4.8"
futures = "0.3.1"
futures = "0.3.4"
tokio = { version = "0.2.10", features = ["rt-core"] }
exit-future = "0.2.0"
codec = { package = "parity-scale-codec", version = "1.1.0", features = ["derive"] }
+1 -1
View File
@@ -10,7 +10,7 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
log = "0.4.8"
futures = { version = "0.3.1", features = ["compat"] }
futures = { version = "0.3.4", features = ["compat"] }
structopt = "0.3.8"
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master", optional = true }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
+4 -2
View File
@@ -32,7 +32,8 @@ pub fn run(version: VersionInfo) -> error::Result<()> {
match opt.subcommand {
None => {
sc_cli::init(&mut config, load_spec, &opt.run.shared_params, &version)?;
sc_cli::init(&opt.run.shared_params, &version)?;
sc_cli::init_config(&mut config, &opt.run.shared_params, &version, load_spec)?;
let is_kusama = config.chain_spec.as_ref().map_or(false, |s| s.is_kusama());
@@ -72,7 +73,8 @@ pub fn run(version: VersionInfo) -> error::Result<()> {
}
},
Some(Subcommand::Base(cmd)) => {
sc_cli::init(&mut config, load_spec, cmd.get_shared_params(), &version)?;
sc_cli::init(cmd.get_shared_params(), &version)?;
sc_cli::init_config(&mut config, &opt.run.shared_params, &version, load_spec)?;
let is_kusama = config.chain_spec.as_ref().map_or(false, |s| s.is_kusama());
+1 -1
View File
@@ -6,7 +6,7 @@ description = "Collator node implementation"
edition = "2018"
[dependencies]
futures = "0.3.1"
futures = "0.3.4"
sc-client = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
+44 -55
View File
@@ -90,9 +90,8 @@ pub trait Network: Send + Sync {
fn checked_statements(&self, relay_parent: Hash) -> Box<dyn Stream<Item=SignedStatement>>;
}
impl<P, E, SP> Network for ValidationNetwork<P, E, SP> where
impl<P, SP> Network for ValidationNetwork<P, SP> where
P: 'static + Send + Sync,
E: 'static + Send + Sync,
SP: 'static + Spawn + Clone + Send + Sync,
{
fn collator_id_to_peer_id(&self, collator_id: CollatorId) ->
@@ -239,16 +238,15 @@ pub async fn collate<R, P>(
}
/// Polkadot-api context.
struct ApiContext<P, E, SP> {
network: Arc<ValidationNetwork<P, E, SP>>,
struct ApiContext<P, SP> {
network: Arc<ValidationNetwork<P, SP>>,
parent_hash: Hash,
validators: Vec<ValidatorId>,
}
impl<P: 'static, E: 'static, SP: 'static> RelayChainContext for ApiContext<P, E, SP> where
impl<P: 'static, SP: 'static> RelayChainContext for ApiContext<P, SP> where
P: ProvideRuntimeApi<Block> + Send + Sync,
P::Api: ParachainHost<Block>,
E: futures::Future<Output=()> + Clone + Send + Sync + 'static,
SP: Spawn + Clone + Send + Sync
{
type Error = String;
@@ -276,13 +274,12 @@ impl<P: 'static, E: 'static, SP: 'static> RelayChainContext for ApiContext<P, E,
}
/// Run the collator node using the given `service`.
fn run_collator_node<S, E, P, Extrinsic>(
fn run_collator_node<S, P, Extrinsic>(
service: S,
exit: E,
para_id: ParaId,
key: Arc<CollatorPair>,
build_parachain_context: P,
) -> polkadot_cli::error::Result<()>
) -> Result<S, polkadot_service::Error>
where
S: AbstractService<Block = service::Block, NetworkSpecialization = service::PolkadotProtocol>,
sc_client::Client<S::Backend, S::CallExecutor, service::Block, S::RuntimeApi>: ProvideRuntimeApi<Block>,
@@ -301,7 +298,6 @@ fn run_collator_node<S, E, P, Extrinsic>(
S::CallExecutor: service::CallExecutor<service::Block>,
// Rust bug: https://github.com/rust-lang/rust/issues/24159
S::SelectChain: service::SelectChain<service::Block>,
E: futures::Future<Output=()> + Clone + Unpin + Send + Sync + 'static,
P: BuildParachainContext,
P::ParachainContext: Send + 'static,
<P::ParachainContext as ParachainContext>::ProduceCandidate: Send,
@@ -315,7 +311,7 @@ fn run_collator_node<S, E, P, Extrinsic>(
let select_chain = if let Some(select_chain) = service.select_chain() {
select_chain
} else {
return Err(polkadot_cli::error::Error::Other("The node cannot work because it can't select chain.".into()))
return Err("The node cannot work because it can't select chain.".into())
};
let is_known = move |block_hash: &Hash| {
@@ -345,7 +341,6 @@ fn run_collator_node<S, E, P, Extrinsic>(
let validation_network = Arc::new(ValidationNetwork::new(
message_validator,
exit.clone(),
client.clone(),
spawner.clone(),
));
@@ -357,11 +352,10 @@ fn run_collator_node<S, E, P, Extrinsic>(
) {
Ok(ctx) => ctx,
Err(()) => {
return Err(polkadot_cli::error::Error::Other("Could not build the parachain context!".into()))
return Err("Could not build the parachain context!".into())
}
};
let inner_exit = exit.clone();
let work = async move {
let mut notification_stream = client.import_notification_stream();
@@ -385,7 +379,6 @@ fn run_collator_node<S, E, P, Extrinsic>(
let key = key.clone();
let parachain_context = parachain_context.clone();
let validation_network = validation_network.clone();
let inner_exit_2 = inner_exit.clone();
let work = future::lazy(move |_| async move {
let api = client.runtime_api();
@@ -425,8 +418,7 @@ fn run_collator_node<S, E, P, Extrinsic>(
outgoing,
);
let exit = inner_exit_2.clone();
tokio::spawn(future::select(res.boxed(), exit));
tokio::spawn(res.boxed());
});
}
future::ok(())
@@ -444,10 +436,7 @@ fn run_collator_node<S, E, P, Extrinsic>(
}
});
let future = future::select(
silenced,
inner_exit.clone()
).map(drop);
let future = silenced.map(drop);
tokio::spawn(future);
}
@@ -455,8 +444,7 @@ fn run_collator_node<S, E, P, Extrinsic>(
service.spawn_essential_task("collation", work);
// NOTE: this is not ideal as we should only provide the service
sc_cli::run_service_until_exit(Configuration::default(), |_config| Ok(service))
Ok(service)
}
fn compute_targets(para_id: ParaId, session_keys: &[ValidatorId], roster: DutyRoster) -> HashSet<ValidatorId> {
@@ -472,53 +460,54 @@ fn compute_targets(para_id: ParaId, session_keys: &[ValidatorId], roster: DutyRo
/// Run a collator node with the given `RelayChainContext` and `ParachainContext`
/// build by the given `BuildParachainContext` and arguments to the underlying polkadot node.
///
/// Provide a future which resolves when the node should exit.
/// This function blocks until done.
pub fn run_collator<P, E>(
pub fn run_collator<P>(
build_parachain_context: P,
para_id: ParaId,
exit: E,
key: Arc<CollatorPair>,
config: Configuration,
) -> polkadot_cli::error::Result<()> where
P: BuildParachainContext,
P::ParachainContext: Send + 'static,
<P::ParachainContext as ParachainContext>::ProduceCandidate: Send,
E: futures::Future<Output = ()> + Unpin + Send + Clone + Sync + 'static,
{
match (config.expect_chain_spec().is_kusama(), config.roles) {
(true, Roles::LIGHT) =>
run_collator_node(
service::kusama_new_light(config, Some((key.public(), para_id)))?,
exit,
para_id,
key,
build_parachain_context,
),
sc_cli::run_service_until_exit(config, |config| {
run_collator_node(
service::kusama_new_light(config, Some((key.public(), para_id)))?,
para_id,
key,
build_parachain_context,
)
}),
(true, _) =>
run_collator_node(
service::kusama_new_full(config, Some((key.public(), para_id)), None, false, 6000)?,
exit,
para_id,
key,
build_parachain_context,
),
sc_cli::run_service_until_exit(config, |config| {
run_collator_node(
service::kusama_new_full(config, Some((key.public(), para_id)), None, false, 6000)?,
para_id,
key,
build_parachain_context,
)
}),
(false, Roles::LIGHT) =>
run_collator_node(
service::polkadot_new_light(config, Some((key.public(), para_id)))?,
exit,
para_id,
key,
build_parachain_context,
),
sc_cli::run_service_until_exit(config, |config| {
run_collator_node(
service::polkadot_new_light(config, Some((key.public(), para_id)))?,
para_id,
key,
build_parachain_context,
)
}),
(false, _) =>
run_collator_node(
service::polkadot_new_full(config, Some((key.public(), para_id)), None, false, 6000)?,
exit,
para_id,
key,
build_parachain_context,
),
sc_cli::run_service_until_exit(config, |config| {
run_collator_node(
service::polkadot_new_full(config, Some((key.public(), para_id)), None, false, 6000)?,
para_id,
key,
build_parachain_context,
)
}),
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkad
sc-network-gossip = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
futures = "0.3.1"
futures = "0.3.4"
log = "0.4.8"
exit-future = "0.2.0"
sc-client = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
+10 -13
View File
@@ -35,7 +35,7 @@ use crate::gossip::{RegisteredMessageValidator, GossipMessage, GossipStatement,
use sp_api::ProvideRuntimeApi;
use futures::prelude::*;
use futures::{task::SpawnExt, future::{ready, select}};
use futures::{task::SpawnExt, future::ready};
use parking_lot::Mutex;
use log::{debug, trace};
@@ -73,18 +73,18 @@ pub(crate) fn checked_statements<N: NetworkService>(network: &N, topic: Hash) ->
}
/// Table routing implementation.
pub struct Router<P, E, T> {
pub struct Router<P, T> {
table: Arc<SharedTable>,
attestation_topic: Hash,
fetcher: LeafWorkDataFetcher<P, E, T>,
fetcher: LeafWorkDataFetcher<P, T>,
deferred_statements: Arc<Mutex<DeferredStatements>>,
message_validator: RegisteredMessageValidator,
}
impl<P, E, T> Router<P, E, T> {
impl<P, T> Router<P, T> {
pub(crate) fn new(
table: Arc<SharedTable>,
fetcher: LeafWorkDataFetcher<P, E, T>,
fetcher: LeafWorkDataFetcher<P, T>,
message_validator: RegisteredMessageValidator,
) -> Self {
let parent_hash = fetcher.parent_hash();
@@ -116,7 +116,7 @@ impl<P, E, T> Router<P, E, T> {
}
}
impl<P, E: Clone, T: Clone> Clone for Router<P, E, T> {
impl<P, T: Clone> Clone for Router<P, T> {
fn clone(&self) -> Self {
Router {
table: self.table.clone(),
@@ -128,10 +128,9 @@ impl<P, E: Clone, T: Clone> Clone for Router<P, E, T> {
}
}
impl<P: ProvideRuntimeApi<Block> + Send + Sync + 'static, E, T> Router<P, E, T> where
impl<P: ProvideRuntimeApi<Block> + Send + Sync + 'static, T> Router<P, T> where
P::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
T: Clone + Executor + Send + 'static,
E: Future<Output=()> + Clone + Send + Unpin + 'static,
{
/// Import a statement whose signature has been checked already.
pub(crate) fn import_statement(&self, statement: SignedStatement) {
@@ -176,8 +175,7 @@ impl<P: ProvideRuntimeApi<Block> + Send + Sync + 'static, E, T> Router<P, E, T>
if let Some(work) = producer.map(|p| self.create_work(c_hash, p)) {
trace!(target: "validation", "driving statement work to completion");
let work = select(work.boxed(), self.fetcher.exit().clone())
.map(drop);
let work = work.boxed().map(drop);
let _ = self.fetcher.executor().spawn(work);
}
}
@@ -226,10 +224,9 @@ impl<P: ProvideRuntimeApi<Block> + Send + Sync + 'static, E, T> Router<P, E, T>
}
}
impl<P: ProvideRuntimeApi<Block> + Send, E, T> TableRouter for Router<P, E, T> where
impl<P: ProvideRuntimeApi<Block> + Send, T> TableRouter for Router<P, T> where
P::Api: ParachainHost<Block>,
T: Clone + Executor + Send + 'static,
E: Future<Output=()> + Clone + Send + 'static,
{
type Error = io::Error;
type FetchValidationProof = Pin<Box<dyn Future<Output = Result<PoVBlock, io::Error>> + Send>>;
@@ -283,7 +280,7 @@ impl<P: ProvideRuntimeApi<Block> + Send, E, T> TableRouter for Router<P, E, T> w
}
}
impl<P, E, T> Drop for Router<P, E, T> {
impl<P, T> Drop for Router<P, T> {
fn drop(&mut self) {
let parent_hash = self.parent_hash();
self.network().with_spec(move |spec, _| { spec.remove_validation_session(parent_hash); });
+1 -6
View File
@@ -319,11 +319,7 @@ impl ParachainHost<Block> for RuntimeApi {
}
}
type TestValidationNetwork<SP> = crate::validation::ValidationNetwork<
TestApi,
NeverExit,
SP,
>;
type TestValidationNetwork<SP> = crate::validation::ValidationNetwork<TestApi, SP>;
struct Built<SP> {
gossip: Pin<Box<dyn Future<Output = ()>>>,
@@ -349,7 +345,6 @@ fn build_network<SP: Spawn + Clone>(n: usize, spawner: SP) -> Built<SP> {
TestValidationNetwork::new(
message_val,
NeverExit,
runtime_api.clone(),
spawner.clone(),
)
+14 -29
View File
@@ -62,40 +62,36 @@ pub struct LeafWorkParams {
}
/// Wrapper around the network service
pub struct ValidationNetwork<P, E, T> {
pub struct ValidationNetwork<P, T> {
api: Arc<P>,
executor: T,
network: RegisteredMessageValidator,
exit: E,
}
impl<P, E, T> ValidationNetwork<P, E, T> {
impl<P, T> ValidationNetwork<P, T> {
/// Create a new consensus networking object.
pub fn new(
network: RegisteredMessageValidator,
exit: E,
api: Arc<P>,
executor: T,
) -> Self {
ValidationNetwork { network, exit, api, executor }
ValidationNetwork { network, api, executor }
}
}
impl<P, E: Clone, T: Clone> Clone for ValidationNetwork<P, E, T> {
impl<P, T: Clone> Clone for ValidationNetwork<P, T> {
fn clone(&self) -> Self {
ValidationNetwork {
network: self.network.clone(),
exit: self.exit.clone(),
api: self.api.clone(),
executor: self.executor.clone(),
}
}
}
impl<P, E, T> ValidationNetwork<P, E, T> where
impl<P, T> ValidationNetwork<P, T> where
P: ProvideRuntimeApi<Block> + Send + Sync + 'static,
P::Api: ParachainHost<Block>,
E: Clone + Future<Output=()> + Send + Sync + 'static,
T: Clone + Executor + Send + Sync + 'static,
{
/// Instantiate block-DAG leaf work
@@ -113,13 +109,12 @@ impl<P, E, T> ValidationNetwork<P, E, T> where
/// leaf-work instances safely, but they should all be coordinated on which session keys
/// are being used.
pub fn instantiate_leaf_work(&self, params: LeafWorkParams)
-> oneshot::Receiver<LeafWorkDataFetcher<P, E, T>>
-> oneshot::Receiver<LeafWorkDataFetcher<P, T>>
{
let parent_hash = params.parent_hash;
let network = self.network.clone();
let api = self.api.clone();
let task_executor = self.executor.clone();
let exit = self.exit.clone();
let authorities = params.authorities.clone();
let (tx, rx) = oneshot::channel();
@@ -141,7 +136,6 @@ impl<P, E, T> ValidationNetwork<P, E, T> where
task_executor,
parent_hash,
knowledge: work.knowledge().clone(),
exit,
});
});
@@ -149,7 +143,7 @@ impl<P, E, T> ValidationNetwork<P, E, T> where
}
}
impl<P, E, T> ValidationNetwork<P, E, T> {
impl<P, T> ValidationNetwork<P, T> {
/// Convert the given `CollatorId` to a `PeerId`.
pub fn collator_id_to_peer_id(&self, collator_id: CollatorId) ->
impl Future<Output=Option<PeerId>> + Send
@@ -176,14 +170,13 @@ impl<P, E, T> ValidationNetwork<P, E, T> {
}
/// A long-lived network which can create parachain statement routing processes on demand.
impl<P, E, T> ParachainNetwork for ValidationNetwork<P, E, T> where
impl<P, T> ParachainNetwork for ValidationNetwork<P, T> where
P: ProvideRuntimeApi<Block> + Send + Sync + 'static,
P::Api: ParachainHost<Block, Error = sp_blockchain::Error>,
E: Clone + Future<Output=()> + Send + Sync + Unpin + 'static,
T: Clone + Executor + Send + Sync + 'static,
{
type Error = String;
type TableRouter = Router<P, E, T>;
type TableRouter = Router<P, T>;
type BuildTableRouter = Box<dyn Future<Output=Result<Self::TableRouter, String>> + Send + Unpin>;
fn communication_for(
@@ -234,7 +227,7 @@ impl<P, E, T> ParachainNetwork for ValidationNetwork<P, E, T> where
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NetworkDown;
impl<P, E: Clone, N: Clone> Collators for ValidationNetwork<P, E, N> where
impl<P, N: Clone> Collators for ValidationNetwork<P, N> where
P: ProvideRuntimeApi<Block> + Send + Sync + 'static,
P::Api: ParachainHost<Block>,
{
@@ -518,16 +511,15 @@ impl LiveValidationLeaves {
}
/// Can fetch data for a given validation leaf-work instance.
pub struct LeafWorkDataFetcher<P, E, T> {
pub struct LeafWorkDataFetcher<P, T> {
network: RegisteredMessageValidator,
api: Arc<P>,
exit: E,
task_executor: T,
knowledge: Arc<Mutex<Knowledge>>,
parent_hash: Hash,
}
impl<P, E, T> LeafWorkDataFetcher<P, E, T> {
impl<P, T> LeafWorkDataFetcher<P, T> {
/// Get the parent hash.
pub(crate) fn parent_hash(&self) -> Hash {
self.parent_hash
@@ -538,11 +530,6 @@ impl<P, E, T> LeafWorkDataFetcher<P, E, T> {
&self.knowledge
}
/// Get the exit future.
pub(crate) fn exit(&self) -> &E {
&self.exit
}
/// Get the network service.
pub(crate) fn network(&self) -> &RegisteredMessageValidator {
&self.network
@@ -559,7 +546,7 @@ impl<P, E, T> LeafWorkDataFetcher<P, E, T> {
}
}
impl<P, E: Clone, T: Clone> Clone for LeafWorkDataFetcher<P, E, T> {
impl<P, T: Clone> Clone for LeafWorkDataFetcher<P, T> {
fn clone(&self) -> Self {
LeafWorkDataFetcher {
network: self.network.clone(),
@@ -567,15 +554,13 @@ impl<P, E: Clone, T: Clone> Clone for LeafWorkDataFetcher<P, E, T> {
task_executor: self.task_executor.clone(),
parent_hash: self.parent_hash,
knowledge: self.knowledge.clone(),
exit: self.exit.clone(),
}
}
}
impl<P: ProvideRuntimeApi<Block> + Send, E, T> LeafWorkDataFetcher<P, E, T> where
impl<P: ProvideRuntimeApi<Block> + Send, T> LeafWorkDataFetcher<P, T> where
P::Api: ParachainHost<Block>,
T: Clone + Executor + Send + 'static,
E: Future<Output=()> + Clone + Send + 'static,
{
/// Fetch PoV block for the given candidate receipt.
pub fn fetch_pov_block(&self, candidate: &CandidateReceipt)
+3 -1
View File
@@ -27,6 +27,7 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "pol
staking = { package = "pallet-staking", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
system = { package = "frame-system", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
vesting = { package = "pallet-vesting", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false }
polkadot-parachain = { path = "../../parachain", default-features = false }
@@ -41,7 +42,7 @@ babe = { package = "pallet-babe", git = "https://github.com/paritytech/substrate
randomness-collective-flip = { package = "pallet-randomness-collective-flip", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
pallet-staking-reward-curve = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
trie-db = "0.19.2"
trie-db = "0.20.0"
serde_json = "1.0.41"
[features]
@@ -67,6 +68,7 @@ std = [
"staking/std",
"system/std",
"timestamp/std",
"vesting/std",
"serde_derive",
"serde/std",
"log",
+59 -38
View File
@@ -18,15 +18,14 @@
use rstd::prelude::*;
use sp_io::{hashing::keccak_256, crypto::secp256k1_ecdsa_recover};
use frame_support::{decl_event, decl_storage, decl_module, decl_error};
use frame_support::weights::SimpleDispatchInfo;
use frame_support::traits::{Currency, Get, VestingCurrency};
use frame_support::{decl_event, decl_storage, decl_module, decl_error, ensure};
use frame_support::{dispatch::DispatchResult, weights::SimpleDispatchInfo};
use frame_support::traits::{Currency, Get, VestingSchedule};
use system::{ensure_root, ensure_none};
use codec::{Encode, Decode};
#[cfg(feature = "std")]
use serde::{self, Serialize, Deserialize, Serializer, Deserializer};
#[cfg(feature = "std")]
use sp_runtime::traits::Zero;
use sp_runtime::traits::{Zero, CheckedSub};
use sp_runtime::{
RuntimeDebug, transaction_validity::{
TransactionLongevity, TransactionValidity, ValidTransaction, InvalidTransaction
@@ -35,14 +34,14 @@ use sp_runtime::{
use primitives::ValidityError;
use system;
type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
type CurrencyOf<T> = <<T as Trait>::VestingSchedule as VestingSchedule<<T as system::Trait>::AccountId>>::Currency;
type BalanceOf<T> = <CurrencyOf<T> as Currency<<T as system::Trait>::AccountId>>::Balance;
/// Configuration trait.
pub trait Trait: system::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
type Currency: Currency<Self::AccountId>
+ VestingCurrency<Self::AccountId, Moment=Self::BlockNumber>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment=Self::BlockNumber>;
type Prefix: Get<&'static [u8]>;
}
@@ -108,6 +107,11 @@ decl_error! {
InvalidEthereumSignature,
/// Ethereum address has no claim.
SignerHasNoClaim,
/// The destination is already vesting and cannot be the target of a further claim.
DestinationVesting,
/// There's not enough in the pot to pay out some unvested amount. Generally implies a logic
/// error.
PotUnderflow,
}
}
@@ -157,24 +161,34 @@ decl_module! {
let balance_due = <Claims<T>>::get(&signer)
.ok_or(Error::<T>::SignerHasNoClaim)?;
let maybe_vested = <Vesting<T>>::get(&signer);
// If this fails, destination account already has a vesting schedule
// applied to it, and this claim should not be processed.
ensure!(
maybe_vested.is_none() || T::VestingSchedule::vesting_balance(&dest).is_zero(),
Error::<T>::DestinationVesting
);
<Total<T>>::mutate(|t| -> DispatchResult {
*t = t.checked_sub(&balance_due).ok_or(Error::<T>::PotUnderflow)?;
Ok(())
})?;
// This must happen before the add_vesting_schedule otherwise the schedule will be
// nullified.
CurrencyOf::<T>::deposit_creating(&dest, balance_due);
// Check if this claim should have a vesting schedule.
if let Some(vs) = <Vesting<T>>::get(&signer) {
// If this fails, destination account already has a vesting schedule
// applied to it, and this claim should not be processed.
T::Currency::add_vesting_schedule(&dest, vs.0, vs.1, vs.2)?;
if let Some(vs) = maybe_vested {
// Should never fail since we ensured that the destination is not already vesting.
// However, we already deposited, so can't error out here anyway.
let _ = T::VestingSchedule::add_vesting_schedule(&dest, vs.0, vs.1, vs.2);
}
<Claims<T>>::remove(&signer);
<Vesting<T>>::remove(&signer);
<Total<T>>::mutate(|t| if *t < balance_due {
panic!("Logic error: Pot less than the total of claims!")
} else {
*t -= balance_due
});
T::Currency::deposit_creating(&dest, balance_due);
// Let's deposit an event to let the outside world know this happened.
Self::deposit_event(RawEvent::Claimed(dest, signer, balance_due));
}
@@ -284,9 +298,11 @@ mod tests {
use codec::Encode;
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup, Identity}, testing::Header};
use frame_support::{
impl_outer_origin, assert_ok, assert_err, assert_noop, parameter_types
};
use balances;
use frame_support::{impl_outer_origin, assert_ok, assert_err, assert_noop, parameter_types};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -315,8 +331,8 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type AvailableBlockRatio = AvailableBlockRatio;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
}
@@ -329,28 +345,33 @@ mod tests {
impl balances::Trait for Test {
type Balance = u64;
type OnFreeBalanceZero = ();
type OnReapAccount = System;
type OnNewAccount = ();
type Event = ();
type DustRemoval = ();
type TransferPayment = ();
type DustRemoval = ();
type Event = ();
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type CreationFee = CreationFee;
}
impl vesting::Trait for Test {
type Event = ();
type Currency = Balances;
type BlockNumberToBalance = Identity;
}
parameter_types!{
pub const Prefix: &'static [u8] = b"Pay RUSTs to the TEST account:";
}
impl Trait for Test {
type Event = ();
type Currency = Balances;
type VestingSchedule = Vesting;
type Prefix = Prefix;
}
type System = system::Module<Test>;
type Balances = balances::Module<Test>;
type Vesting = vesting::Module<Test>;
type Claims = Module<Test>;
fn alice() -> secp256k1::SecretKey {
@@ -414,7 +435,7 @@ mod tests {
assert_eq!(Balances::free_balance(&42), 0);
assert_ok!(Claims::claim(Origin::NONE, 42, sig(&alice(), &42u64.encode())));
assert_eq!(Balances::free_balance(&42), 100);
assert_eq!(Balances::vesting_balance(&42), 50);
assert_eq!(Vesting::vesting_balance(&42), 50);
});
}
@@ -432,8 +453,8 @@ mod tests {
);
assert_ok!(Claims::mint_claim(Origin::ROOT, eth(&bob()), 200, None));
assert_ok!(Claims::claim(Origin::NONE, 69, sig(&bob(), &69u64.encode())));
assert_eq!(Balances::free_balance(&69), 200);
assert_eq!(Balances::vesting_balance(&69), 0);
assert_eq!(Balances::free_balance(69), 200);
assert_eq!(Vesting::vesting_balance(&69), 0);
});
}
@@ -444,22 +465,22 @@ mod tests {
Claims::mint_claim(Origin::signed(42), eth(&bob()), 200, Some((50, 10, 1))),
sp_runtime::traits::BadOrigin,
);
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::free_balance(42), 0);
assert_noop!(
Claims::claim(Origin::NONE, 69, sig(&bob(), &69u64.encode())),
Error::<Test>::SignerHasNoClaim
);
assert_ok!(Claims::mint_claim(Origin::ROOT, eth(&bob()), 200, Some((50, 10, 1))));
assert_ok!(Claims::claim(Origin::NONE, 69, sig(&bob(), &69u64.encode())));
assert_eq!(Balances::free_balance(&69), 200);
assert_eq!(Balances::vesting_balance(&69), 50);
assert_eq!(Balances::free_balance(69), 200);
assert_eq!(Vesting::vesting_balance(&69), 50);
});
}
#[test]
fn origin_signed_claiming_fail() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::free_balance(42), 0);
assert_err!(
Claims::claim(Origin::signed(42), 42, sig(&alice(), &42u64.encode())),
sp_runtime::traits::BadOrigin,
@@ -470,7 +491,7 @@ mod tests {
#[test]
fn double_claiming_doesnt_work() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::free_balance(42), 0);
assert_ok!(Claims::claim(Origin::NONE, 42, sig(&alice(), &42u64.encode())));
assert_noop!(
Claims::claim(Origin::NONE, 42, sig(&alice(), &42u64.encode())),
@@ -482,7 +503,7 @@ mod tests {
#[test]
fn non_sender_sig_doesnt_work() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::free_balance(42), 0);
assert_noop!(
Claims::claim(Origin::NONE, 42, sig(&alice(), &69u64.encode())),
Error::<Test>::SignerHasNoClaim
@@ -493,7 +514,7 @@ mod tests {
#[test]
fn non_claimant_doesnt_work() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::free_balance(42), 0);
assert_noop!(
Claims::claim(Origin::NONE, 42, sig(&bob(), &69u64.encode())),
Error::<Test>::SignerHasNoClaim
+12 -16
View File
@@ -284,7 +284,7 @@ decl_module! {
/// Contribute to a crowd sale. This will transfer some balance over to fund a parachain
/// slot. It will be withdrawable in two instances: the parachain becomes retired; or the
/// slot is
/// slot is unable to be purchased and the timeout expires.
fn contribute(origin, #[compact] index: FundIndex, #[compact] value: BalanceOf<T>) {
let who = ensure_signed(origin)?;
@@ -599,21 +599,16 @@ mod tests {
}
parameter_types! {
pub const ExistentialDeposit: u64 = 0;
// We want to make sure these fees are non zero, so we can check
// that our module correctly avoids these fees :)
pub const TransferFee: u64 = 10;
pub const CreationFee: u64 = 10;
pub const CreationFee: u64 = 0;
}
impl balances::Trait for Test {
type Balance = u64;
type OnFreeBalanceZero = ();
type OnReapAccount = System;
type OnNewAccount = ();
type Event = ();
type DustRemoval = ();
type TransferPayment = ();
type DustRemoval = ();
type Event = ();
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type CreationFee = CreationFee;
}
@@ -730,7 +725,6 @@ mod tests {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
balances::GenesisConfig::<Test>{
balances: vec![(1, 1000), (2, 2000), (3, 3000), (4, 4000)],
vesting: vec![],
}.assimilate_storage(&mut t).unwrap();
t.into()
}
@@ -830,7 +824,7 @@ mod tests {
// User 1 contributes to their own crowdfund
assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 49));
// User 1 has spent some funds to do this, transfer fees **are** taken
assert_eq!(Balances::free_balance(1), 940);
assert_eq!(Balances::free_balance(1), 950);
// Contributions are stored in the trie
assert_eq!(Crowdfund::contribution_get(0, &1), 49);
// Contributions appear in free balance of crowdfund
@@ -1108,13 +1102,13 @@ mod tests {
// User can withdraw their full balance without fees
assert_ok!(Crowdfund::withdraw(Origin::signed(1), 0));
assert_eq!(Balances::free_balance(1), 989);
assert_eq!(Balances::free_balance(1), 999);
assert_ok!(Crowdfund::withdraw(Origin::signed(2), 0));
assert_eq!(Balances::free_balance(2), 1990);
assert_eq!(Balances::free_balance(2), 2000);
assert_ok!(Crowdfund::withdraw(Origin::signed(3), 0));
assert_eq!(Balances::free_balance(3), 2990);
assert_eq!(Balances::free_balance(3), 3000);
});
}
@@ -1126,7 +1120,7 @@ mod tests {
assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
// Transfer fee is taken here
assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 49));
assert_eq!(Balances::free_balance(1), 940);
assert_eq!(Balances::free_balance(1), 950);
run_to_block(5);
@@ -1156,6 +1150,8 @@ mod tests {
// Skip all the way to the end
run_to_block(50);
// Check initiator's balance.
assert_eq!(Balances::free_balance(1), 899);
// Check current funds (contributions + deposit)
assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 601);
@@ -1165,7 +1161,7 @@ mod tests {
// Fund account is emptied
assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 0);
// Deposit is returned
assert_eq!(Balances::free_balance(1), 890);
assert_eq!(Balances::free_balance(1), 900);
// Treasury account is filled
assert_eq!(Balances::free_balance(Treasury::account_id()), 600);
+5 -9
View File
@@ -1010,13 +1010,13 @@ mod tests {
}
impl session::Trait for Test {
type SessionManager = ();
type Keys = UintAuthorityId;
type ShouldEndSession = session::PeriodicSessions<Period, Offset>;
type SessionHandler = session::TestSessionHandler;
type Event = ();
type ValidatorId = u64;
type ValidatorIdOf = staking::StashOf<Self>;
type ShouldEndSession = session::PeriodicSessions<Period, Offset>;
type SessionManager = ();
type SessionHandler = session::TestSessionHandler;
type Keys = UintAuthorityId;
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}
@@ -1057,20 +1057,17 @@ mod tests {
parameter_types! {
pub const ExistentialDeposit: Balance = 0;
pub const TransferFee: Balance = 0;
pub const CreationFee: Balance = 0;
}
impl balances::Trait for Test {
type Balance = Balance;
type OnFreeBalanceZero = ();
type OnReapAccount = System;
type OnNewAccount = ();
type Event = ();
type DustRemoval = ();
type TransferPayment = ();
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type TransferPayment = ();
type CreationFee = CreationFee;
}
@@ -1216,7 +1213,6 @@ mod tests {
balances::GenesisConfig::<Test> {
balances,
vesting: vec![],
}.assimilate_storage(&mut t).unwrap();
staking::GenesisConfig::<Test> {
+7 -11
View File
@@ -654,20 +654,17 @@ mod tests {
parameter_types! {
pub const ExistentialDeposit: Balance = 0;
pub const TransferFee: Balance = 0;
pub const CreationFee: Balance = 0;
}
impl balances::Trait for Test {
type Balance = Balance;
type OnFreeBalanceZero = ();
type OnReapAccount = System;
type OnNewAccount = ();
type OnReapAccount = System;
type Balance = Balance;
type Event = ();
type DustRemoval = ();
type TransferPayment = ();
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type TransferPayment = ();
type CreationFee = CreationFee;
}
@@ -793,7 +790,6 @@ mod tests {
balances::GenesisConfig::<Test> {
balances,
vesting: vec![],
}.assimilate_storage(&mut t).unwrap();
t.into()
@@ -1060,8 +1056,8 @@ mod tests {
vec![3; 3],
));
// deposit should be taken (reserved)
assert_eq!(Balances::free_balance(&3u64) + ParathreadDeposit::get(), orig_bal);
assert_eq!(Balances::reserved_balance(&3u64), ParathreadDeposit::get());
assert_eq!(Balances::free_balance(3u64) + ParathreadDeposit::get(), orig_bal);
assert_eq!(Balances::reserved_balance(3u64), ParathreadDeposit::get());
run_to_block(3);
@@ -1083,8 +1079,8 @@ mod tests {
parachains::Origin::Parachain(user_id(0)).into()
));
// reserved balance should be returned.
assert_eq!(Balances::free_balance(&3u64), orig_bal);
assert_eq!(Balances::reserved_balance(&3u64), 0);
assert_eq!(Balances::free_balance(3u64), orig_bal);
assert_eq!(Balances::reserved_balance(3u64), 0);
run_to_block(4);
+22 -26
View File
@@ -898,21 +898,18 @@ mod tests {
parameter_types! {
pub const ExistentialDeposit: u64 = 0;
pub const TransferFee: u64 = 0;
pub const CreationFee: u64 = 0;
}
impl balances::Trait for Test {
type Balance = u64;
type OnFreeBalanceZero = ();
type OnReapAccount = System;
type OnNewAccount = ();
type Event = ();
type OnNewAccount = ();
type OnReapAccount = System;
type DustRemoval = ();
type TransferPayment = ();
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type CreationFee = CreationFee;
type TransferPayment = ();
}
thread_local! {
@@ -987,7 +984,6 @@ mod tests {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
balances::GenesisConfig::<Test>{
balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)],
vesting: vec![],
}.assimilate_storage(&mut t).unwrap();
t.into()
}
@@ -1086,8 +1082,8 @@ mod tests {
assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));
assert_eq!(Balances::reserved_balance(&1), 1);
assert_eq!(Balances::free_balance(&1), 9);
assert_eq!(Balances::reserved_balance(1), 1);
assert_eq!(Balances::free_balance(1), 9);
run_to_block(9);
assert_eq!(Slots::onboard_queue(1), vec![0.into()]);
@@ -1095,8 +1091,8 @@ mod tests {
Some((1, IncomingParachain::Unset(NewBidder { who: 1, sub: 0 })))
);
assert_eq!(Slots::deposit_held(&0.into()), 1);
assert_eq!(Balances::reserved_balance(&1), 0);
assert_eq!(Balances::free_balance(&1), 9);
assert_eq!(Balances::reserved_balance(1), 0);
assert_eq!(Balances::free_balance(1), 9);
});
}
@@ -1106,7 +1102,7 @@ mod tests {
run_to_block(1);
assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 1));
assert_eq!(Balances::free_balance(&1), 9);
assert_eq!(Balances::free_balance(1), 9);
run_to_block(9);
assert_eq!(Slots::deposit_held(&0.into()), 1);
@@ -1114,7 +1110,7 @@ mod tests {
run_to_block(50);
assert_eq!(Slots::deposit_held(&0.into()), 0);
assert_eq!(Balances::free_balance(&1), 10);
assert_eq!(Balances::free_balance(1), 10);
});
}
@@ -1135,7 +1131,7 @@ mod tests {
run_to_block(50);
assert_eq!(Slots::deposit_held(&0.into()), 0);
assert_eq!(Balances::free_balance(&10), 1);
assert_eq!(Balances::free_balance(10), 1);
});
}
@@ -1189,8 +1185,8 @@ mod tests {
assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
assert_ok!(Slots::bid(Origin::signed(1), 0, 1, 1, 4, 5));
assert_ok!(Slots::bid(Origin::signed(2), 0, 1, 1, 4, 1));
assert_eq!(Balances::reserved_balance(&2), 0);
assert_eq!(Balances::free_balance(&2), 20);
assert_eq!(Balances::reserved_balance(2), 0);
assert_eq!(Balances::free_balance(2), 20);
assert_eq!(
Slots::winning(0).unwrap()[SlotRange::ZeroThree as u8 as usize],
Some((Bidder::New(NewBidder{who: 1, sub: 0}), 5))
@@ -1382,13 +1378,13 @@ mod tests {
assert_ok!(Slots::bid_renew(Origin::signed(ParaId::from(0).into_account()), 2, 2, 2, 3));
run_to_block(20);
assert_eq!(Balances::free_balance::<u64>(ParaId::from(0).into_account()), 2);
assert_eq!(Balances::free_balance(&ParaId::from(0u32).into_account()), 2);
assert_ok!(Slots::new_auction(Origin::ROOT, 5, 2));
assert_ok!(Slots::bid_renew(Origin::signed(ParaId::from(0).into_account()), 3, 3, 3, 4));
run_to_block(30);
assert_eq!(Balances::free_balance::<u64>(ParaId::from(0).into_account()), 1);
assert_eq!(Balances::free_balance(&ParaId::from(0u32).into_account()), 1);
});
}
@@ -1424,8 +1420,8 @@ mod tests {
run_to_block(i);
assert_ok!(Slots::bid(Origin::signed(i), 0, 1, 1, 4, i));
for j in 1..6 {
assert_eq!(Balances::reserved_balance(&j), if j == i { j } else { 0 });
assert_eq!(Balances::free_balance(&j), if j == i { j * 9 } else { j * 10 });
assert_eq!(Balances::reserved_balance(j), if j == i { j } else { 0 });
assert_eq!(Balances::free_balance(j), if j == i { j * 9 } else { j * 10 });
}
}
@@ -1436,8 +1432,8 @@ mod tests {
Some((1, IncomingParachain::Unset(NewBidder { who: 5, sub: 0 })))
);
assert_eq!(Slots::deposit_held(&0.into()), 5);
assert_eq!(Balances::reserved_balance(&5), 0);
assert_eq!(Balances::free_balance(&5), 45);
assert_eq!(Balances::reserved_balance(5), 0);
assert_eq!(Balances::free_balance(5), 45);
});
}
@@ -1452,8 +1448,8 @@ mod tests {
run_to_block(i + 3);
assert_ok!(Slots::bid(Origin::signed(i), 0, 1, 1, 4, i));
for j in 1..6 {
assert_eq!(Balances::reserved_balance(&j), if j == i { j } else { 0 });
assert_eq!(Balances::free_balance(&j), if j == i { j * 9 } else { j * 10 });
assert_eq!(Balances::reserved_balance(j), if j == i { j } else { 0 });
assert_eq!(Balances::free_balance(j), if j == i { j * 9 } else { j * 10 });
}
}
@@ -1464,8 +1460,8 @@ mod tests {
Some((1, IncomingParachain::Unset(NewBidder { who: 3, sub: 0 })))
);
assert_eq!(Slots::deposit_held(&0.into()), 3);
assert_eq!(Balances::reserved_balance(&3), 0);
assert_eq!(Balances::free_balance(&3), 27);
assert_eq!(Balances::reserved_balance(3), 0);
assert_eq!(Balances::free_balance(3), 27);
});
}
+3 -1
View File
@@ -58,6 +58,7 @@ system_rpc_runtime_api = { package = "frame-system-rpc-runtime-api", git = "http
timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
utility = { package = "pallet-utility", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
vesting = { package = "pallet-vesting", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false }
primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false }
@@ -69,7 +70,7 @@ libsecp256k1 = "0.3.2"
tiny-keccak = "1.5.0"
keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
trie-db = "0.19.2"
trie-db = "0.20.0"
serde_json = "1.0.41"
[build-dependencies]
@@ -124,6 +125,7 @@ std = [
"treasury/std",
"version/std",
"utility/std",
"vesting/std",
"serde_derive",
"serde/std",
"log",
+41 -31
View File
@@ -38,7 +38,7 @@ use sp_runtime::{
ApplyExtrinsicResult, Percent, Permill, Perbill, RuntimeDebug,
transaction_validity::{TransactionValidity, InvalidTransaction, TransactionValidityError},
curve::PiecewiseLinear,
traits::{BlakeTwo256, Block as BlockT, StaticLookup, SignedExtension, OpaqueKeys},
traits::{BlakeTwo256, Block as BlockT, StaticLookup, SignedExtension, OpaqueKeys, ConvertInto},
};
use version::RuntimeVersion;
use grandpa::{AuthorityId as GrandpaId, fg_primitives};
@@ -77,7 +77,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("kusama"),
impl_name: create_runtime_str!("parity-kusama"),
authoring_version: 2,
spec_version: 1045,
spec_version: 1046,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
};
@@ -151,16 +151,19 @@ impl babe::Trait for Runtime {
type EpochChangeTrigger = babe::ExternalTrigger;
}
parameter_types! {
pub const IndexDeposit: Balance = 1 * DOLLARS;
}
impl indices::Trait for Runtime {
type IsDeadAccount = Balances;
type AccountIndex = AccountIndex;
type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
type Event = Event;
type IsDeadAccount = Balances;
type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
}
parameter_types! {
pub const ExistentialDeposit: Balance = 1 * CENTS;
pub const TransferFee: Balance = 1 * CENTS;
pub const CreationFee: Balance = 1 * CENTS;
}
@@ -174,14 +177,12 @@ pub type DealWithFees = SplitTwoWays<
impl balances::Trait for Runtime {
type Balance = Balance;
type OnFreeBalanceZero = Staking;
type OnReapAccount = (System, Recovery);
type OnNewAccount = Indices;
type Event = Event;
type DustRemoval = ();
type TransferPayment = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type OnReapAccount = (Staking, Session, Democracy);
type OnNewAccount = ();
type TransferPayment = ();
type CreationFee = CreationFee;
}
@@ -242,13 +243,13 @@ parameter_types! {
}
impl session::Trait for Runtime {
type SessionManager = Staking;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type ShouldEndSession = Babe;
type Event = Event;
type Keys = SessionKeys;
type ValidatorId = AccountId;
type ValidatorIdOf = staking::StashOf<Self>;
type ShouldEndSession = Babe;
type SessionManager = Staking;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}
@@ -279,10 +280,11 @@ parameter_types! {
}
impl staking::Trait for Runtime {
type RewardRemainder = Treasury;
type CurrencyToVote = CurrencyToVoteHandler<Self>;
type Event = Event;
type Currency = Balances;
type Time = Timestamp;
type CurrencyToVote = CurrencyToVoteHandler<Self>;
type RewardRemainder = Treasury;
type Event = Event;
type Slash = Treasury;
type Reward = ();
type SessionsPerEra = SessionsPerEra;
@@ -291,7 +293,6 @@ impl staking::Trait for Runtime {
// A majority of the council can cancel the slash.
type SlashCancelOrigin = collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
type SessionInterface = Self;
type Time = Timestamp;
type RewardCurve = RewardCurve;
}
@@ -313,7 +314,6 @@ impl democracy::Trait for Runtime {
type EnactmentPeriod = EnactmentPeriod;
type LaunchPeriod = LaunchPeriod;
type VotingPeriod = VotingPeriod;
type EmergencyVotingPeriod = EmergencyVotingPeriod;
type MinimumDeposit = MinimumDeposit;
/// A straight majority of the council can decide what their next motion is.
type ExternalOrigin = collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
@@ -325,6 +325,7 @@ impl democracy::Trait for Runtime {
/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
/// be tabled immediately and with a shorter voting/enactment period.
type FastTrackOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
type EmergencyVotingPeriod = EmergencyVotingPeriod;
// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
type CancellationOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>;
// Any single technical committee member may veto a coming council proposal, however they can
@@ -358,12 +359,12 @@ impl elections_phragmen::Trait for Runtime {
type CurrencyToVote = CurrencyToVoteHandler<Self>;
type CandidacyBond = CandidacyBond;
type VotingBond = VotingBond;
type TermDuration = TermDuration;
type DesiredMembers = DesiredMembers;
type DesiredRunnersUp = DesiredRunnersUp;
type LoserCandidate = Treasury;
type BadReport = Treasury;
type KickedMember = Treasury;
type DesiredMembers = DesiredMembers;
type DesiredRunnersUp = DesiredRunnersUp;
type TermDuration = TermDuration;
}
type TechnicalCollective = collective::Instance2;
@@ -399,17 +400,17 @@ impl treasury::Trait for Runtime {
type Currency = Balances;
type ApproveOrigin = collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>;
type RejectOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>;
type Tippers = ElectionsPhragmen;
type TipCountdown = TipCountdown;
type TipFindersFee = TipFindersFee;
type TipReportDepositBase = TipReportDepositBase;
type TipReportDepositPerByte = TipReportDepositPerByte;
type Event = Event;
type ProposalRejection = Treasury;
type ProposalBond = ProposalBond;
type ProposalBondMinimum = ProposalBondMinimum;
type SpendPeriod = SpendPeriod;
type Burn = Burn;
type Tippers = ElectionsPhragmen;
type TipCountdown = TipCountdown;
type TipFindersFee = TipFindersFee;
type TipReportDepositBase = TipReportDepositBase;
type TipReportDepositPerByte = TipReportDepositPerByte;
}
impl offences::Trait for Runtime {
@@ -505,7 +506,7 @@ parameter_types! {
impl claims::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type VestingSchedule = Vesting;
type Prefix = Prefix;
}
@@ -591,6 +592,12 @@ impl society::Trait for Runtime {
type ChallengePeriod = ChallengePeriod;
}
impl vesting::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type BlockNumberToBalance = ConvertInto;
}
construct_runtime! {
pub enum Runtime where
Block = Block,
@@ -598,14 +605,14 @@ construct_runtime! {
UncheckedExtrinsic = UncheckedExtrinsic
{
// Basic stuff; balances is uncallable initially.
System: system::{Module, Call, Storage, Config, Event},
System: system::{Module, Call, Storage, Config, Event<T>},
RandomnessCollectiveFlip: randomness_collective_flip::{Module, Storage},
// Must be before session.
Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)},
Timestamp: timestamp::{Module, Call, Storage, Inherent},
Indices: indices,
Indices: indices::{Module, Call, Storage, Config<T>, Event<T>},
Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},
TransactionPayment: transaction_payment::{Module, Storage},
@@ -648,6 +655,9 @@ construct_runtime! {
// Social recovery module.
Recovery: recovery::{Module, Call, Storage, Event<T>},
// Vesting. Usable initially, but removed once all vesting is finished.
Vesting: vesting::{Module, Call, Storage, Event<T>, Config<T>},
}
}
+3 -1
View File
@@ -55,6 +55,7 @@ system_rpc_runtime_api = { package = "frame-system-rpc-runtime-api", git = "http
timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
sudo = { package = "pallet-sudo", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
vesting = { package = "pallet-vesting", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false }
primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false }
@@ -66,7 +67,7 @@ libsecp256k1 = "0.3.2"
tiny-keccak = "1.5.0"
keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
trie-db = "0.19.2"
trie-db = "0.20.0"
serde_json = "1.0.41"
[build-dependencies]
@@ -126,4 +127,5 @@ std = [
"randomness-collective-flip/std",
"runtime-common/std",
"sudo/std",
"vesting/std",
]
+45 -36
View File
@@ -38,7 +38,7 @@ use sp_runtime::{
ApplyExtrinsicResult, Percent, Permill, Perbill, RuntimeDebug,
transaction_validity::{TransactionValidity, InvalidTransaction, TransactionValidityError},
curve::PiecewiseLinear,
traits::{BlakeTwo256, Block as BlockT, StaticLookup, SignedExtension, OpaqueKeys},
traits::{BlakeTwo256, Block as BlockT, StaticLookup, SignedExtension, OpaqueKeys, ConvertInto},
};
use version::RuntimeVersion;
use grandpa::{AuthorityId as GrandpaId, fg_primitives};
@@ -155,16 +155,19 @@ impl babe::Trait for Runtime {
type EpochChangeTrigger = babe::ExternalTrigger;
}
parameter_types! {
pub const IndexDeposit: Balance = 1 * DOLLARS;
}
impl indices::Trait for Runtime {
type IsDeadAccount = Balances;
type AccountIndex = AccountIndex;
type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
type Event = Event;
type IsDeadAccount = Balances;
type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
}
parameter_types! {
pub const ExistentialDeposit: Balance = 100 * CENTS;
pub const TransferFee: Balance = 1 * CENTS;
pub const CreationFee: Balance = 1 * CENTS;
}
@@ -178,14 +181,12 @@ pub type DealWithFees = SplitTwoWays<
impl balances::Trait for Runtime {
type Balance = Balance;
type OnFreeBalanceZero = Staking;
type OnReapAccount = System;
type OnNewAccount = Indices;
type Event = Event;
type DustRemoval = ();
type TransferPayment = ();
type ExistentialDeposit = ExistentialDeposit;
type TransferFee = TransferFee;
type OnReapAccount = (Staking, Session, Democracy);
type OnNewAccount = ();
type TransferPayment = ();
type CreationFee = CreationFee;
}
@@ -246,13 +247,13 @@ parameter_types! {
}
impl session::Trait for Runtime {
type SessionManager = Staking;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type ShouldEndSession = Babe;
type Event = Event;
type Keys = SessionKeys;
type ValidatorId = AccountId;
type ValidatorIdOf = staking::StashOf<Self>;
type ShouldEndSession = Babe;
type SessionManager = Staking;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}
@@ -282,10 +283,11 @@ parameter_types! {
}
impl staking::Trait for Runtime {
type RewardRemainder = Treasury;
type CurrencyToVote = CurrencyToVoteHandler<Self>;
type Event = Event;
type Currency = Balances;
type Time = Timestamp;
type CurrencyToVote = CurrencyToVoteHandler<Self>;
type RewardRemainder = Treasury;
type Event = Event;
type Slash = Treasury;
type Reward = ();
type SessionsPerEra = SessionsPerEra;
@@ -294,7 +296,6 @@ impl staking::Trait for Runtime {
// A super-majority of the council can cancel the slash.
type SlashCancelOrigin = collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>;
type SessionInterface = Self;
type Time = Timestamp;
type RewardCurve = RewardCurve;
}
@@ -316,7 +317,6 @@ impl democracy::Trait for Runtime {
type EnactmentPeriod = EnactmentPeriod;
type LaunchPeriod = LaunchPeriod;
type VotingPeriod = VotingPeriod;
type EmergencyVotingPeriod = EmergencyVotingPeriod;
type MinimumDeposit = MinimumDeposit;
/// A straight majority of the council can decide what their next motion is.
type ExternalOrigin = collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
@@ -328,6 +328,7 @@ impl democracy::Trait for Runtime {
/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
/// be tabled immediately and with a shorter voting/enactment period.
type FastTrackOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
type EmergencyVotingPeriod = EmergencyVotingPeriod;
// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
type CancellationOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>;
// Any single technical committee member may veto a coming council proposal, however they can
@@ -362,12 +363,12 @@ impl elections_phragmen::Trait for Runtime {
type CurrencyToVote = CurrencyToVoteHandler<Self>;
type CandidacyBond = CandidacyBond;
type VotingBond = VotingBond;
type TermDuration = TermDuration;
type DesiredMembers = DesiredMembers;
type DesiredRunnersUp = DesiredRunnersUp;
type LoserCandidate = Treasury;
type BadReport = Treasury;
type KickedMember = Treasury;
type DesiredMembers = DesiredMembers;
type DesiredRunnersUp = DesiredRunnersUp;
type TermDuration = TermDuration;
}
type TechnicalCollective = collective::Instance2;
@@ -403,17 +404,17 @@ impl treasury::Trait for Runtime {
type Currency = Balances;
type ApproveOrigin = collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>;
type RejectOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>;
type Tippers = ElectionsPhragmen;
type TipCountdown = TipCountdown;
type TipFindersFee = TipFindersFee;
type TipReportDepositBase = TipReportDepositBase;
type TipReportDepositPerByte = TipReportDepositPerByte;
type Event = Event;
type ProposalRejection = Treasury;
type ProposalBond = ProposalBond;
type ProposalBondMinimum = ProposalBondMinimum;
type SpendPeriod = SpendPeriod;
type Burn = Burn;
type Tippers = ElectionsPhragmen;
type TipCountdown = TipCountdown;
type TipFindersFee = TipFindersFee;
type TipReportDepositBase = TipReportDepositBase;
type TipReportDepositPerByte = TipReportDepositPerByte;
}
impl offences::Trait for Runtime {
@@ -435,8 +436,8 @@ impl im_online::Trait for Runtime {
type Event = Event;
type Call = Call;
type SubmitTransaction = SubmitTransaction;
type ReportUnresponsiveness = Offences;
type SessionDuration = SessionDuration;
type ReportUnresponsiveness = Offences;
}
impl grandpa::Trait for Runtime {
@@ -498,8 +499,8 @@ impl slots::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type Parachains = Registrar;
type LeasePeriod = LeasePeriod;
type EndingPeriod = EndingPeriod;
type LeasePeriod = LeasePeriod;
type Randomness = RandomnessCollectiveFlip;
}
@@ -509,10 +510,16 @@ parameter_types! {
impl claims::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type VestingSchedule = Vesting;
type Prefix = Prefix;
}
impl vesting::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type BlockNumberToBalance = ConvertInto;
}
impl sudo::Trait for Runtime {
type Event = Event;
type Proposal = Call;
@@ -525,7 +532,7 @@ construct_runtime! {
UncheckedExtrinsic = UncheckedExtrinsic
{
// Basic stuff; balances is uncallable initially.
System: system::{Module, Call, Storage, Config, Event},
System: system::{Module, Call, Storage, Config, Event<T>},
RandomnessCollectiveFlip: randomness_collective_flip::{Module, Storage},
// Must be before session.
@@ -546,9 +553,6 @@ construct_runtime! {
ImOnline: im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
AuthorityDiscovery: authority_discovery::{Module, Call, Config},
// Sudo. Usable initially.
Sudo: sudo,
// Governance stuff; uncallable initially.
Democracy: democracy::{Module, Call, Storage, Config, Event<T>},
Council: collective::<Instance1>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>},
@@ -557,15 +561,20 @@ construct_runtime! {
TechnicalMembership: membership::<Instance1>::{Module, Call, Storage, Event<T>, Config<T>},
Treasury: treasury::{Module, Call, Storage, Event<T>},
// Claims. Usable initially.
Claims: claims::{Module, Call, Storage, Event<T>, Config<T>, ValidateUnsigned},
// Parachains stuff; slots are disabled (no auctions initially). The rest are safe as they
// have no public dispatchables.
Parachains: parachains::{Module, Call, Storage, Config, Inherent, Origin},
Attestations: attestations::{Module, Call, Storage},
Slots: slots::{Module, Call, Storage, Event<T>},
Registrar: registrar::{Module, Call, Storage, Event, Config<T>},
// Claims. Usable initially.
Claims: claims::{Module, Call, Storage, Event<T>, Config<T>, ValidateUnsigned},
// Vesting. Usable initially, but removed once all vesting is finished.
Vesting: vesting::{Module, Call, Storage, Event<T>, Config<T>},
// Sudo. Last module. Usable initially, but removed once governance enabled.
Sudo: sudo,
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ parking_lot = "0.9.0"
serde = { version = "1.0.102", features = ["derive"] }
lazy_static = "1.4.0"
log = "0.4.8"
futures = "0.3.1"
futures = "0.3.4"
slog = "2.5.2"
hex-literal = "0.2.1"
av_store = { package = "polkadot-availability-store", path = "../availability-store" }
+7 -4
View File
@@ -169,7 +169,6 @@ fn staging_testnet_config_genesis() -> polkadot::GenesisConfig {
.map(|k: &AccountId| (k.clone(), ENDOWMENT))
.chain(initial_authorities.iter().map(|x| (x.0.clone(), STASH)))
.collect(),
vesting: vec![],
}),
indices: Some(polkadot::IndicesConfig {
ids: endowed_accounts.iter().cloned()
@@ -222,9 +221,12 @@ fn staging_testnet_config_genesis() -> polkadot::GenesisConfig {
claims: vec![],
vesting: vec![],
}),
vesting: Some(polkadot::VestingConfig {
vesting: vec![],
}),
sudo: Some(polkadot::SudoConfig {
key: endowed_accounts[0].clone(),
})
}),
}
}
@@ -315,7 +317,6 @@ pub fn testnet_genesis(
}),
balances: Some(polkadot::BalancesConfig {
balances: endowed_accounts.iter().map(|k| (k.clone(), ENDOWMENT)).collect(),
vesting: vec![],
}),
session: Some(polkadot::SessionConfig {
keys: initial_authorities.iter().map(|x| (
@@ -362,13 +363,15 @@ pub fn testnet_genesis(
claims: vec![],
vesting: vec![],
}),
vesting: Some(polkadot::VestingConfig {
vesting: vec![],
}),
sudo: Some(polkadot::SudoConfig {
key: root_key,
}),
}
}
fn development_config_genesis() -> polkadot::GenesisConfig {
testnet_genesis(
vec![
+1 -2
View File
@@ -270,7 +270,7 @@ pub fn new_full<Runtime, Dispatch, Extrinsic>(
let is_authority = config.roles.is_authority() && !is_collator;
let force_authoring = config.force_authoring;
let max_block_data_size = max_block_data_size;
let db_path = if let DatabaseConfig::Path { ref path, .. } = config.database {
let db_path = if let Some(DatabaseConfig::Path { ref path, .. }) = config.database {
path.clone()
} else {
return Err("Starting a Polkadot service with a custom database isn't supported".to_string().into());
@@ -371,7 +371,6 @@ pub fn new_full<Runtime, Dispatch, Extrinsic>(
// collator connections and validation network both fulfilled by this
let validation_network = ValidationNetwork::new(
gossip_validator,
service.on_exit(),
service.client(),
service.spawn_task_handle(),
);
@@ -14,6 +14,4 @@ client = { package = "sc-client", git = "https://github.com/paritytech/substrate
client-api = { package = "sc-client-api", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
parking_lot = "0.10.0"
codec = { package = "parity-scale-codec", version = "1.1.0" }
ctrlc = { version = "3.1.3", features = ["termination"] }
futures = "0.3.1"
exit-future = "0.2.0"
futures = "0.3.4"
@@ -16,7 +16,6 @@
//! Collator for polkadot
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
@@ -135,16 +134,6 @@ fn main() {
println!();
}
// can't use signal directly here because CtrlC takes only `Fn`.
let (exit_send, exit) = exit_future::signal();
let exit_send_cell = RefCell::new(Some(exit_send));
ctrlc::set_handler(move || {
if let Some(exit_send) = exit_send_cell.try_borrow_mut().expect("signal handler not reentrant; qed").take() {
let _ = exit_send.fire();
}
}).expect("Error setting up ctrl-c handler");
let context = AdderContext {
db: Arc::new(Mutex::new(HashMap::new())),
_network: None,
@@ -156,7 +145,6 @@ fn main() {
let res = collator::run_collator(
context,
id,
exit,
key,
config,
);
+1 -1
View File
@@ -5,7 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
futures = "0.3.1"
futures = "0.3.4"
futures-timer = "2.0"
parking_lot = "0.9.0"
tokio = { version = "0.2.10", features = ["rt-core", "blocking"] }