1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use sc_client_api::backend;
use sc_executor::RuntimeVersionOf;
use sp_blockchain::{HeaderBackend, Result};
use sp_core::traits::{FetchRuntimeCode, RuntimeCode};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, NumberFor},
};
use sp_state_machine::BasicExternalities;
use sp_version::RuntimeVersion;
use std::{
collections::{hash_map::DefaultHasher, HashMap},
hash::Hasher as _,
sync::Arc,
};
#[derive(Debug)]
struct WasmSubstitute<Block: BlockT> {
code: Vec<u8>,
hash: Vec<u8>,
block_number: NumberFor<Block>,
}
impl<Block: BlockT> WasmSubstitute<Block> {
fn new(code: Vec<u8>, block_number: NumberFor<Block>) -> Self {
let hash = make_hash(&code);
Self { code, hash, block_number }
}
fn runtime_code(&self, heap_pages: Option<u64>) -> RuntimeCode {
RuntimeCode { code_fetcher: self, hash: self.hash.clone(), heap_pages }
}
fn matches(&self, block_id: &BlockId<Block>, backend: &impl backend::Backend<Block>) -> bool {
let requested_block_number =
backend.blockchain().block_number_from_id(block_id).ok().flatten();
Some(self.block_number) <= requested_block_number
}
}
fn make_hash<K: std::hash::Hash + ?Sized>(val: &K) -> Vec<u8> {
let mut state = DefaultHasher::new();
val.hash(&mut state);
state.finish().to_le_bytes().to_vec()
}
impl<Block: BlockT> FetchRuntimeCode for WasmSubstitute<Block> {
fn fetch_runtime_code(&self) -> Option<std::borrow::Cow<[u8]>> {
Some(self.code.as_slice().into())
}
}
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum WasmSubstituteError {
#[error("Failed to get runtime version: {0}")]
VersionInvalid(String),
}
impl From<WasmSubstituteError> for sp_blockchain::Error {
fn from(err: WasmSubstituteError) -> Self {
Self::Application(Box::new(err))
}
}
#[derive(Debug)]
pub struct WasmSubstitutes<Block: BlockT, Executor, Backend> {
substitutes: Arc<HashMap<u32, WasmSubstitute<Block>>>,
executor: Executor,
backend: Arc<Backend>,
}
impl<Block: BlockT, Executor: Clone, Backend> Clone for WasmSubstitutes<Block, Executor, Backend> {
fn clone(&self) -> Self {
Self {
substitutes: self.substitutes.clone(),
executor: self.executor.clone(),
backend: self.backend.clone(),
}
}
}
impl<Executor, Backend, Block> WasmSubstitutes<Block, Executor, Backend>
where
Executor: RuntimeVersionOf + Clone + 'static,
Backend: backend::Backend<Block>,
Block: BlockT,
{
pub fn new(
substitutes: HashMap<NumberFor<Block>, Vec<u8>>,
executor: Executor,
backend: Arc<Backend>,
) -> Result<Self> {
let substitutes = substitutes
.into_iter()
.map(|(block_number, code)| {
let substitute = WasmSubstitute::new(code, block_number);
let version = Self::runtime_version(&executor, &substitute)?;
Ok((version.spec_version, substitute))
})
.collect::<Result<HashMap<_, _>>>()?;
Ok(Self { executor, substitutes: Arc::new(substitutes), backend })
}
pub fn get(
&self,
spec: u32,
pages: Option<u64>,
block_id: &BlockId<Block>,
) -> Option<RuntimeCode<'_>> {
let s = self.substitutes.get(&spec)?;
s.matches(block_id, &*self.backend).then(|| s.runtime_code(pages))
}
fn runtime_version(
executor: &Executor,
code: &WasmSubstitute<Block>,
) -> Result<RuntimeVersion> {
let mut ext = BasicExternalities::default();
executor
.runtime_version(&mut ext, &code.runtime_code(None))
.map_err(|e| WasmSubstituteError::VersionInvalid(e.to_string()).into())
}
}