1#![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
60pub use sp_version_proc_macro::runtime_version;
123
124pub type ApiId = [u8; 8];
147
148pub type ApisVec = alloc::borrow::Cow<'static, [(ApiId, u32)]>;
150
151#[macro_export]
153macro_rules! create_apis_vec {
154 ( $y:expr ) => {
155 $crate::Cow::Borrowed(&$y)
156 };
157}
158
159#[derive(Clone, PartialEq, Eq, Encode, Default, sp_runtime::RuntimeDebug, TypeInfo)]
166pub struct RuntimeVersion {
167 pub spec_name: Cow<'static, str>,
171
172 pub impl_name: Cow<'static, str>,
178
179 pub authoring_version: u32,
182
183 pub spec_version: u32,
191
192 pub impl_version: u32,
202
203 pub apis: ApisVec,
205
206 pub transaction_version: u32,
226
227 pub system_version: u8,
230}
231
232#[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#[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 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
693pub 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 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 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 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 pub fn state_version(&self) -> StateVersion {
727 self.system_version.try_into().unwrap_or(StateVersion::V1)
729 }
730
731 pub fn extrinsics_root_state_version(&self) -> StateVersion {
733 match self.system_version {
734 0 | 1 => StateVersion::V0,
736 _ => StateVersion::V1,
738 }
739 }
740}
741
742#[derive(Debug)]
747#[cfg(feature = "std")]
748pub struct NativeVersion {
749 pub runtime_version: RuntimeVersion,
751 pub can_author_with: HashSet<u32>,
753}
754
755#[cfg(feature = "std")]
756impl NativeVersion {
757 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")]
785pub trait GetNativeVersion {
787 fn native_version(&self) -> &NativeVersion;
789}
790
791#[cfg(feature = "std")]
793pub trait GetRuntimeVersionAt<Block: BlockT> {
794 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}