1pub use checked::*;
5#[sui_macros::with_checked_arithmetic]
6mod checked {
7 use move_vm_runtime::natives::extensions::NativeExtensions;
8 use move_vm_runtime::natives::functions::{NativeFunctionTable, NativeFunctions};
9 use move_vm_runtime::runtime::MoveRuntime;
10 use std::cell::RefCell;
11 use std::rc::Rc;
12 use std::{collections::BTreeMap, sync::Arc};
13
14 use anyhow::Result;
15 use move_binary_format::file_format::CompiledModule;
16 use move_bytecode_verifier::verify_module_with_config_metered;
17 use move_bytecode_verifier_meter::{Meter, Scope};
18 use move_core_types::account_address::AccountAddress;
19 use move_vm_config::{
20 runtime::{VMConfig, VMRuntimeLimitsConfig},
21 verifier::VerifierConfig,
22 };
23 use mysten_common::debug_fatal;
24 use sui_move_natives::{object_runtime, transaction_context::TransactionContext};
25 use sui_types::error::SuiErrorKind;
26 use sui_types::metrics::BytecodeVerifierMetrics;
27 use sui_verifier::check_for_verifier_timeout;
28 use tracing::instrument;
29
30 use sui_move_natives::{
31 NativesCostTable, object_runtime::ObjectRuntime, scratch::ScratchRuntime,
32 };
33 use sui_protocol_config::ProtocolConfig;
34 use sui_types::{
35 base_types::*,
36 error::{ExecutionError, SuiError},
37 execution_status::ExecutionErrorKind,
38 metrics::ExecutionMetrics,
39 storage::RuntimeObjectResolver,
40 };
41 use sui_verifier::verifier::sui_verify_module_metered_check_timeout_only;
42
43 pub fn new_move_runtime(
44 natives: NativeFunctionTable,
45 protocol_config: &ProtocolConfig,
46 ) -> Result<MoveRuntime, SuiError> {
47 let native_functions =
48 NativeFunctions::new(natives).map_err(|_| SuiErrorKind::ExecutionInvariantViolation)?;
49 Ok(MoveRuntime::new(
50 native_functions,
51 vm_config(protocol_config),
52 ))
53 }
54
55 pub fn vm_config(protocol_config: &ProtocolConfig) -> VMConfig {
56 VMConfig {
57 verifier: protocol_config.verifier_config(None),
58 max_binary_format_version: protocol_config.move_binary_format_version(),
59 runtime_limits_config: VMRuntimeLimitsConfig {
60 vector_len_max: protocol_config.max_move_vector_len(),
61 max_value_nest_depth: protocol_config.max_move_value_depth_as_option(),
62 hardened_otw_check: protocol_config.hardened_otw_check(),
63 },
64 enable_invariant_violation_check_in_swap_loc: !protocol_config
65 .disable_invariant_violation_check_in_swap_loc(),
66 check_no_extraneous_bytes_during_deserialization: protocol_config
67 .no_extraneous_module_bytes(),
68 error_execution_state: false,
70 binary_config: protocol_config.binary_config(None),
71 rethrow_serialization_type_layout_errors: protocol_config
72 .rethrow_serialization_type_layout_errors(),
73 max_type_to_layout_nodes: protocol_config.max_type_to_layout_nodes_as_option(),
74 variant_nodes: protocol_config.variant_nodes(),
75 deprecate_global_storage_ops_during_deserialization: protocol_config
76 .deprecate_global_storage_ops_during_deserialization(),
77 normalize_depth_formula: protocol_config.normalize_depth_formula(),
78 }
79 }
80
81 pub fn new_native_extensions<'r>(
82 child_resolver: &'r dyn RuntimeObjectResolver,
83 input_objects: BTreeMap<ObjectID, object_runtime::InputObject>,
84 is_metered: bool,
85 protocol_config: &'r ProtocolConfig,
86 metrics: Arc<ExecutionMetrics>,
87 tx_context: Rc<RefCell<TxContext>>,
88 ) -> Result<NativeExtensions<'r>, ExecutionError> {
89 let current_epoch_id: EpochId = tx_context.borrow().epoch();
90 let extensions = NativeExtensions::default();
91 let mut exts = extensions.try_borrow_mut().map_err(|_| {
92 make_invariant_violation!(
93 "Failed to mutably borrow native extensions to populate them right after creating them"
94 )
95 })?;
96 exts.add(ObjectRuntime::new(
97 child_resolver,
98 input_objects,
99 is_metered,
100 protocol_config,
101 metrics,
102 current_epoch_id,
103 ));
104 exts.add(NativesCostTable::from_protocol_config(protocol_config));
105 exts.add(ScratchRuntime::new(protocol_config));
106 exts.add(TransactionContext::new(tx_context));
107 drop(exts);
108 Ok(extensions)
109 }
110
111 pub fn substitute_package_id(
114 modules: &mut [CompiledModule],
115 object_id: ObjectID,
116 ) -> Result<(), ExecutionError> {
117 let new_address = AccountAddress::from(object_id);
118
119 for module in modules.iter_mut() {
120 let self_handle = module.self_handle().clone();
121 let self_address_idx = self_handle.address;
122
123 let addrs = &mut module.address_identifiers;
124 let Some(address_mut) = addrs.get_mut(self_address_idx.0 as usize) else {
125 let name = module.identifier_at(self_handle.name);
126 return Err(ExecutionError::new_with_source(
127 ExecutionErrorKind::PublishErrorNonZeroAddress,
128 format!("Publishing module {name} with invalid address index"),
129 ));
130 };
131
132 if *address_mut != AccountAddress::ZERO {
133 let name = module.identifier_at(self_handle.name);
134 return Err(ExecutionError::new_with_source(
135 ExecutionErrorKind::PublishErrorNonZeroAddress,
136 format!("Publishing module {name} with non-zero address is not allowed"),
137 ));
138 };
139
140 *address_mut = new_address;
141 }
142
143 Ok(())
144 }
145
146 pub fn missing_unwrapped_msg(id: &ObjectID) -> String {
147 format!(
148 "Unable to unwrap object {}. Was unable to retrieve last known version in the parent sync",
149 id
150 )
151 }
152
153 #[instrument(level = "trace", skip_all)]
159 pub fn run_metered_move_bytecode_verifier(
160 modules: &[CompiledModule],
161 verifier_config: &VerifierConfig,
162 meter: &mut (impl Meter + ?Sized),
163 metrics: &Arc<BytecodeVerifierMetrics>,
164 ) -> Result<(), SuiError> {
165 for module in modules.iter() {
167 let per_module_meter_verifier_timer = metrics
168 .verifier_runtime_per_module_success_latency
169 .start_timer();
170
171 if let Err(e) = verify_module_timeout_only(module, verifier_config, meter) {
172 metrics
175 .verifier_runtime_per_module_timeout_latency
176 .observe(per_module_meter_verifier_timer.stop_and_discard());
177 metrics
178 .verifier_timeout_metrics
179 .with_label_values(&[
180 BytecodeVerifierMetrics::OVERALL_TAG,
181 BytecodeVerifierMetrics::TIMEOUT_TAG,
182 ])
183 .inc();
184
185 return Err(e);
186 };
187
188 per_module_meter_verifier_timer.stop_and_record();
190 metrics
191 .verifier_timeout_metrics
192 .with_label_values(&[
193 BytecodeVerifierMetrics::OVERALL_TAG,
194 BytecodeVerifierMetrics::SUCCESS_TAG,
195 ])
196 .inc();
197 }
198
199 Ok(())
200 }
201
202 fn verify_module_timeout_only(
206 module: &CompiledModule,
207 verifier_config: &VerifierConfig,
208 meter: &mut (impl Meter + ?Sized),
209 ) -> Result<(), SuiError> {
210 meter.enter_scope(module.self_id().name().as_str(), Scope::Module);
211
212 if let Err(e) = verify_module_with_config_metered(verifier_config, module, meter) {
213 if check_for_verifier_timeout(&e.major_status()) {
215 if e.major_status()
216 == move_core_types::vm_status::StatusCode::REFERENCE_SAFETY_INCONSISTENT
217 {
218 let mut bytes = vec![];
219 let _ = module.serialize_with_version(
220 move_binary_format::file_format_common::VERSION_MAX,
221 &mut bytes,
222 );
223 debug_fatal!(
224 "Reference safety inconsistency detected in module: {:?}",
225 bytes
226 );
227 }
228 return Err(SuiErrorKind::ModuleVerificationFailure {
229 error: format!("Verification timed out: {}", e),
230 }
231 .into());
232 }
233 } else if let Err(err) = sui_verify_module_metered_check_timeout_only(
234 module,
235 &BTreeMap::new(),
236 meter,
237 verifier_config,
238 ) {
239 return Err(err.into());
240 }
241
242 if meter.transfer(Scope::Module, Scope::Package, 1.0).is_err() {
243 return Err(SuiErrorKind::ModuleVerificationFailure {
244 error: "Verification timed out".to_string(),
245 }
246 .into());
247 }
248
249 Ok(())
250 }
251}