Управление версиями во время выполнения - важная часть функции «обновления без выполнения» в блокчейнах на основе субстратов.
С core/sr-version
на момент публикации:
/// Runtime version.
/// This should not be thought of as classic Semver (major/minor/tiny).
/// This triplet have different semantics and mis-interpretation could cause problems.
/// In particular: bug fixes should result in an increment of `spec_version` and possibly `authoring_version`,
/// absolutely not `impl_version` since they change the semantics of the runtime.
#[derive(Clone, PartialEq, Eq, Encode)]
#[cfg_attr(feature = "std", derive(Debug, Serialize, Decode))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct RuntimeVersion {
/// Identifies the different Substrate runtimes. There'll be at least polkadot and node.
/// A different on-chain spec_name to that of the native runtime would normally result
/// in node not attempting to sync or author blocks.
pub spec_name: RuntimeString,
/// Name of the implementation of the spec. This is of little consequence for the node
/// and serves only to differentiate code of different implementation teams. For this
/// codebase, it will be parity-polkadot. If there were a non-Rust implementation of the
/// Polkadot runtime (e.g. C++), then it would identify itself with an accordingly different
/// `impl_name`.
pub impl_name: RuntimeString,
/// `authoring_version` is the version of the authorship interface. An authoring node
/// will not attempt to author blocks unless this is equal to its native runtime.
pub authoring_version: u32,
/// Version of the runtime specification. A full-node will not attempt to use its native
/// runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`,
/// `spec_version` and `authoring_version` are the same between Wasm and native.
pub spec_version: u32,
/// Version of the implementation of the specification. Nodes are free to ignore this; it
/// serves only as an indication that the code is different; as long as the other two versions
/// are the same then while the actual code may be different, it is nonetheless required to
/// do the same thing.
/// Non-consensus-breaking optimizations are about the only changes that could be made which
/// would result in only the `impl_version` changing.
pub impl_version: u32,
/// List of supported API "features" along with their versions.
#[cfg_attr(feature = "std", serde(serialize_with = "apis_serialize::serialize"))]
pub apis: ApisVec,
}
spec_version
используется для обозначения того, изменилась ли согласованная логика , а impl_version
используется для обозначения изменений, которые не повлияют на согласованность в сети. Например, если поведение функции изменяется во время выполнения, вы должны увеличить spec_version
, чтобы отметить, что эта версия среды выполнения не достигнет консенсуса с другой версией среды выполнения. Принимая во внимание, что если была проведена только оптимизация для функции, но результирующий вывод такой же, то нужно только увеличить impl_version
.
Используя spec_version
, узел может определить, соответствует ли собственная версия среды выполнения (собственно исполняемый файл, фактически выполняющий узел) версии Wasm среды выполнения (которая хранится в цепочке, и сеть пришла к согласию с).
В случае, когда собственные spec_name
, authoring_version
и spec_version
среды выполнения соответствуют версиям среды выполнения Wasm, вместо среды выполнения Wasm используется собственная среда выполнения, поскольку быстрее выполнить. В случае, если spec_version
не совпадает точно, узел вернется к использованию версии среды выполнения Wasm, гарантируя, что узел остается согласованным с остальной сетью.
Если вы хотите следовать пути кода, где это происходит, вы можете начать с core/sr-version
.
impl RuntimeVersion {
/// Check if this version matches other version for calling into runtime.
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
}
...
}
Затем, если вы войдете в core/executor/native_executor.rs
, вы увидите, что функция can_call_with
используется для определения возможности использования встроенной среды выполнения.
Редактировать: Важно отметить, что механизм выполнения построения блока всегда по умолчанию равен Wasm, в то время как механизм выполнения импорта пытается по возможности использовать native, используя приведенную выше логику.