sp_version/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Substrate runtime version
19//!
20//! Each runtime that should be executed by a Substrate based node needs to have a runtime version.
21//! The runtime version is defined by [`RuntimeVersion`]. The runtime version is used to
22//! distinguish different runtimes. The most important field is the
23//! [`spec_version`](RuntimeVersion::spec_version). The `spec_version` should be increased in a
24//! runtime when a new runtime build includes breaking changes that would make other runtimes unable
25//! to import blocks built by this runtime or vice-versa, where the new runtime could not import
26//! blocks built by the old runtime. The runtime version also carries other version information
27//! about the runtime, see [`RuntimeVersion`] for more information on this.
28//!
29//! Substrate will fetch the runtime version from a `wasm` blob by first checking the
30//! `runtime_version` link section or calling the `Core::version` runtime api. The link section can
31//! be generated in the runtime using the [`runtime_version`] attribute. The `Core` runtime api also
32//! needs to be implemented for the runtime using `impl_runtime_apis!`.
33
34#![cfg_attr(not(feature = "std"), no_std)]
35
36extern crate alloc;
37
38#[cfg(any(feature = "std", feature = "serde"))]
39use alloc::fmt;
40#[cfg(feature = "serde")]
41use serde::{Deserialize, Serialize};
42#[cfg(feature = "std")]
43use std::collections::HashSet;
44
45#[doc(hidden)]
46pub use alloc::borrow::Cow;
47use codec::{Decode, Encode, Input};
48use scale_info::TypeInfo;
49#[allow(deprecated)]
50pub use sp_runtime::{create_runtime_str, StateVersion};
51#[doc(hidden)]
52pub use sp_std;
53
54#[cfg(feature = "std")]
55use sp_runtime::traits::Block as BlockT;
56
57#[cfg(feature = "std")]
58pub mod embed;
59
60/// An attribute that accepts a version declaration of a runtime and generates a custom wasm
61/// section with the equivalent contents.
62///
63/// The custom section allows to read the version of the runtime without having to execute any
64/// code. Instead, the generated custom section can be relatively easily parsed from the wasm
65/// binary. The identifier of the custom section is "runtime_version".
66///
67/// A shortcoming of this macro is that it is unable to embed information regarding supported
68/// APIs. This is supported by the `construct_runtime!` macro.
69///
70/// # Usage
71///
72/// This macro accepts a const item like the following:
73///
74/// ```rust
75/// extern crate alloc;
76///
77/// use alloc::borrow::Cow;
78/// use sp_version::RuntimeVersion;
79///
80/// #[sp_version::runtime_version]
81/// pub const VERSION: RuntimeVersion = RuntimeVersion {
82/// 	spec_name: Cow::Borrowed("test"),
83/// 	impl_name: Cow::Borrowed("test"),
84/// 	authoring_version: 10,
85/// 	spec_version: 265,
86/// 	impl_version: 1,
87/// 	apis: RUNTIME_API_VERSIONS,
88/// 	transaction_version: 2,
89/// 	system_version: 1,
90/// };
91///
92/// # const RUNTIME_API_VERSIONS: sp_version::ApisVec = sp_version::create_apis_vec!([]);
93/// ```
94///
95/// It will pass it through and add code required for emitting a custom section. The
96/// information that will go into the custom section is parsed from the item declaration. Due
97/// to that, the macro is somewhat rigid in terms of the code it accepts. There are the
98/// following considerations:
99///
100/// - The `spec_name` and `impl_name` must be set by a macro-like expression. The name of the
101///   macro doesn't matter though.
102///
103/// - `authoring_version`, `spec_version`, `impl_version` and `transaction_version` must be set
104///   by a literal. Literal must be an integer. No other expressions are allowed there. In
105///   particular, you can't supply a constant variable.
106///
107/// - `apis` doesn't have any specific constraints. This is because this information doesn't
108///   get into the custom section and is not parsed.
109///
110/// # Compilation Target & "std" feature
111///
112/// This macro assumes it will be used within a runtime. By convention, a runtime crate defines
113/// a feature named "std". This feature is enabled when the runtime is compiled to native code
114/// and disabled when it is compiled to the wasm code.
115///
116/// The custom section can only be emitted while compiling to wasm. In order to detect the
117/// compilation target we use the "std" feature. This macro will emit the custom section only
118/// if the "std" feature is **not** enabled.
119///
120/// Including this macro in the context where there is no "std" feature and the code is not
121/// compiled to wasm can lead to cryptic linking errors.
122pub use sp_version_proc_macro::runtime_version;
123
124/// The identity of a particular API interface that the runtime might provide.
125///
126/// The id is generated by hashing the name of the runtime api with BLAKE2 using a hash size
127/// of 8 bytes.
128///
129/// The name of the runtime api is the name of the trait when using `decl_runtime_apis!` macro. So,
130/// in the following runtime api declaration:
131///
132/// ```nocompile
133/// decl_runtime_apis! {
134///     trait TestApi {
135///         fn do_test();
136///     }
137/// }
138/// ```
139///
140/// The name of the trait would be `TestApi` and would be taken as input to the BLAKE2 hash
141/// function.
142///
143/// As Rust supports renaming of traits, the name of a runtime api given to `impl_runtime_apis!`
144/// doesn't need to be the same as in `decl_runtime_apis!`, but only the name in
145/// `decl_runtime_apis!` is the important one!
146pub type ApiId = [u8; 8];
147
148/// A vector of pairs of `ApiId` and a `u32` for version.
149pub type ApisVec = alloc::borrow::Cow<'static, [(ApiId, u32)]>;
150
151/// Create a vector of Api declarations.
152#[macro_export]
153macro_rules! create_apis_vec {
154	( $y:expr ) => {
155		$crate::Cow::Borrowed(&$y)
156	};
157}
158
159/// Runtime version.
160/// This should not be thought of as classic Semver (major/minor/tiny).
161/// This triplet have different semantics and mis-interpretation could cause problems.
162/// In particular: bug fixes should result in an increment of `spec_version` and possibly
163/// `authoring_version`, absolutely not `impl_version` since they change the semantics of the
164/// runtime.
165#[derive(Clone, PartialEq, Eq, Encode, Default, sp_runtime::RuntimeDebug, TypeInfo)]
166pub struct RuntimeVersion {
167	/// Identifies the different Substrate runtimes. There'll be at least polkadot and node.
168	/// A different on-chain spec_name to that of the native runtime would normally result
169	/// in node not attempting to sync or author blocks.
170	pub spec_name: Cow<'static, str>,
171
172	/// Name of the implementation of the spec. This is of little consequence for the node
173	/// and serves only to differentiate code of different implementation teams. For this
174	/// codebase, it will be parity-polkadot. If there were a non-Rust implementation of the
175	/// Polkadot runtime (e.g. C++), then it would identify itself with an accordingly different
176	/// `impl_name`.
177	pub impl_name: Cow<'static, str>,
178
179	/// `authoring_version` is the version of the authorship interface. An authoring node
180	/// will not attempt to author blocks unless this is equal to its native runtime.
181	pub authoring_version: u32,
182
183	/// Version of the runtime specification.
184	///
185	/// A full-node will not attempt to use its native runtime in substitute for the on-chain
186	/// Wasm runtime unless all of `spec_name`, `spec_version` and `authoring_version` are the same
187	/// between Wasm and native.
188	///
189	/// This number should never decrease.
190	pub spec_version: u32,
191
192	/// Version of the implementation of the specification.
193	///
194	/// Nodes are free to ignore this; it serves only as an indication that the code is different;
195	/// as long as the other two versions are the same then while the actual code may be different,
196	/// it is nonetheless required to do the same thing. Non-consensus-breaking optimizations are
197	/// about the only changes that could be made which would result in only the `impl_version`
198	/// changing.
199	///
200	/// This number can be reverted to `0` after a [`spec_version`](Self::spec_version) bump.
201	pub impl_version: u32,
202
203	/// List of supported API "features" along with their versions.
204	pub apis: ApisVec,
205
206	/// All existing calls (dispatchables) are fully compatible when this number doesn't change. If
207	/// this number changes, then [`spec_version`](Self::spec_version) must change, also.
208	///
209	/// This number must change when an existing call (pallet index, call index) is changed,
210	/// either through an alteration in its user-level semantics, a parameter
211	/// added/removed, a parameter type changed, or a call/pallet changing its index. An alteration
212	/// of the user level semantics is for example when the call was before `transfer` and now is
213	/// `transfer_all`, the semantics of the call changed completely.
214	///
215	/// Removing a pallet or a call doesn't require a *bump* as long as no pallet or call is put at
216	/// the same index. Removing doesn't require a bump as the chain will reject a transaction
217	/// referencing this removed call/pallet while decoding and thus, the user isn't at risk to
218	/// execute any unknown call. FRAME runtime devs have control over the index of a call/pallet
219	/// to prevent that an index gets reused.
220	///
221	/// Adding a new pallet or call also doesn't require a *bump* as long as they also don't reuse
222	/// any previously used index.
223	///
224	/// This number should never decrease.
225	pub transaction_version: u32,
226
227	/// Version of the system implementation used by this runtime.
228	/// Use of an incorrect version is consensus breaking.
229	pub system_version: u8,
230}
231
232// Manual implementation in order to sprinkle `stateVersion` at the end for migration purposes
233// after the field was renamed from `state_version` to `system_version`
234#[cfg(feature = "serde")]
235impl serde::Serialize for RuntimeVersion {
236	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
237	where
238		S: serde::Serializer,
239	{
240		use serde::ser::SerializeStruct;
241
242		let mut state = serializer.serialize_struct("RuntimeVersion", 9)?;
243		state.serialize_field("specName", &self.spec_name)?;
244		state.serialize_field("implName", &self.impl_name)?;
245		state.serialize_field("authoringVersion", &self.authoring_version)?;
246		state.serialize_field("specVersion", &self.spec_version)?;
247		state.serialize_field("implVersion", &self.impl_version)?;
248		state.serialize_field("apis", {
249			struct SerializeWith<'a>(&'a ApisVec);
250
251			impl<'a> serde::Serialize for SerializeWith<'a> {
252				fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
253				where
254					S: serde::Serializer,
255				{
256					apis_serialize::serialize(self.0, serializer)
257				}
258			}
259
260			&SerializeWith(&self.apis)
261		})?;
262		state.serialize_field("transactionVersion", &self.transaction_version)?;
263		state.serialize_field("systemVersion", &self.system_version)?;
264		state.serialize_field("stateVersion", &self.system_version)?;
265		state.end()
266	}
267}
268
269// Manual implementation in order to allow both old `stateVersion` and new `systemVersion` to be
270// present at the same time
271#[cfg(feature = "serde")]
272impl<'de> serde::Deserialize<'de> for RuntimeVersion {
273	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
274	where
275		D: serde::Deserializer<'de>,
276	{
277		use core::marker::PhantomData;
278
279		enum Field {
280			SpecName,
281			ImplName,
282			AuthoringVersion,
283			SpecVersion,
284			ImplVersion,
285			Apis,
286			TransactionVersion,
287			SystemVersion,
288			Ignore,
289		}
290
291		struct FieldVisitor;
292
293		impl<'de> serde::de::Visitor<'de> for FieldVisitor {
294			type Value = Field;
295
296			fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
297				formatter.write_str("field identifier")
298			}
299
300			fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
301			where
302				E: serde::de::Error,
303			{
304				match value {
305					0 => Ok(Field::SpecName),
306					1 => Ok(Field::ImplName),
307					2 => Ok(Field::AuthoringVersion),
308					3 => Ok(Field::SpecVersion),
309					4 => Ok(Field::ImplVersion),
310					5 => Ok(Field::Apis),
311					6 => Ok(Field::TransactionVersion),
312					7 => Ok(Field::SystemVersion),
313					_ => Ok(Field::Ignore),
314				}
315			}
316
317			fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
318			where
319				E: serde::de::Error,
320			{
321				match value {
322					"specName" => Ok(Field::SpecName),
323					"implName" => Ok(Field::ImplName),
324					"authoringVersion" => Ok(Field::AuthoringVersion),
325					"specVersion" => Ok(Field::SpecVersion),
326					"implVersion" => Ok(Field::ImplVersion),
327					"apis" => Ok(Field::Apis),
328					"transactionVersion" => Ok(Field::TransactionVersion),
329					"systemVersion" | "stateVersion" => Ok(Field::SystemVersion),
330					_ => Ok(Field::Ignore),
331				}
332			}
333
334			fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
335			where
336				E: serde::de::Error,
337			{
338				match value {
339					b"specName" => Ok(Field::SpecName),
340					b"implName" => Ok(Field::ImplName),
341					b"authoringVersion" => Ok(Field::AuthoringVersion),
342					b"specVersion" => Ok(Field::SpecVersion),
343					b"implVersion" => Ok(Field::ImplVersion),
344					b"apis" => Ok(Field::Apis),
345					b"transactionVersion" => Ok(Field::TransactionVersion),
346					b"systemVersion" | b"stateVersion" => Ok(Field::SystemVersion),
347					_ => Ok(Field::Ignore),
348				}
349			}
350		}
351
352		impl<'de> serde::Deserialize<'de> for Field {
353			#[inline]
354			fn deserialize<E>(deserializer: E) -> Result<Self, E::Error>
355			where
356				E: serde::Deserializer<'de>,
357			{
358				deserializer.deserialize_identifier(FieldVisitor)
359			}
360		}
361
362		struct Visitor<'de> {
363			lifetime: PhantomData<&'de ()>,
364		}
365		impl<'de> serde::de::Visitor<'de> for Visitor<'de> {
366			type Value = RuntimeVersion;
367
368			fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
369				formatter.write_str("struct RuntimeVersion")
370			}
371
372			#[inline]
373			fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
374			where
375				A: serde::de::SeqAccess<'de>,
376			{
377				let spec_name = match seq.next_element()? {
378					Some(spec_name) => spec_name,
379					None =>
380						return Err(serde::de::Error::invalid_length(
381							0usize,
382							&"struct RuntimeVersion with 8 elements",
383						)),
384				};
385				let impl_name = match seq.next_element()? {
386					Some(impl_name) => impl_name,
387					None =>
388						return Err(serde::de::Error::invalid_length(
389							1usize,
390							&"struct RuntimeVersion with 8 elements",
391						)),
392				};
393				let authoring_version = match seq.next_element()? {
394					Some(authoring_version) => authoring_version,
395					None =>
396						return Err(serde::de::Error::invalid_length(
397							2usize,
398							&"struct RuntimeVersion with 8 elements",
399						)),
400				};
401				let spec_version = match seq.next_element()? {
402					Some(spec_version) => spec_version,
403					None =>
404						return Err(serde::de::Error::invalid_length(
405							3usize,
406							&"struct RuntimeVersion with 8 elements",
407						)),
408				};
409				let impl_version = match seq.next_element()? {
410					Some(impl_version) => impl_version,
411					None =>
412						return Err(serde::de::Error::invalid_length(
413							4usize,
414							&"struct RuntimeVersion with 8 elements",
415						)),
416				};
417				let apis = match {
418					struct DeserializeWith<'de> {
419						value: ApisVec,
420
421						phantom: PhantomData<RuntimeVersion>,
422						lifetime: PhantomData<&'de ()>,
423					}
424					impl<'de> serde::Deserialize<'de> for DeserializeWith<'de> {
425						fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
426						where
427							D: serde::Deserializer<'de>,
428						{
429							Ok(DeserializeWith {
430								value: apis_serialize::deserialize(deserializer)?,
431								phantom: PhantomData,
432								lifetime: PhantomData,
433							})
434						}
435					}
436					seq.next_element::<DeserializeWith<'de>>()?.map(|wrap| wrap.value)
437				} {
438					Some(apis) => apis,
439					None =>
440						return Err(serde::de::Error::invalid_length(
441							5usize,
442							&"struct RuntimeVersion with 8 elements",
443						)),
444				};
445				let transaction_version = match seq.next_element()? {
446					Some(transaction_version) => transaction_version,
447					None =>
448						return Err(serde::de::Error::invalid_length(
449							6usize,
450							&"struct RuntimeVersion with 8 elements",
451						)),
452				};
453				let system_version = match seq.next_element()? {
454					Some(system_version) => system_version,
455					None =>
456						return Err(serde::de::Error::invalid_length(
457							7usize,
458							&"struct RuntimeVersion with 8 elements",
459						)),
460				};
461				Ok(RuntimeVersion {
462					spec_name,
463					impl_name,
464					authoring_version,
465					spec_version,
466					impl_version,
467					apis,
468					transaction_version,
469					system_version,
470				})
471			}
472
473			#[inline]
474			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
475			where
476				A: serde::de::MapAccess<'de>,
477			{
478				let mut spec_name: Option<Cow<'static, str>> = None;
479				let mut impl_name: Option<Cow<'static, str>> = None;
480				let mut authoring_version: Option<u32> = None;
481				let mut spec_version: Option<u32> = None;
482				let mut impl_version: Option<u32> = None;
483				let mut apis: Option<ApisVec> = None;
484				let mut transaction_version: Option<u32> = None;
485				let mut system_version: Option<u8> = None;
486
487				while let Some(key) = map.next_key()? {
488					match key {
489						Field::SpecName => {
490							if spec_name.is_some() {
491								return Err(<A::Error as serde::de::Error>::duplicate_field(
492									"specName",
493								));
494							}
495							spec_name = Some(map.next_value()?);
496						},
497						Field::ImplName => {
498							if impl_name.is_some() {
499								return Err(<A::Error as serde::de::Error>::duplicate_field(
500									"implName",
501								));
502							}
503							impl_name = Some(map.next_value()?);
504						},
505						Field::AuthoringVersion => {
506							if authoring_version.is_some() {
507								return Err(<A::Error as serde::de::Error>::duplicate_field(
508									"authoringVersion",
509								));
510							}
511							authoring_version = Some(map.next_value()?);
512						},
513						Field::SpecVersion => {
514							if spec_version.is_some() {
515								return Err(<A::Error as serde::de::Error>::duplicate_field(
516									"specVersion",
517								));
518							}
519							spec_version = Some(map.next_value()?);
520						},
521						Field::ImplVersion => {
522							if impl_version.is_some() {
523								return Err(<A::Error as serde::de::Error>::duplicate_field(
524									"implVersion",
525								));
526							}
527							impl_version = Some(map.next_value()?);
528						},
529						Field::Apis => {
530							if apis.is_some() {
531								return Err(<A::Error as serde::de::Error>::duplicate_field("apis"));
532							}
533							apis = Some({
534								struct DeserializeWith<'de> {
535									value: ApisVec,
536									lifetime: PhantomData<&'de ()>,
537								}
538								impl<'de> serde::Deserialize<'de> for DeserializeWith<'de> {
539									fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
540									where
541										D: serde::Deserializer<'de>,
542									{
543										Ok(DeserializeWith {
544											value: apis_serialize::deserialize(deserializer)?,
545											lifetime: PhantomData,
546										})
547									}
548								}
549
550								map.next_value::<DeserializeWith<'de>>()?.value
551							});
552						},
553						Field::TransactionVersion => {
554							if transaction_version.is_some() {
555								return Err(<A::Error as serde::de::Error>::duplicate_field(
556									"transactionVersion",
557								));
558							}
559							transaction_version = Some(map.next_value()?);
560						},
561						Field::SystemVersion =>
562							if let Some(system_version) = system_version {
563								let new_value = map.next_value::<u8>()?;
564								if system_version != new_value {
565									return Err(<A::Error as serde::de::Error>::custom(
566										alloc::format!(
567											r#"Duplicated "stateVersion" and "systemVersion" \
568											fields must have the same value, but different values \
569											were provided: {system_version} vs {new_value}"#
570										),
571									));
572								}
573							} else {
574								system_version = Some(map.next_value()?);
575							},
576						_ => {
577							let _ = map.next_value::<serde::de::IgnoredAny>()?;
578						},
579					}
580				}
581				let spec_name = spec_name
582					.ok_or_else(|| <A::Error as serde::de::Error>::missing_field("specName"))?;
583				let impl_name = impl_name
584					.ok_or_else(|| <A::Error as serde::de::Error>::missing_field("implName"))?;
585				let authoring_version = authoring_version.ok_or_else(|| {
586					<A::Error as serde::de::Error>::missing_field("authoringVersion")
587				})?;
588				let spec_version = spec_version
589					.ok_or_else(|| <A::Error as serde::de::Error>::missing_field("specVersion"))?;
590				let impl_version = impl_version
591					.ok_or_else(|| <A::Error as serde::de::Error>::missing_field("implVersion"))?;
592				let apis =
593					apis.ok_or_else(|| <A::Error as serde::de::Error>::missing_field("apis"))?;
594				let transaction_version = transaction_version.ok_or_else(|| {
595					<A::Error as serde::de::Error>::missing_field("transactionVersion")
596				})?;
597				let system_version = system_version.ok_or_else(|| {
598					<A::Error as serde::de::Error>::missing_field("systemVersion")
599				})?;
600				Ok(RuntimeVersion {
601					spec_name,
602					impl_name,
603					authoring_version,
604					spec_version,
605					impl_version,
606					apis,
607					transaction_version,
608					system_version,
609				})
610			}
611		}
612
613		const FIELDS: &[&str] = &[
614			"specName",
615			"implName",
616			"authoringVersion",
617			"specVersion",
618			"implVersion",
619			"apis",
620			"transactionVersion",
621			"stateVersion",
622			"systemVersion",
623		];
624
625		deserializer.deserialize_struct("RuntimeVersion", FIELDS, Visitor { lifetime: PhantomData })
626	}
627}
628
629impl RuntimeVersion {
630	/// `Decode` while giving a "version hint"
631	///
632	/// There exists multiple versions of [`RuntimeVersion`] and they are versioned using the `Core`
633	/// runtime api:
634	/// - `Core` version < 3 is a runtime version without a transaction version and state version.
635	/// - `Core` version 3 is a runtime version without a state version.
636	/// - `Core` version 4 is the latest runtime version.
637	pub fn decode_with_version_hint<I: Input>(
638		input: &mut I,
639		core_version: Option<u32>,
640	) -> Result<RuntimeVersion, codec::Error> {
641		let spec_name = Decode::decode(input)?;
642		let impl_name = Decode::decode(input)?;
643		let authoring_version = Decode::decode(input)?;
644		let spec_version = Decode::decode(input)?;
645		let impl_version = Decode::decode(input)?;
646		let apis = Decode::decode(input)?;
647		let core_version =
648			if core_version.is_some() { core_version } else { core_version_from_apis(&apis) };
649		let transaction_version =
650			if core_version.map(|v| v >= 3).unwrap_or(false) { Decode::decode(input)? } else { 1 };
651		let system_version =
652			if core_version.map(|v| v >= 4).unwrap_or(false) { Decode::decode(input)? } else { 0 };
653		Ok(RuntimeVersion {
654			spec_name,
655			impl_name,
656			authoring_version,
657			spec_version,
658			impl_version,
659			apis,
660			transaction_version,
661			system_version,
662		})
663	}
664}
665
666impl Decode for RuntimeVersion {
667	fn decode<I: Input>(input: &mut I) -> Result<Self, codec::Error> {
668		Self::decode_with_version_hint(input, None)
669	}
670}
671
672#[cfg(feature = "std")]
673impl fmt::Display for RuntimeVersion {
674	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
675		write!(
676			f,
677			"{}-{} ({}-{}.tx{}.au{})",
678			self.spec_name,
679			self.spec_version,
680			self.impl_name,
681			self.impl_version,
682			self.transaction_version,
683			self.authoring_version,
684		)
685	}
686}
687
688#[cfg(feature = "std")]
689fn has_api_with<P: Fn(u32) -> bool>(apis: &ApisVec, id: &ApiId, predicate: P) -> bool {
690	apis.iter().any(|(s, v)| s == id && predicate(*v))
691}
692
693/// Returns the version of the `Core` runtime api.
694pub fn core_version_from_apis(apis: &ApisVec) -> Option<u32> {
695	let id = sp_crypto_hashing_proc_macro::blake2b_64!(b"Core");
696	apis.iter().find(|(s, _v)| s == &id).map(|(_s, v)| *v)
697}
698
699#[cfg(feature = "std")]
700impl RuntimeVersion {
701	/// Check if this version matches other version for calling into runtime.
702	pub fn can_call_with(&self, other: &RuntimeVersion) -> bool {
703		self.spec_version == other.spec_version &&
704			self.spec_name == other.spec_name &&
705			self.authoring_version == other.authoring_version
706	}
707
708	/// Check if the given api with `api_id` is implemented and the version passes the given
709	/// `predicate`.
710	pub fn has_api_with<P: Fn(u32) -> bool>(&self, id: &ApiId, predicate: P) -> bool {
711		has_api_with(&self.apis, id, predicate)
712	}
713
714	/// Returns the api version found for api with `id`.
715	pub fn api_version(&self, id: &ApiId) -> Option<u32> {
716		self.apis.iter().find_map(|a| (a.0 == *id).then(|| a.1))
717	}
718}
719
720impl RuntimeVersion {
721	/// Returns state version to use for update.
722	///
723	/// For runtime with core api version less than 4,
724	/// V0 trie version will be applied to state.
725	/// Otherwise, V1 trie version will be use.
726	pub fn state_version(&self) -> StateVersion {
727		// If version > than 1, keep using latest version.
728		self.system_version.try_into().unwrap_or(StateVersion::V1)
729	}
730
731	/// Returns the state version to use for Extrinsics root.
732	pub fn extrinsics_root_state_version(&self) -> StateVersion {
733		match self.system_version {
734			// for system version 0 and 1, return V0
735			0 | 1 => StateVersion::V0,
736			// anything above 1, return V1
737			_ => StateVersion::V1,
738		}
739	}
740}
741
742/// The version of the native runtime.
743///
744/// In contrast to the bare [`RuntimeVersion`] this also carries a list of `spec_version`s of
745/// runtimes this native runtime can be used to author blocks for.
746#[derive(Debug)]
747#[cfg(feature = "std")]
748pub struct NativeVersion {
749	/// Basic runtime version info.
750	pub runtime_version: RuntimeVersion,
751	/// Authoring runtimes (`spec_version`s) that this native runtime supports.
752	pub can_author_with: HashSet<u32>,
753}
754
755#[cfg(feature = "std")]
756impl NativeVersion {
757	/// Check if this version matches other version for authoring blocks.
758	///
759	/// # Return
760	///
761	/// - Returns `Ok(())` when authoring is supported.
762	/// - Returns `Err(_)` with a detailed error when authoring is not supported.
763	pub fn can_author_with(&self, other: &RuntimeVersion) -> Result<(), String> {
764		if self.runtime_version.spec_name != other.spec_name {
765			Err(format!(
766				"`spec_name` does not match `{}` vs `{}`",
767				self.runtime_version.spec_name, other.spec_name,
768			))
769		} else if self.runtime_version.authoring_version != other.authoring_version &&
770			!self.can_author_with.contains(&other.authoring_version)
771		{
772			Err(format!(
773				"`authoring_version` does not match `{version}` vs `{other_version}` and \
774				`can_author_with` not contains `{other_version}`",
775				version = self.runtime_version.authoring_version,
776				other_version = other.authoring_version,
777			))
778		} else {
779			Ok(())
780		}
781	}
782}
783
784#[cfg(feature = "std")]
785/// Returns the version of the native runtime.
786pub trait GetNativeVersion {
787	/// Returns the version of the native runtime.
788	fn native_version(&self) -> &NativeVersion;
789}
790
791/// Something that can provide the runtime version at a given block.
792#[cfg(feature = "std")]
793pub trait GetRuntimeVersionAt<Block: BlockT> {
794	/// Returns the version of runtime at the given block.
795	fn runtime_version(&self, at: <Block as BlockT>::Hash) -> Result<RuntimeVersion, String>;
796}
797
798#[cfg(feature = "std")]
799impl<T: GetRuntimeVersionAt<Block>, Block: BlockT> GetRuntimeVersionAt<Block>
800	for std::sync::Arc<T>
801{
802	fn runtime_version(&self, at: <Block as BlockT>::Hash) -> Result<RuntimeVersion, String> {
803		(&**self).runtime_version(at)
804	}
805}
806
807#[cfg(feature = "std")]
808impl<T: GetNativeVersion> GetNativeVersion for std::sync::Arc<T> {
809	fn native_version(&self) -> &NativeVersion {
810		(&**self).native_version()
811	}
812}
813
814#[cfg(feature = "serde")]
815mod apis_serialize {
816	use super::*;
817	use alloc::vec::Vec;
818	use impl_serde::serialize as bytes;
819	use serde::{de, ser::SerializeTuple, Serializer};
820
821	#[derive(Serialize)]
822	struct ApiId<'a>(#[serde(serialize_with = "serialize_bytesref")] &'a super::ApiId, &'a u32);
823
824	pub fn serialize<S>(apis: &ApisVec, ser: S) -> Result<S::Ok, S::Error>
825	where
826		S: Serializer,
827	{
828		let len = apis.len();
829		let mut seq = ser.serialize_tuple(len)?;
830		for (api, ver) in &**apis {
831			seq.serialize_element(&ApiId(api, ver))?;
832		}
833		seq.end()
834	}
835
836	pub fn serialize_bytesref<S>(&apis: &&super::ApiId, ser: S) -> Result<S::Ok, S::Error>
837	where
838		S: Serializer,
839	{
840		bytes::serialize(apis, ser)
841	}
842
843	#[derive(Deserialize)]
844	struct ApiIdOwned(#[serde(deserialize_with = "deserialize_bytes")] super::ApiId, u32);
845
846	pub fn deserialize<'de, D>(deserializer: D) -> Result<ApisVec, D::Error>
847	where
848		D: de::Deserializer<'de>,
849	{
850		struct Visitor;
851		impl<'de> de::Visitor<'de> for Visitor {
852			type Value = ApisVec;
853
854			fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
855				formatter.write_str("a sequence of api id and version tuples")
856			}
857
858			fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
859			where
860				V: de::SeqAccess<'de>,
861			{
862				let mut apis = Vec::new();
863				while let Some(value) = visitor.next_element::<ApiIdOwned>()? {
864					apis.push((value.0, value.1));
865				}
866				Ok(apis.into())
867			}
868		}
869		deserializer.deserialize_seq(Visitor)
870	}
871
872	pub fn deserialize_bytes<'de, D>(d: D) -> Result<super::ApiId, D::Error>
873	where
874		D: de::Deserializer<'de>,
875	{
876		let mut arr = [0; 8];
877		bytes::deserialize_check_len(d, bytes::ExpectedLen::Exact(&mut arr[..]))?;
878		Ok(arr)
879	}
880}