Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[core,model] Add ext_random_seed runtime call bindings #54

Merged
merged 14 commits into from
Apr 17, 2019
Merged
Show file tree
Hide file tree
Changes from 12 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
8 changes: 8 additions & 0 deletions core/src/env/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub type Address = <ContractEnv as EnvTypes>::Address;
/// The environmental balance type.
pub type Balance = <ContractEnv as EnvTypes>::Balance;

/// The environmental hash type.
pub type Hash = <ContractEnv as EnvTypes>::Hash;

/// Returns the address of the caller of the current smart contract execution.
pub fn caller() -> Address {
ContractEnv::caller()
Expand All @@ -41,6 +44,11 @@ pub fn input() -> Vec<u8> {
ContractEnv::input()
}

/// Returns the random seed from the latest block.
pub fn random_seed() -> Hash {
ContractEnv::random_seed()
}

/// Returns the current smart contract exection back to the caller
/// and return the given encoded value.
///
Expand Down
1 change: 1 addition & 0 deletions core/src/env/srml/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod types;
pub use self::types::{
Address,
Balance,
Hash,
DefaultSrmlTypes,
};

Expand Down
19 changes: 16 additions & 3 deletions core/src/env/srml/srml_only/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ where
{
type Address = <T as EnvTypes>::Address;
type Balance = <T as EnvTypes>::Balance;
type Hash = <T as EnvTypes>::Hash;
}

impl<T> EnvStorage for SrmlEnv<T>
Expand Down Expand Up @@ -88,6 +89,7 @@ impl<T> Env for SrmlEnv<T>
where
T: EnvTypes,
<T as EnvTypes>::Address: for<'a> From<&'a [u8]>,
<T as EnvTypes>::Hash: for<'a> From<&'a [u8]>,
{
fn caller() -> <Self as EnvTypes>::Address {
unsafe { sys::ext_caller() };
Expand Down Expand Up @@ -116,13 +118,24 @@ where
}
}

fn random_seed() -> <Self as EnvTypes>::Hash {
unsafe { sys::ext_random_seed() };
let size = unsafe { sys::ext_scratch_size() };
let mut value = Vec::new();
if size > 0 {
value.resize(size as usize, 0);
unsafe {
sys::ext_scratch_copy(value.as_mut_ptr() as u32, 0, size);
}
}
value.as_slice().into()
}

unsafe fn r#return(data: &[u8]) -> ! {
sys::ext_return(data.as_ptr() as u32, data.len() as u32);
}

fn println(content: &str) {
unsafe {
sys::ext_println(content.as_ptr() as u32, content.len() as u32)
}
unsafe { sys::ext_println(content.as_ptr() as u32, content.len() as u32) }
}
}
42 changes: 35 additions & 7 deletions core/src/env/srml/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with pDSL. If not, see <http://www.gnu.org/licenses/>.

use core::convert::TryFrom;
use core::array::TryFromSliceError;

use crate::env::EnvTypes;
use parity_codec::{
Decode,
Expand All @@ -26,21 +29,46 @@ pub struct DefaultSrmlTypes;
impl EnvTypes for DefaultSrmlTypes {
type Address = self::Address;
type Balance = self::Balance;
type Hash = self::Hash;
}

/// The default SRML address type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encode, Decode)]
pub struct Address([u8; 32]);

impl<'a> From<&'a [u8]> for Address {
fn from(bytes: &'a [u8]) -> Self {
assert_eq!(bytes.len(), 32);
let mut array = [0; 32];
let bytes = &bytes[..array.len()]; // panics if not enough data
array.copy_from_slice(bytes);
Address(array)
impl From<[u8;32]> for Address {
fn from(address: [u8; 32]) -> Address {
Address(address)
}
}

impl<'a> TryFrom<&'a [u8]> for Address {
type Error = TryFromSliceError;

fn try_from(bytes: &'a [u8]) -> Result<Address, TryFromSliceError> {
let address = <[u8; 32]>::try_from(bytes)?;
Ok(Address(address))
}
}

/// The default SRML balance type.
pub type Balance = u64;

/// The default SRML hash type.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encode, Decode)]
pub struct Hash([u8; 32]);
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved

impl From<[u8;32]> for Hash {
fn from(hash: [u8; 32]) -> Hash {
Hash(hash)
}
}

impl<'a> TryFrom<&'a [u8]> for Hash {
type Error = TryFromSliceError;

fn try_from(bytes: &'a [u8]) -> Result<Hash, TryFromSliceError> {
let hash = <[u8; 32]>::try_from(bytes)?;
Ok(Hash(hash))
}
}
49 changes: 41 additions & 8 deletions core/src/env/test_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with pDSL. If not, see <http://www.gnu.org/licenses/>.

use std::convert::TryFrom;
use super::*;
use crate::{
env::srml,
Expand Down Expand Up @@ -103,13 +104,19 @@ pub struct TestEnvData {
/// # Note
///
/// The current caller can be adjusted by `TestEnvData::set_caller`.
caller: Vec<u8>,
caller: srml::Address,
/// The input data for the next contract invocation.
///
/// # Note
///
/// The current input can be adjusted by `TestEnvData::set_input`.
input: Vec<u8>,
/// The random seed for the next contract invocation.
///
/// # Note
///
/// The current random seed can be adjusted by `TestEnvData::set_random_seed`.
random_seed: srml::Hash,
/// The expected return data of the next contract invocation.
///
/// # Note
Expand All @@ -126,8 +133,9 @@ impl Default for TestEnvData {
fn default() -> Self {
Self {
storage: HashMap::new(),
caller: vec![0x0; 32],
caller: srml::Address::from([0x0; 32]),
input: Vec::new(),
random_seed: srml::Hash::from([0x0; 32]),
expected_return: Vec::new(),
total_reads: Cell::new(0),
total_writes: 0,
Expand All @@ -139,8 +147,9 @@ impl TestEnvData {
/// Resets `self` as if no contract execution happened so far.
pub fn reset(&mut self) {
self.storage.clear();
self.caller.clear();
self.caller = srml::Address::from([0; 32]);
self.input.clear();
self.random_seed = srml::Hash::from([0; 32]);
self.expected_return.clear();
self.total_reads.set(0);
self.total_writes = 0;
Expand Down Expand Up @@ -182,14 +191,19 @@ impl TestEnvData {
}

/// Sets the caller address for the next contract invocation.
pub fn set_caller(&mut self, new_caller: &[u8]) {
self.caller = new_caller.to_vec();
pub fn set_caller(&mut self, new_caller: srml::Address) {
self.caller = new_caller;
}

/// Sets the input data for the next contract invocation.
pub fn set_input(&mut self, input_bytes: &[u8]) {
self.input = input_bytes.to_vec();
}

/// Sets the random seed for the next contract invocation.
pub fn set_random_seed(&mut self, random_seed_hash: srml::Hash) {
self.random_seed = random_seed_hash;
}
}

impl TestEnvData {
Expand All @@ -210,7 +224,7 @@ impl TestEnvData {

/// Returns the caller of the contract invocation.
pub fn caller(&self) -> srml::Address {
srml::Address::from(self.caller.as_slice())
self.caller
}

/// Stores the given value under the given key in the contract storage.
Expand Down Expand Up @@ -242,6 +256,11 @@ impl TestEnvData {
self.input.clone()
}

/// Returns the random seed for the contract invocation.
pub fn random_seed(&self) -> srml::Hash {
self.random_seed
}

/// Returns the data to the internal caller.
///
/// # Note
Expand Down Expand Up @@ -311,21 +330,28 @@ impl TestEnv {
}

/// Sets the caller address for the next contract invocation.
pub fn set_caller(new_caller: &[u8]) {
pub fn set_caller(new_caller: srml::Address) {
TEST_ENV_DATA.with(|test_env| test_env.borrow_mut().set_caller(new_caller))
}

/// Sets the input data for the next contract invocation.
pub fn set_input(input_bytes: &[u8]) {
TEST_ENV_DATA.with(|test_env| test_env.borrow_mut().set_input(input_bytes))
}

/// Sets the random seed for the next contract invocation.
pub fn set_random_seed(random_seed_bytes: srml::Hash) {
TEST_ENV_DATA
.with(|test_env| test_env.borrow_mut().set_random_seed(random_seed_bytes))
}
}

const TEST_ENV_LOG_TARGET: &str = "test-env";

impl EnvTypes for TestEnv {
type Address = srml::Address;
type Balance = srml::Balance;
type Hash = srml::Hash;
}

impl EnvStorage for TestEnv {
Expand Down Expand Up @@ -360,7 +386,9 @@ impl EnvStorage for TestEnv {

impl Env for TestEnv
where
<Self as EnvTypes>::Address: for<'a> From<&'a [u8]>,
<Self as EnvTypes>::Address: for<'a> TryFrom<&'a [u8]>,
<Self as EnvTypes>::Hash: for<'a> TryFrom<&'a [u8]>,

{
fn caller() -> <Self as EnvTypes>::Address {
log::debug!(target: TEST_ENV_LOG_TARGET, "TestEnv::caller()");
Expand All @@ -372,6 +400,11 @@ where
TEST_ENV_DATA.with(|test_env| test_env.borrow().input())
}

fn random_seed() -> <Self as EnvTypes>::Hash {
log::debug!(target: TEST_ENV_LOG_TARGET, "TestEnv::random_seed()",);
TEST_ENV_DATA.with(|test_env| test_env.borrow().random_seed())
}

unsafe fn r#return(data: &[u8]) -> ! {
log::debug!(
target: TEST_ENV_LOG_TARGET,
Expand Down
5 changes: 5 additions & 0 deletions core/src/env/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub trait EnvTypes {
type Address: Codec + PartialEq + Eq;
/// The type of balances.
type Balance: Codec;
/// The type of hash.
type Hash: Codec;
}

/// Types implementing this can act as contract storage.
Expand Down Expand Up @@ -63,6 +65,9 @@ pub trait Env: EnvTypes + EnvStorage {
/// Loads input data for contract execution.
fn input() -> Vec<u8>;

/// Get the random seed from the latest block.
fn random_seed() -> <Self as EnvTypes>::Hash;

/// Returns from the contract execution with the given value.
///
/// # Safety
Expand Down