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
//! Provides functionality to embed a [`RuntimeVersion`](crate::RuntimeVersion) as custom section
19
//! into a WASM file.
20

            
21
use codec::Encode;
22
use parity_wasm::elements::{deserialize_buffer, serialize, Module};
23

            
24
#[derive(Clone, Copy, Eq, PartialEq, Debug, thiserror::Error)]
25
pub enum Error {
26
	#[error("Deserializing wasm failed")]
27
	Deserialize,
28
	#[error("Serializing wasm failed")]
29
	Serialize,
30
}
31

            
32
/// Embed the given `version` to the given `wasm` blob.
33
///
34
/// If there was already a runtime version embedded, this will be overwritten.
35
///
36
/// Returns the new WASM blob.
37
pub fn embed_runtime_version(
38
	wasm: &[u8],
39
	mut version: crate::RuntimeVersion,
40
) -> Result<Vec<u8>, Error> {
41
	let mut module: Module = deserialize_buffer(wasm).map_err(|_| Error::Deserialize)?;
42

            
43
	let apis = version
44
		.apis
45
		.iter()
46
		.map(Encode::encode)
47
		.flat_map(|v| v.into_iter())
48
		.collect::<Vec<u8>>();
49

            
50
	module.set_custom_section("runtime_apis", apis);
51

            
52
	version.apis.to_mut().clear();
53
	module.set_custom_section("runtime_version", version.encode());
54

            
55
	serialize(module).map_err(|_| Error::Serialize)
56
}