#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
use codec::{Encode, Decode};
use sp_std::{collections::btree_map::{BTreeMap, IntoIter, Entry}, vec::Vec};
#[cfg(feature = "std")]
use parking_lot::RwLock;
#[cfg(feature = "std")]
use std::{sync::Arc, format};
#[cfg(feature = "std")]
#[derive(Debug, Encode, Decode, derive_more::Display)]
pub struct Error(String);
#[cfg(feature = "std")]
impl<T: Into<String>> From<T> for Error {
fn from(data: T) -> Error {
Self(data.into())
}
}
#[cfg(feature = "std")]
impl Error {
pub fn into_string(self) -> String {
self.0
}
}
#[derive(Encode, sp_core::RuntimeDebug)]
#[cfg(not(feature = "std"))]
pub struct Error(&'static str);
#[cfg(not(feature = "std"))]
impl From<&'static str> for Error {
fn from(data: &'static str) -> Error {
Self(data)
}
}
pub type InherentIdentifier = [u8; 8];
#[derive(Clone, Default, Encode, Decode)]
pub struct InherentData {
data: BTreeMap<InherentIdentifier, Vec<u8>>
}
impl InherentData {
pub fn new() -> Self {
Self::default()
}
pub fn put_data<I: codec::Encode>(
&mut self,
identifier: InherentIdentifier,
inherent: &I,
) -> Result<(), Error> {
match self.data.entry(identifier) {
Entry::Vacant(entry) => {
entry.insert(inherent.encode());
Ok(())
},
Entry::Occupied(_) => {
Err("Inherent with same identifier already exists!".into())
}
}
}
pub fn replace_data<I: codec::Encode>(
&mut self,
identifier: InherentIdentifier,
inherent: &I,
) {
self.data.insert(identifier, inherent.encode());
}
pub fn get_data<I: codec::Decode>(
&self,
identifier: &InherentIdentifier,
) -> Result<Option<I>, Error> {
match self.data.get(identifier) {
Some(inherent) =>
I::decode(&mut &inherent[..])
.map_err(|_| {
"Could not decode requested inherent type!".into()
})
.map(Some),
None => Ok(None)
}
}
pub fn len(&self) -> usize {
self.data.len()
}
}
#[derive(Encode, Decode, Clone)]
pub struct CheckInherentsResult {
okay: bool,
fatal_error: bool,
errors: InherentData,
}
impl Default for CheckInherentsResult {
fn default() -> Self {
Self {
okay: true,
errors: InherentData::new(),
fatal_error: false,
}
}
}
impl CheckInherentsResult {
pub fn new() -> Self {
Self::default()
}
pub fn put_error<E: codec::Encode + IsFatalError>(
&mut self,
identifier: InherentIdentifier,
error: &E,
) -> Result<(), Error> {
if self.fatal_error {
return Err("No other errors are accepted after an hard error!".into())
}
if error.is_fatal_error() {
self.errors.data.clear();
}
self.errors.put_data(identifier, error)?;
self.okay = false;
self.fatal_error = error.is_fatal_error();
Ok(())
}
pub fn get_error<E: codec::Decode>(
&self,
identifier: &InherentIdentifier,
) -> Result<Option<E>, Error> {
self.errors.get_data(identifier)
}
pub fn into_errors(self) -> IntoIter<InherentIdentifier, Vec<u8>> {
self.errors.data.into_iter()
}
pub fn ok(&self) -> bool {
self.okay
}
pub fn fatal_error(&self) -> bool {
self.fatal_error
}
}
#[cfg(feature = "std")]
impl PartialEq for CheckInherentsResult {
fn eq(&self, other: &Self) -> bool {
self.fatal_error == other.fatal_error &&
self.okay == other.okay &&
self.errors.data == other.errors.data
}
}
#[cfg(feature = "std")]
#[derive(Clone, Default)]
pub struct InherentDataProviders {
providers: Arc<RwLock<Vec<Box<dyn ProvideInherentData + Send + Sync>>>>,
}
#[cfg(feature = "std")]
impl InherentDataProviders {
pub fn new() -> Self {
Self::default()
}
pub fn register_provider<P: ProvideInherentData + Send + Sync +'static>(
&self,
provider: P,
) -> Result<(), Error> {
if self.has_provider(&provider.inherent_identifier()) {
Err(
format!(
"Inherent data provider with identifier {:?} already exists!",
&provider.inherent_identifier()
).into()
)
} else {
provider.on_register(self)?;
self.providers.write().push(Box::new(provider));
Ok(())
}
}
pub fn has_provider(&self, identifier: &InherentIdentifier) -> bool {
self.providers.read().iter().any(|p| p.inherent_identifier() == identifier)
}
pub fn create_inherent_data(&self) -> Result<InherentData, Error> {
let mut data = InherentData::new();
self.providers.read().iter().try_for_each(|p| {
p.provide_inherent_data(&mut data)
.map_err(|e| format!("Error for `{:?}`: {:?}", p.inherent_identifier(), e))
})?;
Ok(data)
}
pub fn error_to_string(&self, identifier: &InherentIdentifier, error: &[u8]) -> String {
let res = self.providers.read().iter().filter_map(|p|
if p.inherent_identifier() == identifier {
Some(
p.error_to_string(error)
.unwrap_or_else(|| error_to_string_fallback(identifier))
)
} else {
None
}
).next();
match res {
Some(res) => res,
None => format!(
"Error while checking inherent of type \"{}\", but this inherent type is unknown.",
String::from_utf8_lossy(identifier)
)
}
}
}
#[cfg(feature = "std")]
pub trait ProvideInherentData {
fn on_register(&self, _: &InherentDataProviders) -> Result<(), Error> {
Ok(())
}
fn inherent_identifier(&self) -> &'static InherentIdentifier;
fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), Error>;
fn error_to_string(&self, error: &[u8]) -> Option<String>;
}
#[cfg(feature = "std")]
fn error_to_string_fallback(identifier: &InherentIdentifier) -> String {
format!(
"Error while checking inherent of type \"{}\", but error could not be decoded.",
String::from_utf8_lossy(identifier)
)
}
pub trait IsFatalError {
fn is_fatal_error(&self) -> bool;
}
#[derive(Encode)]
pub struct MakeFatalError<E: codec::Encode>(E);
impl<E: codec::Encode> From<E> for MakeFatalError<E> {
fn from(err: E) -> Self {
MakeFatalError(err)
}
}
impl<E: codec::Encode> IsFatalError for MakeFatalError<E> {
fn is_fatal_error(&self) -> bool {
true
}
}
pub trait ProvideInherent {
type Call;
type Error: codec::Encode + IsFatalError;
const INHERENT_IDENTIFIER: self::InherentIdentifier;
fn create_inherent(data: &InherentData) -> Option<Self::Call>;
fn is_inherent_required(_: &InherentData) -> Result<Option<Self::Error>, Self::Error> { Ok(None) }
fn check_inherent(_: &Self::Call, _: &InherentData) -> Result<(), Self::Error> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use codec::{Encode, Decode};
const TEST_INHERENT_0: InherentIdentifier = *b"testinh0";
const TEST_INHERENT_1: InherentIdentifier = *b"testinh1";
#[derive(Encode)]
struct NoFatalError<E: codec::Encode>(E);
impl<E: codec::Encode> IsFatalError for NoFatalError<E> {
fn is_fatal_error(&self) -> bool {
false
}
}
#[test]
fn inherent_data_encodes_and_decodes() {
let inherent_0 = vec![1, 2, 3];
let inherent_1: u32 = 7;
let mut data = InherentData::new();
data.put_data(TEST_INHERENT_0, &inherent_0).unwrap();
data.put_data(TEST_INHERENT_1, &inherent_1).unwrap();
let encoded = data.encode();
let decoded = InherentData::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded.get_data::<Vec<u32>>(&TEST_INHERENT_0).unwrap().unwrap(), inherent_0);
assert_eq!(decoded.get_data::<u32>(&TEST_INHERENT_1).unwrap().unwrap(), inherent_1);
}
#[test]
fn adding_same_inherent_returns_an_error() {
let mut data = InherentData::new();
data.put_data(TEST_INHERENT_0, &8).unwrap();
assert!(data.put_data(TEST_INHERENT_0, &10).is_err());
}
#[derive(Clone)]
struct TestInherentDataProvider {
registered: Arc<RwLock<bool>>,
}
impl TestInherentDataProvider {
fn new() -> Self {
let inst = Self {
registered: Default::default(),
};
assert!(!inst.is_registered());
inst
}
fn is_registered(&self) -> bool {
*self.registered.read()
}
}
const ERROR_TO_STRING: &str = "Found error!";
impl ProvideInherentData for TestInherentDataProvider {
fn on_register(&self, _: &InherentDataProviders) -> Result<(), Error> {
*self.registered.write() = true;
Ok(())
}
fn inherent_identifier(&self) -> &'static InherentIdentifier {
&TEST_INHERENT_0
}
fn provide_inherent_data(&self, data: &mut InherentData) -> Result<(), Error> {
data.put_data(TEST_INHERENT_0, &42)
}
fn error_to_string(&self, _: &[u8]) -> Option<String> {
Some(ERROR_TO_STRING.into())
}
}
#[test]
fn registering_inherent_provider() {
let provider = TestInherentDataProvider::new();
let providers = InherentDataProviders::new();
providers.register_provider(provider.clone()).unwrap();
assert!(provider.is_registered());
assert!(providers.has_provider(provider.inherent_identifier()));
assert!(providers.register_provider(provider.clone()).is_err());
}
#[test]
fn create_inherent_data_from_all_providers() {
let provider = TestInherentDataProvider::new();
let providers = InherentDataProviders::new();
providers.register_provider(provider.clone()).unwrap();
assert!(provider.is_registered());
let inherent_data = providers.create_inherent_data().unwrap();
assert_eq!(
inherent_data.get_data::<u32>(provider.inherent_identifier()).unwrap().unwrap(),
42u32
);
}
#[test]
fn encoded_error_to_string() {
let provider = TestInherentDataProvider::new();
let providers = InherentDataProviders::new();
providers.register_provider(provider.clone()).unwrap();
assert!(provider.is_registered());
assert_eq!(
&providers.error_to_string(&TEST_INHERENT_0, &[1, 2]), ERROR_TO_STRING
);
assert!(
providers
.error_to_string(&TEST_INHERENT_1, &[1, 2])
.contains("inherent type is unknown")
);
}
#[test]
fn check_inherents_result_encodes_and_decodes() {
let mut result = CheckInherentsResult::new();
assert!(result.ok());
result.put_error(TEST_INHERENT_0, &NoFatalError(2u32)).unwrap();
assert!(!result.ok());
assert!(!result.fatal_error());
let encoded = result.encode();
let decoded = CheckInherentsResult::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded.get_error::<u32>(&TEST_INHERENT_0).unwrap().unwrap(), 2);
assert!(!decoded.ok());
assert!(!decoded.fatal_error());
}
#[test]
fn check_inherents_result_removes_other_errors_on_fatal_error() {
let mut result = CheckInherentsResult::new();
assert!(result.ok());
result.put_error(TEST_INHERENT_0, &NoFatalError(2u32)).unwrap();
assert!(!result.ok());
assert!(!result.fatal_error());
result.put_error(TEST_INHERENT_1, &MakeFatalError(4u32)).unwrap();
assert!(!result.ok());
assert!(result.fatal_error());
assert!(result.put_error(TEST_INHERENT_0, &NoFatalError(5u32)).is_err());
result.into_errors().for_each(|(i, e)| match i {
TEST_INHERENT_1 => assert_eq!(u32::decode(&mut &e[..]).unwrap(), 4),
_ => panic!("There should be no other error!"),
});
}
}