// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate 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.
// Substrate 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 Substrate. If not, see .
//! Runtime Modules shared primitive types.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[doc(hidden)]
pub use parity_codec as codec;
#[cfg(feature = "std")]
#[doc(hidden)]
pub use serde;
#[cfg(feature = "std")]
pub use runtime_io::{StorageOverlay, ChildrenStorageOverlay};
use rstd::prelude::*;
use substrate_primitives::{crypto, ed25519, sr25519, hash::{H256, H512}};
use codec::{Encode, Decode};
#[cfg(feature = "std")]
pub mod testing;
pub mod traits;
pub mod generic;
pub mod transaction_validity;
/// A message indicating an invalid signature in extrinsic.
pub const BAD_SIGNATURE: &str = "bad signature in extrinsic";
/// Full block error message.
///
/// This allows modules to indicate that given transaction is potentially valid
/// in the future, but can't be executed in the current state.
/// Note this error should be returned early in the execution to prevent DoS,
/// cause the fees are not being paid if this error is returned.
///
/// Example: block gas limit is reached (the transaction can be retried in the next block though).
pub const BLOCK_FULL: &str = "block size limit is reached";
/// Justification type.
pub type Justification = Vec;
use traits::{Verify, Lazy};
/// A String that is a `&'static str` on `no_std` and a `Cow<'static, str>` on `std`.
#[cfg(feature = "std")]
pub type RuntimeString = ::std::borrow::Cow<'static, str>;
/// A String that is a `&'static str` on `no_std` and a `Cow<'static, str>` on `std`.
#[cfg(not(feature = "std"))]
pub type RuntimeString = &'static str;
/// Create a const [RuntimeString].
#[cfg(feature = "std")]
#[macro_export]
macro_rules! create_runtime_str {
( $y:expr ) => {{ ::std::borrow::Cow::Borrowed($y) }}
}
/// Create a const [RuntimeString].
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! create_runtime_str {
( $y:expr ) => {{ $y }}
}
#[cfg(feature = "std")]
pub use serde::{Serialize, Deserialize, de::DeserializeOwned};
/// Complex storage builder stuff.
#[cfg(feature = "std")]
pub trait BuildStorage: Sized {
/// Build the storage out of this builder.
fn build_storage(self) -> Result<(StorageOverlay, ChildrenStorageOverlay), String> {
let mut storage = Default::default();
let mut child_storage = Default::default();
self.assimilate_storage(&mut storage, &mut child_storage)?;
Ok((storage, child_storage))
}
/// Assimilate the storage for this module into pre-existing overlays.
fn assimilate_storage(self, storage: &mut StorageOverlay, child_storage: &mut ChildrenStorageOverlay) -> Result<(), String>;
}
#[cfg(feature = "std")]
impl BuildStorage for StorageOverlay {
fn build_storage(self) -> Result<(StorageOverlay, ChildrenStorageOverlay), String> {
Ok((self, Default::default()))
}
fn assimilate_storage(self, storage: &mut StorageOverlay, _child_storage: &mut ChildrenStorageOverlay) -> Result<(), String> {
storage.extend(self);
Ok(())
}
}
/// Consensus engine unique ID.
pub type ConsensusEngineId = [u8; 4];
/// Permill is parts-per-million (i.e. after multiplying by this, divide by 1000000).
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq)]
pub struct Permill(u32);
impl Permill {
/// Wraps the argument into `Permill` type.
pub fn from_millionths(x: u32) -> Permill { Permill(x) }
/// Converts percents into `Permill`.
pub fn from_percent(x: u32) -> Permill { Permill(x * 10_000) }
/// Converts a fraction into `Permill`.
#[cfg(feature = "std")]
pub fn from_fraction(x: f64) -> Permill { Permill((x * 1_000_000.0) as u32) }
}
impl ::rstd::ops::Mul for Permill
where
N: traits::As
{
type Output = N;
fn mul(self, b: N) -> Self::Output {
>::sa(b.as_().saturating_mul(self.0 as u64) / 1_000_000)
}
}
#[cfg(feature = "std")]
impl From for Permill {
fn from(x: f64) -> Permill {
Permill::from_fraction(x)
}
}
#[cfg(feature = "std")]
impl From for Permill {
fn from(x: f32) -> Permill {
Permill::from_fraction(x as f64)
}
}
impl codec::CompactAs for Permill {
type As = u32;
fn encode_as(&self) -> &u32 {
&self.0
}
fn decode_from(x: u32) -> Permill {
Permill(x)
}
}
impl From> for Permill {
fn from(x: codec::Compact) -> Permill {
x.0
}
}
/// Perbill is parts-per-billion. It stores a value between 0 and 1 in fixed point and
/// provides a means to multiply some other value by that.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq)]
pub struct Perbill(u32);
impl Perbill {
/// Nothing.
pub fn zero() -> Perbill { Perbill(0) }
/// `true` if this is nothing.
pub fn is_zero(&self) -> bool { self.0 == 0 }
/// Everything.
pub fn one() -> Perbill { Perbill(1_000_000_000) }
/// Construct new instance where `x` is in billionths. Value equivalent to `x / 1,000,000,000`.
pub fn from_billionths(x: u32) -> Perbill { Perbill(x.min(1_000_000_000)) }
/// Construct new instance where `x` is in millionths. Value equivalent to `x / 1,000,000`.
pub fn from_millionths(x: u32) -> Perbill { Perbill(x.min(1_000_000) * 1000) }
/// Construct new instance where `x` is a percent. Value equivalent to `x%`.
pub fn from_percent(x: u32) -> Perbill { Perbill(x.min(100) * 10_000_000) }
#[cfg(feature = "std")]
/// Construct new instance whose value is equal to `x` (between 0 and 1).
pub fn from_fraction(x: f64) -> Perbill { Perbill((x.max(0.0).min(1.0) * 1_000_000_000.0) as u32) }
#[cfg(feature = "std")]
/// Construct new instance whose value is equal to `n / d` (between 0 and 1).
pub fn from_rational(n: f64, d: f64) -> Perbill { Perbill(((n / d).max(0.0).min(1.0) * 1_000_000_000.0) as u32) }
}
impl ::rstd::ops::Mul for Perbill
where
N: traits::As
{
type Output = N;
fn mul(self, b: N) -> Self::Output {
>::sa(b.as_().saturating_mul(self.0 as u64) / 1_000_000_000)
}
}
#[cfg(feature = "std")]
impl From for Perbill {
fn from(x: f64) -> Perbill {
Perbill::from_fraction(x)
}
}
#[cfg(feature = "std")]
impl From for Perbill {
fn from(x: f32) -> Perbill {
Perbill::from_fraction(x as f64)
}
}
impl codec::CompactAs for Perbill {
type As = u32;
fn encode_as(&self) -> &u32 {
&self.0
}
fn decode_from(x: u32) -> Perbill {
Perbill(x)
}
}
impl From> for Perbill {
fn from(x: codec::Compact) -> Perbill {
x.0
}
}
/// PerU128 is parts-per-u128-max-value. It stores a value between 0 and 1 in fixed point and
/// provides a means to multiply some other value by that.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq)]
pub struct PerU128(u128);
const U128: u128 = u128::max_value();
impl PerU128 {
/// Nothing.
pub fn zero() -> Self { Self(0) }
/// Everything.
pub fn one() -> Self { Self(U128) }
/// Construct new instance where `x` is parts in u128::max_value. Equal to x/U128::max_value.
pub fn from_max_value(x: u128) -> Self { Self(x) }
/// Construct new instance where `x` is denominator and the nominator is 1.
pub fn from_xth(x: u128) -> Self { Self(U128/x.max(1)) }
}
impl ::rstd::ops::Deref for PerU128 {
type Target = u128;
fn deref(&self) -> &u128 {
&self.0
}
}
impl codec::CompactAs for PerU128 {
type As = u128;
fn encode_as(&self) -> &u128 {
&self.0
}
fn decode_from(x: u128) -> PerU128 {
Self(x)
}
}
impl From> for PerU128 {
fn from(x: codec::Compact) -> PerU128 {
x.0
}
}
/// Signature verify that can work with any known signature types..
#[derive(Eq, PartialEq, Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum MultiSignature {
/// An Ed25519 signature.
Ed25519(ed25519::Signature),
/// An Sr25519 signature.
Sr25519(sr25519::Signature),
}
impl From for MultiSignature {
fn from(x: ed25519::Signature) -> Self {
MultiSignature::Ed25519(x)
}
}
impl From for MultiSignature {
fn from(x: sr25519::Signature) -> Self {
MultiSignature::Sr25519(x)
}
}
impl Default for MultiSignature {
fn default() -> Self {
MultiSignature::Ed25519(Default::default())
}
}
/// Public key for any known crypto algorithm.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
pub enum MultiSigner {
/// An Ed25519 identity.
Ed25519(ed25519::Public),
/// An Sr25519 identity.
Sr25519(sr25519::Public),
}
impl Default for MultiSigner {
fn default() -> Self {
MultiSigner::Ed25519(Default::default())
}
}
/// NOTE: This implementations is required by `SimpleAddressDeterminator`,
/// we convert the hash into some AccountId, it's fine to use any scheme.
impl> crypto::UncheckedFrom for MultiSigner {
fn unchecked_from(x: T) -> Self {
ed25519::Public::unchecked_from(x.into()).into()
}
}
impl AsRef<[u8]> for MultiSigner {
fn as_ref(&self) -> &[u8] {
match *self {
MultiSigner::Ed25519(ref who) => who.as_ref(),
MultiSigner::Sr25519(ref who) => who.as_ref(),
}
}
}
impl From for MultiSigner {
fn from(x: ed25519::Public) -> Self {
MultiSigner::Ed25519(x)
}
}
impl From for MultiSigner {
fn from(x: sr25519::Public) -> Self {
MultiSigner::Sr25519(x)
}
}
#[cfg(feature = "std")]
impl std::fmt::Display for MultiSigner {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
MultiSigner::Ed25519(ref who) => write!(fmt, "ed25519: {}", who),
MultiSigner::Sr25519(ref who) => write!(fmt, "sr25519: {}", who),
}
}
}
impl Verify for MultiSignature {
type Signer = MultiSigner;
fn verify>(&self, msg: L, signer: &Self::Signer) -> bool {
match (self, signer) {
(MultiSignature::Ed25519(ref sig), &MultiSigner::Ed25519(ref who)) => sig.verify(msg, who),
(MultiSignature::Sr25519(ref sig), &MultiSigner::Sr25519(ref who)) => sig.verify(msg, who),
_ => false,
}
}
}
/// Signature verify that can work with any known signature types..
#[derive(Eq, PartialEq, Clone, Default, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
pub struct AnySignature(H512);
impl Verify for AnySignature {
type Signer = sr25519::Public;
fn verify>(&self, mut msg: L, signer: &sr25519::Public) -> bool {
runtime_io::sr25519_verify(self.0.as_fixed_bytes(), msg.get(), &signer.0) ||
runtime_io::ed25519_verify(self.0.as_fixed_bytes(), msg.get(), &signer.0)
}
}
impl From for AnySignature {
fn from(s: sr25519::Signature) -> Self {
AnySignature(s.into())
}
}
impl From for AnySignature {
fn from(s: ed25519::Signature) -> Self {
AnySignature(s.into())
}
}
#[derive(Eq, PartialEq, Clone, Copy, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Serialize))]
#[repr(u8)]
/// Outcome of a valid extrinsic application. Capable of being sliced.
pub enum ApplyOutcome {
/// Successful application (extrinsic reported no issue).
Success = 0,
/// Failed application (extrinsic was probably a no-op other than fees).
Fail = 1,
}
impl codec::Encode for ApplyOutcome {
fn using_encoded R>(&self, f: F) -> R {
f(&[*self as u8])
}
}
#[derive(Eq, PartialEq, Clone, Copy, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Serialize))]
#[repr(u8)]
/// Reason why an extrinsic couldn't be applied (i.e. invalid extrinsic).
pub enum ApplyError {
/// Bad signature.
BadSignature = 0,
/// Nonce too low.
Stale = 1,
/// Nonce too high.
Future = 2,
/// Sending account had too low a balance.
CantPay = 3,
/// Block is full, no more extrinsics can be applied.
FullBlock = 255,
}
impl codec::Encode for ApplyError {
fn using_encoded R>(&self, f: F) -> R {
f(&[*self as u8])
}
}
/// Result from attempt to apply an extrinsic.
pub type ApplyResult = Result;
/// Verify a signature on an encoded value in a lazy manner. This can be
/// an optimization if the signature scheme has an "unsigned" escape hash.
pub fn verify_encoded_lazy(sig: &V, item: &T, signer: &V::Signer) -> bool {
// The `Lazy` trait expresses something like `X: FnMut