1use crate::{BlakeTwo256, HashT as _, PvfExecKind, PvfPrepKind};
25use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec};
26use codec::{Decode, DecodeWithMemTracking, Encode};
27use core::{ops::Deref, time::Duration};
28use polkadot_core_primitives::Hash;
29use scale_info::TypeInfo;
30use serde::{Deserialize, Serialize};
31
32pub const DEFAULT_LOGICAL_STACK_MAX: u32 = 65536;
34pub const DEFAULT_NATIVE_STACK_MAX: u32 = 256 * 1024 * 1024;
36
37pub const MEMORY_PAGES_MAX: u32 = 65536;
39pub const LOGICAL_MAX_LO: u32 = 1024;
41pub const LOGICAL_MAX_HI: u32 = 2 * 65536;
43pub const PRECHECK_MEM_MAX_LO: u64 = 256 * 1024 * 1024;
45pub const PRECHECK_MEM_MAX_HI: u64 = 16 * 1024 * 1024 * 1024;
47
48pub const DEFAULT_PRECHECK_PREPARATION_TIMEOUT: Duration = Duration::from_secs(60);
53pub const DEFAULT_LENIENT_PREPARATION_TIMEOUT: Duration = Duration::from_secs(360);
55pub const DEFAULT_BACKING_EXECUTION_TIMEOUT: Duration = Duration::from_secs(2);
57pub const DEFAULT_APPROVAL_EXECUTION_TIMEOUT: Duration = Duration::from_secs(12);
59
60const DEFAULT_PRECHECK_PREPARATION_TIMEOUT_MS: u64 =
61 DEFAULT_PRECHECK_PREPARATION_TIMEOUT.as_millis() as u64;
62const DEFAULT_LENIENT_PREPARATION_TIMEOUT_MS: u64 =
63 DEFAULT_LENIENT_PREPARATION_TIMEOUT.as_millis() as u64;
64const DEFAULT_BACKING_EXECUTION_TIMEOUT_MS: u64 =
65 DEFAULT_BACKING_EXECUTION_TIMEOUT.as_millis() as u64;
66const DEFAULT_APPROVAL_EXECUTION_TIMEOUT_MS: u64 =
67 DEFAULT_APPROVAL_EXECUTION_TIMEOUT.as_millis() as u64;
68
69#[derive(
71 Clone,
72 Debug,
73 Encode,
74 Decode,
75 DecodeWithMemTracking,
76 PartialEq,
77 Eq,
78 TypeInfo,
79 Serialize,
80 Deserialize,
81)]
82pub enum ExecutorParam {
83 #[codec(index = 1)]
86 MaxMemoryPages(u32),
87 #[codec(index = 2)]
96 StackLogicalMax(u32),
97 #[codec(index = 3)]
104 StackNativeMax(u32),
105 #[codec(index = 4)]
109 PrecheckingMaxMemory(u64),
110 #[codec(index = 5)]
114 PvfPrepTimeout(PvfPrepKind, u64),
115 #[codec(index = 6)]
119 PvfExecTimeout(PvfExecKind, u64),
120 #[codec(index = 7)]
122 WasmExtBulkMemory,
123}
124
125#[derive(Debug)]
127pub enum ExecutorParamError {
128 DuplicatedParam(&'static str),
130 OutsideLimit(&'static str),
132 IncompatibleValues(&'static str, &'static str),
134}
135
136#[derive(Clone, Copy, Encode, Decode, Hash, Eq, PartialEq, PartialOrd, Ord, TypeInfo)]
140pub struct ExecutorParamsHash(Hash);
141
142impl ExecutorParamsHash {
143 pub fn from_hash(hash: Hash) -> Self {
145 Self(hash)
146 }
147}
148
149impl core::fmt::Display for ExecutorParamsHash {
150 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151 self.0.fmt(f)
152 }
153}
154
155impl core::fmt::Debug for ExecutorParamsHash {
156 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157 write!(f, "{:?}", self.0)
158 }
159}
160
161impl core::fmt::LowerHex for ExecutorParamsHash {
162 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
163 core::fmt::LowerHex::fmt(&self.0, f)
164 }
165}
166
167#[derive(Clone, Copy, Encode, Decode, Hash, Eq, PartialEq, PartialOrd, Ord, TypeInfo)]
172pub struct ExecutorParamsPrepHash(Hash);
173
174impl core::fmt::Display for ExecutorParamsPrepHash {
175 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
176 self.0.fmt(f)
177 }
178}
179
180impl core::fmt::Debug for ExecutorParamsPrepHash {
181 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
182 write!(f, "{:?}", self.0)
183 }
184}
185
186impl core::fmt::LowerHex for ExecutorParamsPrepHash {
187 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
188 core::fmt::LowerHex::fmt(&self.0, f)
189 }
190}
191
192#[derive(
204 Clone,
205 Debug,
206 Default,
207 Encode,
208 Decode,
209 DecodeWithMemTracking,
210 PartialEq,
211 Eq,
212 TypeInfo,
213 Serialize,
214 Deserialize,
215)]
216pub struct ExecutorParams(Vec<ExecutorParam>);
217
218impl ExecutorParams {
219 pub fn new() -> Self {
221 ExecutorParams(vec![])
222 }
223
224 pub fn hash(&self) -> ExecutorParamsHash {
226 ExecutorParamsHash(BlakeTwo256::hash(&self.encode()))
227 }
228
229 pub fn prep_hash(&self) -> ExecutorParamsPrepHash {
232 use ExecutorParam::*;
233
234 let mut enc = b"prep".to_vec();
235
236 self.0
237 .iter()
238 .flat_map(|param| match param {
239 MaxMemoryPages(..) => Some(param),
240 StackLogicalMax(..) => Some(param),
241 StackNativeMax(..) => None,
242 PrecheckingMaxMemory(..) => None,
243 PvfPrepTimeout(..) => None,
244 PvfExecTimeout(..) => None,
245 WasmExtBulkMemory => Some(param),
246 })
247 .for_each(|p| enc.extend(p.encode()));
248
249 ExecutorParamsPrepHash(BlakeTwo256::hash(&enc))
250 }
251
252 pub fn pvf_prep_timeout(&self, kind: PvfPrepKind) -> Option<Duration> {
254 for param in &self.0 {
255 if let ExecutorParam::PvfPrepTimeout(k, timeout) = param {
256 if kind == *k {
257 return Some(Duration::from_millis(*timeout))
258 }
259 }
260 }
261 None
262 }
263
264 pub fn pvf_exec_timeout(&self, kind: PvfExecKind) -> Option<Duration> {
266 for param in &self.0 {
267 if let ExecutorParam::PvfExecTimeout(k, timeout) = param {
268 if kind == *k {
269 return Some(Duration::from_millis(*timeout))
270 }
271 }
272 }
273 None
274 }
275
276 pub fn prechecking_max_memory(&self) -> Option<u64> {
278 for param in &self.0 {
279 if let ExecutorParam::PrecheckingMaxMemory(limit) = param {
280 return Some(*limit)
281 }
282 }
283 None
284 }
285
286 pub fn check_consistency(&self) -> Result<(), ExecutorParamError> {
288 use ExecutorParam::*;
289 use ExecutorParamError::*;
290
291 let mut seen = BTreeMap::<&str, u64>::new();
292
293 macro_rules! check {
294 ($param:ident, $val:expr $(,)?) => {
295 if seen.contains_key($param) {
296 return Err(DuplicatedParam($param))
297 }
298 seen.insert($param, $val as u64);
299 };
300
301 ($param:ident, $val:expr, $out_of_limit:expr $(,)?) => {
303 if seen.contains_key($param) {
304 return Err(DuplicatedParam($param))
305 }
306 if $out_of_limit {
307 return Err(OutsideLimit($param))
308 }
309 seen.insert($param, $val as u64);
310 };
311 }
312
313 for param in &self.0 {
314 let param_ident = match *param {
316 MaxMemoryPages(_) => "MaxMemoryPages",
317 StackLogicalMax(_) => "StackLogicalMax",
318 StackNativeMax(_) => "StackNativeMax",
319 PrecheckingMaxMemory(_) => "PrecheckingMaxMemory",
320 PvfPrepTimeout(kind, _) => match kind {
321 PvfPrepKind::Precheck => "PvfPrepKind::Precheck",
322 PvfPrepKind::Prepare => "PvfPrepKind::Prepare",
323 },
324 PvfExecTimeout(kind, _) => match kind {
325 PvfExecKind::Backing => "PvfExecKind::Backing",
326 PvfExecKind::Approval => "PvfExecKind::Approval",
327 },
328 WasmExtBulkMemory => "WasmExtBulkMemory",
329 };
330
331 match *param {
332 MaxMemoryPages(val) => {
333 check!(param_ident, val, val == 0 || val > MEMORY_PAGES_MAX,);
334 },
335
336 StackLogicalMax(val) => {
337 check!(param_ident, val, val < LOGICAL_MAX_LO || val > LOGICAL_MAX_HI,);
338 },
339
340 StackNativeMax(val) => {
341 check!(param_ident, val);
342 },
343
344 PrecheckingMaxMemory(val) => {
345 check!(
346 param_ident,
347 val,
348 val < PRECHECK_MEM_MAX_LO || val > PRECHECK_MEM_MAX_HI,
349 );
350 },
351
352 PvfPrepTimeout(_, val) => {
353 check!(param_ident, val);
354 },
355
356 PvfExecTimeout(_, val) => {
357 check!(param_ident, val);
358 },
359
360 WasmExtBulkMemory => {
361 check!(param_ident, 1);
362 },
363 }
364 }
365
366 if let (Some(lm), Some(nm)) = (
367 seen.get("StackLogicalMax").or(Some(&(DEFAULT_LOGICAL_STACK_MAX as u64))),
368 seen.get("StackNativeMax").or(Some(&(DEFAULT_NATIVE_STACK_MAX as u64))),
369 ) {
370 if *nm < 128 * *lm {
371 return Err(IncompatibleValues("StackLogicalMax", "StackNativeMax"))
372 }
373 }
374
375 if let (Some(precheck), Some(lenient)) = (
376 seen.get("PvfPrepKind::Precheck")
377 .or(Some(&DEFAULT_PRECHECK_PREPARATION_TIMEOUT_MS)),
378 seen.get("PvfPrepKind::Prepare")
379 .or(Some(&DEFAULT_LENIENT_PREPARATION_TIMEOUT_MS)),
380 ) {
381 if *precheck >= *lenient {
382 return Err(IncompatibleValues("PvfPrepKind::Precheck", "PvfPrepKind::Prepare"))
383 }
384 }
385
386 if let (Some(backing), Some(approval)) = (
387 seen.get("PvfExecKind::Backing").or(Some(&DEFAULT_BACKING_EXECUTION_TIMEOUT_MS)),
388 seen.get("PvfExecKind::Approval")
389 .or(Some(&DEFAULT_APPROVAL_EXECUTION_TIMEOUT_MS)),
390 ) {
391 if *backing >= *approval {
392 return Err(IncompatibleValues("PvfExecKind::Backing", "PvfExecKind::Approval"))
393 }
394 }
395
396 Ok(())
397 }
398}
399
400impl Deref for ExecutorParams {
401 type Target = Vec<ExecutorParam>;
402
403 fn deref(&self) -> &Self::Target {
404 &self.0
405 }
406}
407
408impl From<&[ExecutorParam]> for ExecutorParams {
409 fn from(arr: &[ExecutorParam]) -> Self {
410 ExecutorParams(arr.to_vec())
411 }
412}
413
414#[test]
420fn ensure_prep_hash_changes() {
421 use ExecutorParam::*;
422 let ep = ExecutorParams::from(
423 &[
424 MaxMemoryPages(0),
425 StackLogicalMax(0),
426 StackNativeMax(0),
427 PrecheckingMaxMemory(0),
428 PvfPrepTimeout(PvfPrepKind::Precheck, 0),
429 PvfPrepTimeout(PvfPrepKind::Prepare, 0),
430 PvfExecTimeout(PvfExecKind::Backing, 0),
431 PvfExecTimeout(PvfExecKind::Approval, 0),
432 WasmExtBulkMemory,
433 ][..],
434 );
435
436 for p in ep.iter() {
437 let (ep1, ep2) = match p {
438 MaxMemoryPages(_) => (
439 ExecutorParams::from(&[MaxMemoryPages(1)][..]),
440 ExecutorParams::from(&[MaxMemoryPages(2)][..]),
441 ),
442 StackLogicalMax(_) => (
443 ExecutorParams::from(&[StackLogicalMax(1)][..]),
444 ExecutorParams::from(&[StackLogicalMax(2)][..]),
445 ),
446 StackNativeMax(_) => continue,
447 PrecheckingMaxMemory(_) => continue,
448 PvfPrepTimeout(_, _) => continue,
449 PvfExecTimeout(_, _) => continue,
450 WasmExtBulkMemory =>
451 (ExecutorParams::default(), ExecutorParams::from(&[WasmExtBulkMemory][..])),
452 };
453
454 assert_ne!(ep1.prep_hash(), ep2.prep_hash());
455 }
456}