Repot and introduce keccak-256 external.

This commit is contained in:
Gav
2018-01-17 11:45:36 +01:00
parent 17c8bad87c
commit 98faf54ec4
24 changed files with 88 additions and 117 deletions
@@ -0,0 +1,73 @@
use runtime_support::Vec;
use keyedvec::KeyedVec;
use storage::Storage;
use primitives::{AccountID, SessionKey, BlockNumber};
use storage::storage_into;
pub fn set_authority(index: u32, authority: AccountID) {
authority.store(&index.to_keyed_vec(b"con\0aut\0"));
}
fn authority(index: u32) -> AccountID {
storage_into(&index.to_keyed_vec(b"con\0aut\0"))
}
pub fn set_authority_count(count: u32) {
(count..authority_count()).for_each(|i| set_authority(i, SessionKey::default()));
count.store(b"con\0aut\0len");
}
fn authority_count() -> u32 {
storage_into(b"con\0aut\0len")
}
/// Get the current set of authorities. These are the session keys.
pub fn authorities() -> Vec<AccountID> {
(0..authority_count()).into_iter().map(authority).collect()
}
/// Set the current set of authorities' session keys.
///
/// Called by `next_session` only.
pub fn set_authorities(authorities: &[AccountID]) {
set_authority_count(authorities.len() as u32);
authorities.iter().enumerate().for_each(|(v, &i)| set_authority(v as u32, i));
}
/// Get the current set of validators. These are the long-term identifiers for the validators
/// and will be mapped to a session key with the most recent `set_next_session_key`.
pub fn validators() -> Vec<AccountID> {
unimplemented!()
}
/// Set the current set of validators.
///
/// Called by staking::next_era() only.
pub fn set_validators(_new: &[AccountID]) {
unimplemented!()
}
/// The number of blocks in each session.
pub fn session_length() -> BlockNumber {
storage_into(b"con\0bps")
}
/// Sets the session key of `_transactor` to `_session`. This doesn't take effect until the next
/// session.
pub fn set_session_key(_transactor: &AccountID, _session: &AccountID) {
unimplemented!()
}
/// Move onto next session: register the new authority set.
pub fn next_session() {
// TODO: Call set_authorities().
unimplemented!()
}
/// Hook to be called prior to transaction processing.
pub fn pre_transactions() {}
/// Hook to be called after to transaction processing.
pub fn post_transactions() {
// TODO: check block number and call next_session if necessary.
}
@@ -0,0 +1,8 @@
#[allow(unused)]
pub mod system;
#[allow(unused)]
pub mod consensus;
#[allow(unused)]
pub mod staking;
#[allow(unused)]
pub mod timestamp;
@@ -0,0 +1,109 @@
use keyedvec::KeyedVec;
use storage::{Storage, storage_into};
use primitives::{BlockNumber, Balance, AccountID};
use runtime::consensus;
/// The length of a staking era in blocks.
pub fn era_length() -> BlockNumber {
sessions_per_era() * consensus::session_length()
}
/// The length of a staking era in sessions.
pub fn sessions_per_era() -> BlockNumber {
storage_into(b"sta\0spe")
}
/// The era has changed - enact new staking set.
///
/// NOTE: This always happens on a session change.
pub fn next_era() {
unimplemented!()
}
/// The balance of a given account.
pub fn balance(who: &AccountID) -> Balance {
storage_into(&who.to_keyed_vec(b"sta\0bal\0"))
}
/// Transfer some unlocked staking balance to another staker.
pub fn transfer_stake(transactor: &AccountID, dest: &AccountID, value: Balance) {
let from_key = transactor.to_keyed_vec(b"sta\0bal\0");
let from_balance: Balance = storage_into(&from_key);
assert!(from_balance >= value);
let to_key = dest.to_keyed_vec(b"sta\0bal\0");
let to_balance: Balance = storage_into(&to_key);
assert!(to_balance + value > to_balance); // no overflow
(from_balance - value).store(&from_key);
(to_balance + value).store(&to_key);
}
/// Declare the desire to stake for the transactor.
///
/// Effects will be felt at the beginning of the next era.
pub fn stake(_transactor: &AccountID) {
unimplemented!()
}
/// Retract the desire to stake for the transactor.
///
/// Effects will be felt at the beginning of the next era.
pub fn unstake(_transactor: &AccountID) {
unimplemented!()
}
/// Hook to be called prior to transaction processing.
pub fn pre_transactions() {
consensus::pre_transactions();
}
/// Hook to be called after to transaction processing.
pub fn post_transactions() {
// TODO: check block number and call next_era if necessary.
consensus::post_transactions();
}
#[cfg(test)]
mod tests {
use runtime_support::with_externalities;
use testing::TestExternalities;
use primitives::{AccountID};
use runtime::staking;
macro_rules! map {
($( $name:expr => $value:expr ),*) => (
vec![ $( ( $name, $value ) ),* ].into_iter().collect()
)
}
#[test]
fn staking_balance_works() {
let one: AccountID = [1u8; 32];
let two: AccountID = [2u8; 32];
let mut t = TestExternalities { storage: map![
{ let mut r = b"sta\0bal\0".to_vec(); r.extend_from_slice(&one); r } => vec![42u8, 0, 0, 0, 0, 0, 0, 0]
], };
with_externalities(&mut t, || {
assert_eq!(staking::balance(&one), 42);
assert_eq!(staking::balance(&two), 0);
});
}
#[test]
fn staking_balance_transfer_works() {
let one: AccountID = [1u8; 32];
let two: AccountID = [2u8; 32];
let mut t = TestExternalities { storage: map![
{ let mut r = b"sta\0bal\0".to_vec(); r.extend_from_slice(&one); r } => vec![111u8, 0, 0, 0, 0, 0, 0, 0]
], };
with_externalities(&mut t, || {
staking::transfer_stake(&one, &two, 69);
assert_eq!(staking::balance(&one), 42);
assert_eq!(staking::balance(&two), 69);
});
}
}
@@ -0,0 +1,130 @@
use primitives::{Block, BlockNumber, Hash, Transaction};
use runtime_support::{Vec, swap};
use environment::with_env;
use runtime_support;
use runtime::staking;
/// The current block number being processed. Set by `execute_block`.
pub fn block_number() -> BlockNumber {
with_env(|e| e.block_number)
}
/// Get the block hash of a given block (uses storage).
pub fn block_hash(_number: BlockNumber) -> Hash {
unimplemented!()
}
/// Deposits a log and ensures it matches the blocks log data.
pub fn deposit_log(log: &[u8]) {
with_env(|e| {
assert_eq!(log, &e.digest.logs[e.next_log_index][..]);
e.next_log_index += 1;
});
}
pub fn execute_block(mut block: Block) -> Vec<u8> {
// populate environment from header.
with_env(|e| {
e.block_number = block.header.number;
swap(&mut e.digest, &mut block.header.digest);
e.next_log_index = 0;
});
// TODO: check transaction trie root represents the transactions.
// TODO: store the header hash in storage.
staking::pre_transactions();
block.transactions.iter().for_each(|tx| { execute_transaction(tx); });
staking::post_transactions();
final_checks(&block);
// TODO: check state root somehow
Vec::new()
}
fn final_checks(_block: &Block) {
with_env(|e| {
assert_eq!(e.next_log_index, e.digest.logs.len());
});
}
/// Execute a given transaction.
pub fn execute_transaction(_tx: &Transaction) -> Vec<u8> {
// TODO: decode data and ensure valid
// TODO: ensure signature valid and recover id (use authentication::authenticate)
// TODO: check nonce
// TODO: increment nonce in storage
// TODO: ensure target_function valid
// TODO: decode parameters
_tx.function.dispatch(&_tx.signed, &_tx.input_data);
// TODO: encode any return
Vec::new()
}
/// Set the new code.
pub fn set_code(new: &[u8]) {
runtime_support::set_storage(b"\0code", new)
}
#[cfg(test)]
mod tests {
use joiner::Joiner;
use function::Function;
use std::collections::HashMap;
use runtime_support::{NoError, with_externalities, Externalities};
use primitives::{AccountID, Transaction};
use runtime::{system, staking};
#[derive(Debug, Default)]
struct TestExternalities {
storage: HashMap<Vec<u8>, Vec<u8>>,
}
impl Externalities for TestExternalities {
type Error = NoError;
fn storage(&self, key: &[u8]) -> Result<&[u8], NoError> {
Ok(self.storage.get(&key.to_vec()).map_or(&[] as &[u8], Vec::as_slice))
}
fn set_storage(&mut self, key: Vec<u8>, value: Vec<u8>) {
self.storage.insert(key, value);
}
fn chain_id(&self) -> u64 { 42 }
}
macro_rules! map {
($( $name:expr => $value:expr ),*) => (
vec![ $( ( $name, $value ) ),* ].into_iter().collect()
)
}
#[test]
fn staking_balance_transfer_dispatch_works() {
let one: AccountID = [1u8; 32];
let two: AccountID = [2u8; 32];
let mut t = TestExternalities { storage: map![
{ let mut r = b"sta\0bal\0".to_vec(); r.extend_from_slice(&one); r } => vec![111u8, 0, 0, 0, 0, 0, 0, 0]
], };
let tx = Transaction {
signed: one.clone(),
function: Function::StakingTransferStake,
input_data: vec![].join(&two).join(&69u64),
nonce: 0,
};
with_externalities(&mut t, || {
system::execute_transaction(&tx);
assert_eq!(staking::balance(&one), 42);
assert_eq!(staking::balance(&two), 69);
});
}
}
@@ -0,0 +1,9 @@
use primitives::Timestamp;
pub fn timestamp() -> Timestamp {
unimplemented!()
}
pub fn set_timestamp(_now: Timestamp) {
unimplemented!()
}