Genesis creation utilities.

This commit is contained in:
Gav
2018-02-02 22:17:16 +01:00
parent bcb2fd0c10
commit 248f27c976
16 changed files with 201 additions and 100 deletions
+2
View File
@@ -965,10 +965,12 @@ version = "0.1.0"
dependencies = [
"error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
"native-runtime 0.1.0",
"parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 0.1.0",
"polkadot-serializer 0.1.0",
"polkadot-state-machine 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
+2
View File
@@ -10,3 +10,5 @@ parking_lot = "0.4"
polkadot-primitives = { path = "../primitives", version = "0.1" }
polkadot-state-machine = { path = "../state_machine", version = "0.1" }
polkadot-serializer = { path = "../serializer" }
native-runtime = { path = "../native-runtime" }
triehash = "0.1"
+37
View File
@@ -0,0 +1,37 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Tool for creating the genesis block.
use std::collections::HashMap;
use native_runtime::primitives::{Block, Header};
use triehash::trie_root;
/// Create a genesis block, given the initial storage.
pub fn construct_genesis_block(storage: &HashMap<Vec<u8>, Vec<u8>>) -> Block {
let state_root = trie_root(storage.clone().into_iter()).0;
let header = Header {
parent_hash: Default::default(),
number: 0,
state_root,
transaction_root: trie_root(vec![].into_iter()).0,
digest: Default::default(),
};
Block {
header,
transactions: vec![],
}
}
+6
View File
@@ -21,7 +21,9 @@
extern crate polkadot_primitives as primitives;
extern crate polkadot_state_machine as state_machine;
extern crate polkadot_serializer as ser;
extern crate native_runtime;
extern crate triehash;
extern crate parking_lot;
#[macro_use] extern crate error_chain;
#[macro_use] extern crate log;
@@ -31,6 +33,10 @@ pub mod blockchain;
pub mod backend;
pub mod in_mem;
mod genesis;
pub use genesis::construct_genesis_block;
pub use blockchain::Info as ChainInfo;
pub use blockchain::BlockId;
+4 -1
View File
@@ -233,8 +233,11 @@ mod test {
let pair = Pair::from_seed(b"12345678901234567890123456789012");
let public = pair.public();
assert_eq!(public, "2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee".into());
let message = FromHex::from_hex("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000228000000d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000").unwrap();
let message = FromHex::from_hex("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000002228000000d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000").unwrap();
let signature = pair.sign(&message[..]);
use hexdisplay::HexDisplay;
println!("Correct signature: {}", HexDisplay::from(&signature.0));
assert!(signature.verify(&message[..], &public));
panic!();
}
}
+2 -15
View File
@@ -23,10 +23,7 @@ use triehash::sec_trie_root;
use super::{Update, MemoryState};
/// Output of a commit.
pub struct Committed {
/// Root of the storage tree after changes committed.
pub storage_tree_root: H256,
}
pub struct Committed {}
/// A state backend is used to read state data and can have changes committed
/// to it.
@@ -90,17 +87,7 @@ impl Backend for InMemory {
where I: IntoIterator<Item=Update>
{
self.inner.update(changes);
// fully recalculate trie roots.
let storage_tree_root = H256(sec_trie_root(
self.inner.storage.iter()
.map(|(k, v)| (k.to_vec(), v.clone()))
.collect()
).0);
Committed {
storage_tree_root,
}
Committed {}
}
fn pairs(&self) -> Vec<(&[u8], &[u8])> {
@@ -25,13 +25,13 @@ use runtime::{staking, session, timestamp, governance};
#[cfg_attr(feature = "with-std", derive(PartialEq, Debug))]
#[repr(u8)]
pub enum Function {
StakingStake = 0,
StakingUnstake = 1,
StakingTransfer = 2,
SessionSetKey = 3,
TimestampSet = 4,
GovernancePropose = 5,
GovernanceApprove = 6,
TimestampSet = 0x00,
SessionSetKey = 0x10,
StakingStake = 0x20,
StakingUnstake = 0x21,
StakingTransfer = 0x22,
GovernancePropose = 0x30,
GovernanceApprove = 0x31,
}
impl Function {
@@ -41,11 +41,7 @@ impl Function {
let functions = [Function::StakingStake, Function::StakingUnstake,
Function::StakingTransfer, Function::SessionSetKey, Function::TimestampSet,
Function::GovernancePropose, Function::GovernanceApprove];
if (value as usize) < functions.len() {
Some(functions[value as usize])
} else {
None
}
functions.iter().map(|&f| f).find(|&f| value == f as u8)
}
}
@@ -27,12 +27,17 @@ use runtime::{system, governance, staking, session};
#[cfg_attr(feature = "with-std", derive(PartialEq, Debug))]
#[repr(u8)]
pub enum InternalFunction {
SystemSetCode = 0,
StakingSetSessionsPerEra = 1,
StakingSetBondingDuration = 2,
StakingSetValidatorCount = 3,
GovernanceSetApprovalPpmRequired = 4,
SessionSetLength = 5,
SystemSetCode = 0x00,
SessionSetLength = 0x10,
SessionForceNewSession = 0x11,
StakingSetSessionsPerEra = 0x20,
StakingSetBondingDuration = 0x21,
StakingSetValidatorCount = 0x22,
StakingForceNewEra = 0x23,
GovernanceSetApprovalPpmRequired = 0x30,
}
impl InternalFunction {
@@ -41,17 +46,15 @@ impl InternalFunction {
use self::*;
let functions = [
InternalFunction::SystemSetCode,
InternalFunction::SessionSetLength,
InternalFunction::SessionForceNewSession,
InternalFunction::StakingSetSessionsPerEra,
InternalFunction::StakingSetBondingDuration,
InternalFunction::StakingSetValidatorCount,
InternalFunction::StakingForceNewEra,
InternalFunction::GovernanceSetApprovalPpmRequired,
InternalFunction::SessionSetLength
];
if (value as usize) < functions.len() {
Some(functions[value as usize])
} else {
None
}
functions.iter().map(|&f| f).find(|&f| value == f as u8)
}
}
@@ -93,6 +96,13 @@ impl Proposal {
let code: Vec<u8> = params.read().unwrap();
system::privileged::set_code(&code);
}
InternalFunction::SessionSetLength => {
let value = params.read().unwrap();
session::privileged::set_length(value);
}
InternalFunction::SessionForceNewSession => {
session::privileged::force_new_session();
}
InternalFunction::StakingSetSessionsPerEra => {
let value = params.read().unwrap();
staking::privileged::set_sessions_per_era(value);
@@ -105,14 +115,13 @@ impl Proposal {
let value = params.read().unwrap();
staking::privileged::set_validator_count(value);
}
InternalFunction::StakingForceNewEra => {
staking::privileged::force_new_era();
}
InternalFunction::GovernanceSetApprovalPpmRequired => {
let value = params.read().unwrap();
governance::privileged::set_approval_ppm_required(value);
}
InternalFunction::SessionSetLength => {
let value = params.read().unwrap();
session::privileged::set_length(value);
}
}
}
}
@@ -35,7 +35,7 @@ fn serialise_transaction_works() {
assert_eq!(serialised, vec![
1u8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
2,
34,
40, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0
@@ -55,7 +55,7 @@ fn deserialise_transaction_works() {
let data = [
1u8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
2,
34,
40, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0
@@ -162,7 +162,7 @@ fn serialise_block_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 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
2,
34,
40, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0,
@@ -233,7 +233,7 @@ fn deserialise_block_works() {
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
42, 0, 0, 0, 0, 0, 0, 0,
0,
32,
0, 0, 0, 0
];
let deserialised = Block::from_slice(&data).unwrap();
@@ -0,0 +1,85 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Tool for creating the genesis block.
use std::collections::HashMap;
use runtime_std::twox_128;
use codec::{KeyedVec, Slicable};
use support::Hashable;
use primitives::{AccountID, BlockNumber, Block};
use runtime::staking::Balance;
/// Configuration of a general Polkadot genesis block.
pub struct GenesisConfig {
pub validators: Vec<AccountID>,
pub authorities: Vec<AccountID>,
pub balances: Vec<(AccountID, Balance)>,
pub block_time: u64,
pub session_length: BlockNumber,
pub sessions_per_era: BlockNumber,
pub bonding_duration: u64,
pub approval_ratio: u32,
}
impl GenesisConfig {
pub fn new_simple(authorities_validators: Vec<AccountID>, balance: Balance) -> Self {
GenesisConfig {
validators: authorities_validators.clone(),
authorities: authorities_validators.clone(),
balances: authorities_validators.iter().map(|v| (v.clone(), balance)).collect(),
block_time: 5, // 5 second block time.
session_length: 720, // that's 1 hour per session.
sessions_per_era: 24, // 24 hours per era.
bonding_duration: 90, // 90 days per bond.
approval_ratio: 667, // 66.7% approvals required for legislation.
}
}
pub fn genesis_map(&self) -> HashMap<Vec<u8>, Vec<u8>> {
let wasm_runtime = include_bytes!("../../../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm");
vec![
(&b":code"[..], wasm_runtime.to_vec()),
(&b"gov:apr"[..], self.approval_ratio.to_vec()),
(&b"ses:len"[..], self.session_length.to_vec()),
(&b"ses:val:len"[..], (self.validators.len() as u32).to_vec()),
(&b"con:aut:len"[..], (self.authorities.len() as u32).to_vec()),
(&b"sta:wil:len"[..], 0u32.to_vec()),
(&b"sta:spe"[..], self.sessions_per_era.to_vec()),
(&b"sta:vac"[..], (self.validators.len() as u32).to_vec()),
(&b"sta:era"[..], 0u64.to_vec()),
].into_iter()
.map(|(k, v)| (k.to_vec(), v))
.chain(self.validators.iter()
.enumerate()
.map(|(i, account)| ((i as u32).to_keyed_vec(b"ses:val:"), account.to_vec()))
).chain(self.authorities.iter()
.enumerate()
.map(|(i, account)| ((i as u32).to_keyed_vec(b"con:aut:"), account.to_vec()))
).chain(self.balances.iter()
.map(|&(account, balance)| (account.to_keyed_vec(b"sta:bal:"), balance.to_vec()))
)
.map(|(k, v)| (twox_128(&k[..])[..].to_vec(), v.to_vec()))
.collect()
}
}
pub fn additional_storage_with_genesis(genesis_block: &[u8]) -> Result<HashMap<Vec<u8>, Vec<u8>>, ()> {
let h = Block::from_slice(genesis_block).ok_or(())?.header.blake2_256();
Ok(map![
twox_128(&0u64.to_keyed_vec(b"sys:old:")).to_vec() => h.to_vec()
])
}
@@ -31,3 +31,7 @@ pub mod governance;
// TODO: polkadao
// TODO: parachains
#[cfg(feature = "with-std")]
pub mod genesismap;
@@ -78,6 +78,11 @@ pub mod privileged {
pub fn set_length(new: BlockNumber) {
storage::put(NEXT_SESSION_LENGTH, &new);
}
/// Forces a new session.
pub fn force_new_session() {
rotate_session();
}
}
// INTERNAL API (available to other runtime modules)
@@ -151,6 +151,12 @@ pub mod privileged {
pub fn set_validator_count(new: usize) {
storage::put(VALIDATOR_COUNT, &(new as u32));
}
/// Force there to be a new era. This also forces a new session immediately after.
pub fn force_new_era() {
new_era();
session::privileged::force_new_session();
}
}
pub mod internal {
@@ -79,6 +79,7 @@ pub mod internal {
let txs = block.transactions.iter().map(Slicable::to_vec).collect::<Vec<_>>();
let txs = txs.iter().map(Vec::as_slice).collect::<Vec<_>>();
let txs_root = enumerated_trie_root(&txs);
debug_assert_hash(&header.transaction_root, &txs_root);
assert!(header.transaction_root == txs_root, "Transaction trie root must be valid.");
// execute transactions
@@ -167,10 +168,8 @@ mod tests {
function: Function::StakingTransfer,
input_data: vec![].join(&two).join(&69u64),
},
signature: "679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a".convert(),
signature: "13590ae48241e29780407687b86c331a9f40f3ab7f2cc2441787628bcafab6645dc81863b138a358e2a1ed1ffa940a4584ba94837f022f0cd162791530320904".convert(),
};
// tx: 2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000228000000d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000
// sig: 679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a
println!("tx is {}", HexDisplay::from(&tx.transaction.to_vec()));
@@ -212,33 +211,21 @@ mod tests {
let mut t = new_test_ext();
let tx = UncheckedTransaction {
transaction: Transaction {
signed: one.clone(),
nonce: 0,
function: Function::StakingTransfer,
input_data: vec![].join(&two).join(&69u64),
},
signature: "679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a".convert(),
};
let h = Header {
parent_hash: [69u8; 32],
number: 1,
state_root: hex!("2481853da20b9f4322f34650fea5f240dcbfb266d02db94bfa0153c31f4a29db"),
transaction_root: hex!("91fab88ad8c30a6d05ad8e0cf9ab139bf1b8cdddc69abd51cdfa6d2699038af1"),
state_root: hex!("1ab2dbb7d4868a670b181327b0b6a58dc64b10cfb9876f737a5aa014b8da31e0"),
transaction_root: hex!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"),
digest: Digest { logs: vec![], },
};
let b = Block {
header: h,
transactions: vec![tx],
transactions: vec![],
};
with_externalities(&mut t, || {
execute_block(b);
assert_eq!(staking::balance(&one), 42);
assert_eq!(staking::balance(&two), 69);
});
}
@@ -250,35 +237,21 @@ mod tests {
let mut t = new_test_ext();
let tx = UncheckedTransaction {
transaction: Transaction {
signed: one.clone(),
nonce: 0,
function: Function::StakingTransfer,
input_data: vec![].join(&two).join(&69u64),
},
signature: "679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a".convert(),
};
// tx: 2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000228000000d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000
// sig: 679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a
let h = Header {
parent_hash: [69u8; 32],
number: 1,
state_root: [0u8; 32],
transaction_root: hex!("91fab88ad8c30a6d05ad8e0cf9ab139bf1b8cdddc69abd51cdfa6d2699038af1"),
transaction_root: hex!("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"),
digest: Digest { logs: vec![], },
};
let b = Block {
header: h,
transactions: vec![tx],
transactions: vec![],
};
with_externalities(&mut t, || {
execute_block(b);
assert_eq!(staking::balance(&one), 42);
assert_eq!(staking::balance(&two), 69);
});
}
@@ -290,35 +263,21 @@ mod tests {
let mut t = new_test_ext();
let tx = UncheckedTransaction {
transaction: Transaction {
signed: one.clone(),
nonce: 0,
function: Function::StakingTransfer,
input_data: vec![].join(&two).join(&69u64),
},
signature: "679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a".convert(),
};
// tx: 2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000228000000d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000
// sig: 679fcf0a846b4224c84ecad7d91a26241c46d00cb53d6480a363274e8965ee34b0b80b4b2e3836d3d8f8f12c0c1aef7350af587d9aee3883561d11726068ac0a
let h = Header {
parent_hash: [69u8; 32],
number: 1,
state_root: hex!("2481853da20b9f4322f34650fea5f240dcbfb266d02db94bfa0153c31f4a29db"),
state_root: hex!("1ab2dbb7d4868a670b181327b0b6a58dc64b10cfb9876f737a5aa014b8da31e0"),
transaction_root: [0u8; 32],
digest: Digest { logs: vec![], },
};
let b = Block {
header: h,
transactions: vec![tx],
transactions: vec![],
};
with_externalities(&mut t, || {
execute_block(b);
assert_eq!(staking::balance(&one), 42);
assert_eq!(staking::balance(&two), 69);
});
}
}