#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "bench", feature(test))]
#[cfg(feature = "bench")] extern crate test;
#[doc(hidden)]
pub use codec;
#[cfg(feature = "std")]
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
pub use sp_std;
#[doc(hidden)]
pub use paste;
#[doc(hidden)]
pub use sp_application_crypto as app_crypto;
#[cfg(feature = "std")]
pub use sp_core::storage::{Storage, StorageChild};
use sp_std::prelude::*;
use sp_std::convert::TryFrom;
use sp_core::{crypto::{self, Public}, ed25519, sr25519, ecdsa, hash::{H256, H512}};
use codec::{Encode, Decode};
pub mod curve;
pub mod generic;
pub mod offchain;
#[cfg(feature = "std")]
pub mod testing;
pub mod traits;
pub mod transaction_validity;
pub mod random_number_generator;
mod runtime_string;
mod multiaddress;
pub use crate::runtime_string::*;
pub use multiaddress::MultiAddress;
pub use generic::{DigestItem, Digest};
pub use sp_core::{TypeId, crypto::{key_types, KeyTypeId, CryptoType, CryptoTypeId, AccountId32}};
pub use sp_application_crypto::{RuntimeAppPublic, BoundToRuntimeAppPublic};
pub use sp_core::RuntimeDebug;
pub use sp_arithmetic::{
PerThing, Perquintill, Perbill, Permill, Percent, PerU16, InnerOf, UpperOf,
Rational128, FixedI64, FixedI128, FixedU128, FixedPointNumber, FixedPointOperand,
traits::SaturatedConversion,
};
pub use sp_arithmetic::helpers_128bit;
pub use sp_arithmetic::biguint;
pub use random_number_generator::RandomNumberGenerator;
pub use either::Either;
pub type Justification = Vec<u8>;
use traits::{Verify, Lazy};
#[derive(Clone, Copy, Eq, PartialEq, Encode, Decode)]
pub struct ModuleId(pub [u8; 8]);
impl TypeId for ModuleId {
const TYPE_ID: [u8; 4] = *b"modl";
}
#[cfg(feature = "std")]
pub use serde::{Serialize, Deserialize, de::DeserializeOwned};
use crate::traits::IdentifyAccount;
#[cfg(feature = "std")]
pub trait BuildStorage {
fn build_storage(&self) -> Result<sp_core::storage::Storage, String> {
let mut storage = Default::default();
self.assimilate_storage(&mut storage)?;
Ok(storage)
}
fn assimilate_storage(
&self,
storage: &mut sp_core::storage::Storage,
) -> Result<(), String>;
}
#[cfg(feature = "std")]
pub trait BuildModuleGenesisStorage<T, I>: Sized {
fn build_module_genesis_storage(
&self,
storage: &mut sp_core::storage::Storage,
) -> Result<(), String>;
}
#[cfg(feature = "std")]
impl BuildStorage for sp_core::storage::Storage {
fn assimilate_storage(
&self,
storage: &mut sp_core::storage::Storage,
)-> Result<(), String> {
storage.top.extend(self.top.iter().map(|(k, v)| (k.clone(), v.clone())));
for (k, other_map) in self.children_default.iter() {
let k = k.clone();
if let Some(map) = storage.children_default.get_mut(&k) {
map.data.extend(other_map.data.iter().map(|(k, v)| (k.clone(), v.clone())));
if !map.child_info.try_update(&other_map.child_info) {
return Err("Incompatible child info update".to_string());
}
} else {
storage.children_default.insert(k, other_map.clone());
}
}
Ok(())
}
}
#[cfg(feature = "std")]
impl BuildStorage for () {
fn assimilate_storage(
&self,
_: &mut sp_core::storage::Storage,
) -> Result<(), String> {
Err("`assimilate_storage` not implemented for `()`".into())
}
}
pub type ConsensusEngineId = [u8; 4];
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Eq, PartialEq, Clone, Encode, Decode, RuntimeDebug)]
pub enum MultiSignature {
Ed25519(ed25519::Signature),
Sr25519(sr25519::Signature),
Ecdsa(ecdsa::Signature),
}
impl From<ed25519::Signature> for MultiSignature {
fn from(x: ed25519::Signature) -> Self {
MultiSignature::Ed25519(x)
}
}
impl TryFrom<MultiSignature> for ed25519::Signature {
type Error = ();
fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
if let MultiSignature::Ed25519(x) = m { Ok(x) } else { Err(()) }
}
}
impl From<sr25519::Signature> for MultiSignature {
fn from(x: sr25519::Signature) -> Self {
MultiSignature::Sr25519(x)
}
}
impl TryFrom<MultiSignature> for sr25519::Signature {
type Error = ();
fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
if let MultiSignature::Sr25519(x) = m { Ok(x) } else { Err(()) }
}
}
impl From<ecdsa::Signature> for MultiSignature {
fn from(x: ecdsa::Signature) -> Self {
MultiSignature::Ecdsa(x)
}
}
impl TryFrom<MultiSignature> for ecdsa::Signature {
type Error = ();
fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
if let MultiSignature::Ecdsa(x) = m { Ok(x) } else { Err(()) }
}
}
impl Default for MultiSignature {
fn default() -> Self {
MultiSignature::Ed25519(Default::default())
}
}
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum MultiSigner {
Ed25519(ed25519::Public),
Sr25519(sr25519::Public),
Ecdsa(ecdsa::Public),
}
impl Default for MultiSigner {
fn default() -> Self {
MultiSigner::Ed25519(Default::default())
}
}
impl<T: Into<H256>> crypto::UncheckedFrom<T> 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(),
MultiSigner::Ecdsa(ref who) => who.as_ref(),
}
}
}
impl traits::IdentifyAccount for MultiSigner {
type AccountId = AccountId32;
fn into_account(self) -> AccountId32 {
match self {
MultiSigner::Ed25519(who) => <[u8; 32]>::from(who).into(),
MultiSigner::Sr25519(who) => <[u8; 32]>::from(who).into(),
MultiSigner::Ecdsa(who) => sp_io::hashing::blake2_256(&who.as_ref()[..]).into(),
}
}
}
impl From<ed25519::Public> for MultiSigner {
fn from(x: ed25519::Public) -> Self {
MultiSigner::Ed25519(x)
}
}
impl TryFrom<MultiSigner> for ed25519::Public {
type Error = ();
fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
if let MultiSigner::Ed25519(x) = m { Ok(x) } else { Err(()) }
}
}
impl From<sr25519::Public> for MultiSigner {
fn from(x: sr25519::Public) -> Self {
MultiSigner::Sr25519(x)
}
}
impl TryFrom<MultiSigner> for sr25519::Public {
type Error = ();
fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
if let MultiSigner::Sr25519(x) = m { Ok(x) } else { Err(()) }
}
}
impl From<ecdsa::Public> for MultiSigner {
fn from(x: ecdsa::Public) -> Self {
MultiSigner::Ecdsa(x)
}
}
impl TryFrom<MultiSigner> for ecdsa::Public {
type Error = ();
fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
if let MultiSigner::Ecdsa(x) = m { Ok(x) } else { Err(()) }
}
}
#[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),
MultiSigner::Ecdsa(ref who) => write!(fmt, "ecdsa: {}", who),
}
}
}
impl Verify for MultiSignature {
type Signer = MultiSigner;
fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId32) -> bool {
match (self, signer) {
(MultiSignature::Ed25519(ref sig), who) => sig.verify(msg, &ed25519::Public::from_slice(who.as_ref())),
(MultiSignature::Sr25519(ref sig), who) => sig.verify(msg, &sr25519::Public::from_slice(who.as_ref())),
(MultiSignature::Ecdsa(ref sig), who) => {
let m = sp_io::hashing::blake2_256(msg.get());
match sp_io::crypto::secp256k1_ecdsa_recover_compressed(sig.as_ref(), &m) {
Ok(pubkey) =>
&sp_io::hashing::blake2_256(pubkey.as_ref())
== <dyn AsRef<[u8; 32]>>::as_ref(who),
_ => false,
}
}
}
}
}
#[derive(Eq, PartialEq, Clone, Default, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct AnySignature(H512);
impl Verify for AnySignature {
type Signer = sr25519::Public;
fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sr25519::Public) -> bool {
let msg = msg.get();
sr25519::Signature::try_from(self.0.as_fixed_bytes().as_ref())
.map(|s| s.verify(msg, signer))
.unwrap_or(false)
|| ed25519::Signature::try_from(self.0.as_fixed_bytes().as_ref())
.map(|s| s.verify(msg, &ed25519::Public::from_slice(signer.as_ref())))
.unwrap_or(false)
}
}
impl From<sr25519::Signature> for AnySignature {
fn from(s: sr25519::Signature) -> Self {
AnySignature(s.into())
}
}
impl From<ed25519::Signature> for AnySignature {
fn from(s: ed25519::Signature) -> Self {
AnySignature(s.into())
}
}
impl From<DispatchError> for DispatchOutcome {
fn from(err: DispatchError) -> Self {
Err(err)
}
}
pub type DispatchResult = sp_std::result::Result<(), DispatchError>;
pub type DispatchResultWithInfo<T> = sp_std::result::Result<T, DispatchErrorWithPostInfo<T>>;
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum DispatchError {
Other(#[codec(skip)] #[cfg_attr(feature = "std", serde(skip_deserializing))] &'static str),
CannotLookup,
BadOrigin,
Module {
index: u8,
error: u8,
#[codec(skip)]
#[cfg_attr(feature = "std", serde(skip_deserializing))]
message: Option<&'static str>,
},
ConsumerRemaining,
NoProviders,
}
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug)]
pub struct DispatchErrorWithPostInfo<Info> where
Info: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable
{
pub post_info: Info,
pub error: DispatchError,
}
impl DispatchError {
pub fn stripped(self) -> Self {
match self {
DispatchError::Module { index, error, message: Some(_) }
=> DispatchError::Module { index, error, message: None },
m => m,
}
}
}
impl<T, E> From<E> for DispatchErrorWithPostInfo<T> where
T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable + Default,
E: Into<DispatchError>
{
fn from(error: E) -> Self {
Self {
post_info: Default::default(),
error: error.into(),
}
}
}
impl From<crate::traits::LookupError> for DispatchError {
fn from(_: crate::traits::LookupError) -> Self {
Self::CannotLookup
}
}
impl From<crate::traits::BadOrigin> for DispatchError {
fn from(_: crate::traits::BadOrigin) -> Self {
Self::BadOrigin
}
}
impl From<crate::traits::StoredMapError> for DispatchError {
fn from(e: crate::traits::StoredMapError) -> Self {
match e {
crate::traits::StoredMapError::ConsumerRemaining => Self::ConsumerRemaining,
crate::traits::StoredMapError::NoProviders => Self::NoProviders,
}
}
}
impl From<&'static str> for DispatchError {
fn from(err: &'static str) -> DispatchError {
DispatchError::Other(err)
}
}
impl From<DispatchError> for &'static str {
fn from(err: DispatchError) -> &'static str {
match err {
DispatchError::Other(msg) => msg,
DispatchError::CannotLookup => "Cannot lookup",
DispatchError::BadOrigin => "Bad origin",
DispatchError::Module { message, .. } => message.unwrap_or("Unknown module error"),
DispatchError::ConsumerRemaining => "Consumer remaining",
DispatchError::NoProviders => "No providers",
}
}
}
impl<T> From<DispatchErrorWithPostInfo<T>> for &'static str where
T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable
{
fn from(err: DispatchErrorWithPostInfo<T>) -> &'static str {
err.error.into()
}
}
impl traits::Printable for DispatchError {
fn print(&self) {
"DispatchError".print();
match self {
Self::Other(err) => err.print(),
Self::CannotLookup => "Cannot lookup".print(),
Self::BadOrigin => "Bad origin".print(),
Self::Module { index, error, message } => {
index.print();
error.print();
if let Some(msg) = message {
msg.print();
}
}
Self::ConsumerRemaining => "Consumer remaining".print(),
Self::NoProviders => "No providers".print(),
}
}
}
impl<T> traits::Printable for DispatchErrorWithPostInfo<T> where
T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable
{
fn print(&self) {
self.error.print();
"PostInfo: ".print();
self.post_info.print();
}
}
pub type DispatchOutcome = Result<(), DispatchError>;
pub type ApplyExtrinsicResult = Result<DispatchOutcome, transaction_validity::TransactionValidityError>;
pub type ApplyExtrinsicResultWithInfo<T> =
Result<DispatchResultWithInfo<T>, transaction_validity::TransactionValidityError>;
pub fn verify_encoded_lazy<V: Verify, T: codec::Encode>(
sig: &V,
item: &T,
signer: &<V::Signer as IdentifyAccount>::AccountId
) -> bool {
struct LazyEncode<F> {
inner: F,
encoded: Option<Vec<u8>>,
}
impl<F: Fn() -> Vec<u8>> traits::Lazy<[u8]> for LazyEncode<F> {
fn get(&mut self) -> &[u8] {
self.encoded.get_or_insert_with(&self.inner).as_slice()
}
}
sig.verify(
LazyEncode { inner: || item.encode(), encoded: None },
signer,
)
}
#[macro_export]
#[cfg(feature = "std")]
macro_rules! assert_eq_error_rate {
($x:expr, $y:expr, $error:expr $(,)?) => {
assert!(
($x) >= (($y) - ($error)) && ($x) <= (($y) + ($error)),
"{:?} != {:?} (with error rate {:?})",
$x,
$y,
$error,
);
};
}
#[derive(PartialEq, Eq, Clone, Default, Encode, Decode)]
pub struct OpaqueExtrinsic(Vec<u8>);
impl OpaqueExtrinsic {
pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, codec::Error> {
OpaqueExtrinsic::decode(&mut bytes)
}
}
#[cfg(feature = "std")]
impl parity_util_mem::MallocSizeOf for OpaqueExtrinsic {
fn size_of(&self, ops: &mut parity_util_mem::MallocSizeOfOps) -> usize {
self.0.size_of(ops)
}
}
impl sp_std::fmt::Debug for OpaqueExtrinsic {
#[cfg(feature = "std")]
fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
write!(fmt, "{}", sp_core::hexdisplay::HexDisplay::from(&self.0))
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
Ok(())
}
}
#[cfg(feature = "std")]
impl ::serde::Serialize for OpaqueExtrinsic {
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
codec::Encode::using_encoded(&self.0, |bytes| ::sp_core::bytes::serialize(bytes, seq))
}
}
#[cfg(feature = "std")]
impl<'a> ::serde::Deserialize<'a> for OpaqueExtrinsic {
fn deserialize<D>(de: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'a> {
let r = ::sp_core::bytes::deserialize(de)?;
Decode::decode(&mut &r[..])
.map_err(|e| ::serde::de::Error::custom(format!("Decode error: {}", e)))
}
}
impl traits::Extrinsic for OpaqueExtrinsic {
type Call = ();
type SignaturePayload = ();
}
pub fn print(print: impl traits::Printable) {
print.print();
}
#[must_use = "`verify()` needs to be called to finish batch signature verification!"]
pub struct SignatureBatching(bool);
impl SignatureBatching {
pub fn start() -> Self {
sp_io::crypto::start_batch_verify();
SignatureBatching(false)
}
#[must_use]
pub fn verify(mut self) -> bool {
self.0 = true;
sp_io::crypto::finish_batch_verify()
}
}
impl Drop for SignatureBatching {
fn drop(&mut self) {
if !self.0 && !sp_std::thread::panicking() {
panic!("Signature verification has not been called before `SignatureBatching::drop`")
}
}
}
pub enum TransactionOutcome<R> {
Commit(R),
Rollback(R),
}
impl<R> TransactionOutcome<R> {
pub fn into_inner(self) -> R {
match self {
Self::Commit(r) => r,
Self::Rollback(r) => r,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use codec::{Encode, Decode};
use sp_core::crypto::Pair;
#[test]
fn opaque_extrinsic_serialization() {
let ex = super::OpaqueExtrinsic(vec![1, 2, 3, 4]);
assert_eq!(serde_json::to_string(&ex).unwrap(), "\"0x1001020304\"".to_owned());
}
#[test]
fn dispatch_error_encoding() {
let error = DispatchError::Module {
index: 1,
error: 2,
message: Some("error message"),
};
let encoded = error.encode();
let decoded = DispatchError::decode(&mut &encoded[..]).unwrap();
assert_eq!(encoded, vec![3, 1, 2]);
assert_eq!(
decoded,
DispatchError::Module {
index: 1,
error: 2,
message: None,
},
);
}
#[test]
fn multi_signature_ecdsa_verify_works() {
let msg = &b"test-message"[..];
let (pair, _) = ecdsa::Pair::generate();
let signature = pair.sign(&msg);
assert!(ecdsa::Pair::verify(&signature, msg, &pair.public()));
let multi_sig = MultiSignature::from(signature);
let multi_signer = MultiSigner::from(pair.public());
assert!(multi_sig.verify(msg, &multi_signer.into_account()));
let multi_signer = MultiSigner::from(pair.public());
assert!(multi_sig.verify(msg, &multi_signer.into_account()));
}
#[test]
#[should_panic(expected = "Signature verification has not been called")]
fn batching_still_finishes_when_not_called_directly() {
let mut ext = sp_state_machine::BasicExternalities::default();
ext.register_extension(
sp_core::traits::TaskExecutorExt::new(sp_core::testing::TaskExecutor::new()),
);
ext.execute_with(|| {
let _batching = SignatureBatching::start();
sp_io::crypto::sr25519_verify(
&Default::default(),
&Vec::new(),
&Default::default(),
);
});
}
#[test]
#[should_panic(expected = "Hey, I'm an error")]
fn batching_does_not_panic_while_thread_is_already_panicking() {
let mut ext = sp_state_machine::BasicExternalities::default();
ext.register_extension(
sp_core::traits::TaskExecutorExt::new(sp_core::testing::TaskExecutor::new()),
);
ext.execute_with(|| {
let _batching = SignatureBatching::start();
panic!("Hey, I'm an error");
});
}
}