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
use crate::natives::helpers::make_module_natives;
use move_binary_format::errors::PartialVMResult;
use move_vm_runtime::native_functions::{NativeContext, NativeFunction};
use move_vm_types::{
loaded_data::runtime_types::Type, natives::function::NativeResult, pop_arg, values::Value,
};
use sha2::{Digest, Sha256};
use sha3::Sha3_256;
use smallvec::smallvec;
use std::{collections::VecDeque, sync::Arc};
#[derive(Debug, Clone)]
pub struct Sha2_256GasParameters {
pub base_cost: u64,
pub unit_cost: u64,
pub legacy_min_input_len: usize,
}
#[inline]
fn native_sha2_256(
gas_params: &Sha2_256GasParameters,
_context: &mut NativeContext,
_ty_args: Vec<Type>,
mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert!(_ty_args.is_empty());
debug_assert!(arguments.len() == 1);
let hash_arg = pop_arg!(arguments, Vec<u8>);
let cost = gas_params.base_cost
+ gas_params.unit_cost * usize::max(hash_arg.len(), gas_params.legacy_min_input_len) as u64;
let hash_vec = Sha256::digest(hash_arg.as_slice()).to_vec();
Ok(NativeResult::ok(
cost,
smallvec![Value::vector_u8(hash_vec)],
))
}
pub fn make_native_sha2_256(gas_params: Sha2_256GasParameters) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_sha2_256(&gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct Sha3_256GasParameters {
pub base_cost: u64,
pub unit_cost: u64,
pub legacy_min_input_len: usize,
}
#[inline]
fn native_sha3_256(
gas_params: &Sha3_256GasParameters,
_context: &mut NativeContext,
_ty_args: Vec<Type>,
mut arguments: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert!(_ty_args.is_empty());
debug_assert!(arguments.len() == 1);
let hash_arg = pop_arg!(arguments, Vec<u8>);
let cost = gas_params.base_cost
+ gas_params.unit_cost * usize::max(hash_arg.len(), gas_params.legacy_min_input_len) as u64;
let hash_vec = Sha3_256::digest(hash_arg.as_slice()).to_vec();
Ok(NativeResult::ok(
cost,
smallvec![Value::vector_u8(hash_vec)],
))
}
pub fn make_native_sha3_256(gas_params: Sha3_256GasParameters) -> NativeFunction {
Arc::new(
move |context, ty_args, args| -> PartialVMResult<NativeResult> {
native_sha3_256(&gas_params, context, ty_args, args)
},
)
}
#[derive(Debug, Clone)]
pub struct GasParameters {
pub sha2_256: Sha2_256GasParameters,
pub sha3_256: Sha3_256GasParameters,
}
pub fn make_all(gas_params: GasParameters) -> impl Iterator<Item = (String, NativeFunction)> {
let natives = [
("sha2_256", make_native_sha2_256(gas_params.sha2_256)),
("sha3_256", make_native_sha3_256(gas_params.sha3_256)),
];
make_module_natives(natives)
}