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
use move_deps::{
move_binary_format::errors::{PartialVMError, PartialVMResult},
move_core_types::vm_status::StatusCode,
move_vm_runtime::native_functions::{NativeContext, NativeFunction},
move_vm_types::{
loaded_data::runtime_types::Type, natives::function::NativeResult, pop_arg, values::Value,
},
};
use smallvec::smallvec;
use std::{collections::VecDeque, sync::Arc};
const EFROM_BYTES: u64 = 0x01_0001;
#[derive(Debug, Clone)]
pub struct FromBytesGasParameters {
pub base_cost: u64,
pub unit_cost: u64,
}
fn native_from_bytes(
gas_params: &FromBytesGasParameters,
context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert_eq!(ty_args.len(), 1);
debug_assert_eq!(args.len(), 1);
let layout = context.type_to_type_layout(&ty_args[0])?.ok_or_else(|| {
PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR).with_message(format!(
"Failed to get layout of type {:?} -- this should not happen",
ty_args[0]
))
})?;
let bytes = pop_arg!(args, Vec<u8>);
let cost = gas_params.base_cost + gas_params.unit_cost * bytes.len() as u64;
let val = match Value::simple_deserialize(&bytes, &layout) {
Some(val) => val,
None => return Ok(NativeResult::err(cost, EFROM_BYTES)),
};
Ok(NativeResult::ok(cost, smallvec![val]))
}
pub fn make_native_from_bytes(gas_params: FromBytesGasParameters) -> NativeFunction {
Arc::new(move |context, ty_args, args| native_from_bytes(&gas_params, context, ty_args, args))
}
#[derive(Debug, Clone)]
pub struct GasParameters {
pub from_bytes: FromBytesGasParameters,
}
pub fn make_all(gas_params: GasParameters) -> impl Iterator<Item = (String, NativeFunction)> {
let natives = [("from_bytes", make_native_from_bytes(gas_params.from_bytes))];
crate::natives::helpers::make_module_natives(natives)
}