#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use std::collections::HashSet;
#[cfg(feature = "std")]
use std::fmt;
#[doc(hidden)]
pub use alloc::borrow::Cow;
use codec::{Decode, Encode, Input};
use scale_info::TypeInfo;
use sp_runtime::RuntimeString;
pub use sp_runtime::{create_runtime_str, StateVersion};
#[doc(hidden)]
pub use sp_std;
#[cfg(feature = "std")]
use sp_runtime::traits::Block as BlockT;
#[cfg(feature = "std")]
pub mod embed;
pub use sp_version_proc_macro::runtime_version;
pub type ApiId = [u8; 8];
pub type ApisVec = alloc::borrow::Cow<'static, [(ApiId, u32)]>;
#[macro_export]
macro_rules! create_apis_vec {
( $y:expr ) => {
$crate::Cow::Borrowed(&$y)
};
}
#[derive(Clone, PartialEq, Eq, Encode, Default, sp_runtime::RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct RuntimeVersion {
pub spec_name: RuntimeString,
pub impl_name: RuntimeString,
pub authoring_version: u32,
pub spec_version: u32,
pub impl_version: u32,
#[cfg_attr(
feature = "serde",
serde(
serialize_with = "apis_serialize::serialize",
deserialize_with = "apis_serialize::deserialize",
)
)]
pub apis: ApisVec,
pub transaction_version: u32,
pub state_version: u8,
}
impl RuntimeVersion {
pub fn decode_with_version_hint<I: Input>(
input: &mut I,
core_version: Option<u32>,
) -> Result<RuntimeVersion, codec::Error> {
let spec_name = Decode::decode(input)?;
let impl_name = Decode::decode(input)?;
let authoring_version = Decode::decode(input)?;
let spec_version = Decode::decode(input)?;
let impl_version = Decode::decode(input)?;
let apis = Decode::decode(input)?;
let core_version =
if core_version.is_some() { core_version } else { core_version_from_apis(&apis) };
let transaction_version =
if core_version.map(|v| v >= 3).unwrap_or(false) { Decode::decode(input)? } else { 1 };
let state_version =
if core_version.map(|v| v >= 4).unwrap_or(false) { Decode::decode(input)? } else { 0 };
Ok(RuntimeVersion {
spec_name,
impl_name,
authoring_version,
spec_version,
impl_version,
apis,
transaction_version,
state_version,
})
}
}
impl Decode for RuntimeVersion {
fn decode<I: Input>(input: &mut I) -> Result<Self, codec::Error> {
Self::decode_with_version_hint(input, None)
}
}
#[cfg(feature = "std")]
impl fmt::Display for RuntimeVersion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}-{} ({}-{}.tx{}.au{})",
self.spec_name,
self.spec_version,
self.impl_name,
self.impl_version,
self.transaction_version,
self.authoring_version,
)
}
}
#[cfg(feature = "std")]
fn has_api_with<P: Fn(u32) -> bool>(apis: &ApisVec, id: &ApiId, predicate: P) -> bool {
apis.iter().any(|(s, v)| s == id && predicate(*v))
}
pub fn core_version_from_apis(apis: &ApisVec) -> Option<u32> {
let id = sp_crypto_hashing_proc_macro::blake2b_64!(b"Core");
apis.iter().find(|(s, _v)| s == &id).map(|(_s, v)| *v)
}
#[cfg(feature = "std")]
impl RuntimeVersion {
pub fn can_call_with(&self, other: &RuntimeVersion) -> bool {
self.spec_version == other.spec_version &&
self.spec_name == other.spec_name &&
self.authoring_version == other.authoring_version
}
pub fn has_api_with<P: Fn(u32) -> bool>(&self, id: &ApiId, predicate: P) -> bool {
has_api_with(&self.apis, id, predicate)
}
pub fn api_version(&self, id: &ApiId) -> Option<u32> {
self.apis.iter().find_map(|a| (a.0 == *id).then(|| a.1))
}
}
impl RuntimeVersion {
pub fn state_version(&self) -> StateVersion {
self.state_version.try_into().unwrap_or(StateVersion::V1)
}
}
#[derive(Debug)]
#[cfg(feature = "std")]
pub struct NativeVersion {
pub runtime_version: RuntimeVersion,
pub can_author_with: HashSet<u32>,
}
#[cfg(feature = "std")]
impl NativeVersion {
pub fn can_author_with(&self, other: &RuntimeVersion) -> Result<(), String> {
if self.runtime_version.spec_name != other.spec_name {
Err(format!(
"`spec_name` does not match `{}` vs `{}`",
self.runtime_version.spec_name, other.spec_name,
))
} else if self.runtime_version.authoring_version != other.authoring_version &&
!self.can_author_with.contains(&other.authoring_version)
{
Err(format!(
"`authoring_version` does not match `{version}` vs `{other_version}` and \
`can_author_with` not contains `{other_version}`",
version = self.runtime_version.authoring_version,
other_version = other.authoring_version,
))
} else {
Ok(())
}
}
}
#[cfg(feature = "std")]
pub trait GetNativeVersion {
fn native_version(&self) -> &NativeVersion;
}
#[cfg(feature = "std")]
pub trait GetRuntimeVersionAt<Block: BlockT> {
fn runtime_version(&self, at: <Block as BlockT>::Hash) -> Result<RuntimeVersion, String>;
}
#[cfg(feature = "std")]
impl<T: GetRuntimeVersionAt<Block>, Block: BlockT> GetRuntimeVersionAt<Block>
for std::sync::Arc<T>
{
fn runtime_version(&self, at: <Block as BlockT>::Hash) -> Result<RuntimeVersion, String> {
(&**self).runtime_version(at)
}
}
#[cfg(feature = "std")]
impl<T: GetNativeVersion> GetNativeVersion for std::sync::Arc<T> {
fn native_version(&self) -> &NativeVersion {
(&**self).native_version()
}
}
#[cfg(feature = "serde")]
mod apis_serialize {
use super::*;
use alloc::vec::Vec;
use impl_serde::serialize as bytes;
use serde::{de, ser::SerializeTuple, Serializer};
#[derive(Serialize)]
struct ApiId<'a>(#[serde(serialize_with = "serialize_bytesref")] &'a super::ApiId, &'a u32);
pub fn serialize<S>(apis: &ApisVec, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let len = apis.len();
let mut seq = ser.serialize_tuple(len)?;
for (api, ver) in &**apis {
seq.serialize_element(&ApiId(api, ver))?;
}
seq.end()
}
pub fn serialize_bytesref<S>(&apis: &&super::ApiId, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
bytes::serialize(apis, ser)
}
#[derive(Deserialize)]
struct ApiIdOwned(#[serde(deserialize_with = "deserialize_bytes")] super::ApiId, u32);
pub fn deserialize<'de, D>(deserializer: D) -> Result<ApisVec, D::Error>
where
D: de::Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = ApisVec;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str("a sequence of api id and version tuples")
}
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
V: de::SeqAccess<'de>,
{
let mut apis = Vec::new();
while let Some(value) = visitor.next_element::<ApiIdOwned>()? {
apis.push((value.0, value.1));
}
Ok(apis.into())
}
}
deserializer.deserialize_seq(Visitor)
}
pub fn deserialize_bytes<'de, D>(d: D) -> Result<super::ApiId, D::Error>
where
D: de::Deserializer<'de>,
{
let mut arr = [0; 8];
bytes::deserialize_check_len(d, bytes::ExpectedLen::Exact(&mut arr[..]))?;
Ok(arr)
}
}