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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use parking_lot::RwLock;
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_hash: Block::Hash,
block_number: RwLock<Option<NumberFor<Block>>>,
}
impl<Block: BlockT> WasmSubstitute<Block> {
fn new(
code: Vec<u8>,
block_hash: Block::Hash,
backend: &impl backend::Backend<Block>,
) -> Result<Self> {
let block_number = RwLock::new(backend.blockchain().number(block_hash)?);
let hash = make_hash(&code);
Ok(Self { code, hash, block_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 block_number = *self.block_number.read();
let block_number = if let Some(block_number) = block_number {
block_number
} else {
let block_number = match backend.blockchain().number(self.block_hash) {
Ok(Some(n)) => n,
Ok(None) => return false,
Err(e) => {
log::debug!(
target: "wasm_substitutes",
"Failed to get block number for block hash {:?}: {:?}",
self.block_hash,
e,
);
return false
},
};
*self.block_number.write() = Some(block_number);
block_number
};
let requested_block_number =
backend.blockchain().block_number_from_id(&block_id).ok().flatten();
Some(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<'a>(&'a self) -> Option<std::borrow::Cow<'a, [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<Block::Hash, Vec<u8>>,
executor: Executor,
backend: Arc<Backend>,
) -> Result<Self> {
let substitutes = substitutes
.into_iter()
.map(|(parent_block_hash, code)| {
let substitute = WasmSubstitute::new(code, parent_block_hash, &*backend)?;
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(format!("{:?}", e)).into())
}
}