1use std::{collections::BTreeMap, error::Error, num::NonZeroU64};
17
18use iota_types::{
19 GENESIS_BRIDGE_ADDRESS, IOTA_FRAMEWORK_ADDRESS, IOTA_SYSTEM_ADDRESS,
20 error::{ExecutionError, VMMVerifierErrorSubStatusCode},
21};
22use move_abstract_stack::AbstractStack;
23use move_binary_format::{
24 errors::PartialVMError,
25 file_format::{
26 Bytecode, CodeOffset, CompiledModule, FunctionDefinitionIndex, FunctionHandle, LocalIndex,
27 StructDefinition, StructFieldInformation,
28 },
29};
30use move_bytecode_verifier::absint::{
31 AbstractDomain, FunctionContext, JoinResult, TransferFunctions, analyze_function,
32};
33use move_bytecode_verifier_meter::{Meter, Scope};
34use move_core_types::{
35 account_address::AccountAddress, ident_str, identifier::IdentStr, vm_status::StatusCode,
36};
37
38use crate::{check_for_verifier_timeout, to_verification_timeout_error, verification_failure};
39
40pub(crate) const JOIN_BASE_COST: u128 = 10;
41pub(crate) const JOIN_PER_LOCAL_COST: u128 = 5;
42pub(crate) const STEP_BASE_COST: u128 = 15;
43
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45enum AbstractValue {
46 Fresh,
47 Other,
48}
49
50type FunctionIdent<'a> = (&'a AccountAddress, &'a IdentStr, &'a IdentStr);
51const OBJECT_NEW: FunctionIdent = (
52 &IOTA_FRAMEWORK_ADDRESS,
53 ident_str!("object"),
54 ident_str!("new"),
55);
56const OBJECT_NEW_UID_FROM_HASH: FunctionIdent = (
57 &IOTA_FRAMEWORK_ADDRESS,
58 ident_str!("object"),
59 ident_str!("new_uid_from_hash"),
60);
61const TS_NEW_OBJECT: FunctionIdent = (
62 &IOTA_FRAMEWORK_ADDRESS,
63 ident_str!("test_scenario"),
64 ident_str!("new_object"),
65);
66const IOTA_SYSTEM_CREATE: FunctionIdent = (
67 &IOTA_SYSTEM_ADDRESS,
68 ident_str!("iota_system"),
69 ident_str!("create"),
70);
71const IOTA_CLOCK_CREATE: FunctionIdent = (
72 &IOTA_FRAMEWORK_ADDRESS,
73 ident_str!("clock"),
74 ident_str!("create"),
75);
76const IOTA_AUTHENTICATOR_STATE_CREATE: FunctionIdent = (
79 &IOTA_FRAMEWORK_ADDRESS,
80 ident_str!("authenticator_state"),
81 ident_str!("create"),
82);
83const IOTA_RANDOMNESS_STATE_CREATE: FunctionIdent = (
84 &IOTA_FRAMEWORK_ADDRESS,
85 ident_str!("random"),
86 ident_str!("create"),
87);
88const IOTA_DENY_LIST_CREATE: FunctionIdent = (
89 &IOTA_FRAMEWORK_ADDRESS,
90 ident_str!("deny_list"),
91 ident_str!("create"),
92);
93const IOTA_TRANSACTION_DENY_RULES_CREATE: FunctionIdent = (
94 &IOTA_FRAMEWORK_ADDRESS,
95 ident_str!("transaction_deny_rules"),
96 ident_str!("create"),
97);
98
99const IOTA_BRIDGE_CREATE: FunctionIdent = (
100 &GENESIS_BRIDGE_ADDRESS,
101 ident_str!("bridge"),
102 ident_str!("create"),
103);
104const FRESH_ID_FUNCTIONS: &[FunctionIdent] = &[OBJECT_NEW, OBJECT_NEW_UID_FROM_HASH, TS_NEW_OBJECT];
105const FUNCTIONS_TO_SKIP: &[FunctionIdent] = &[
106 IOTA_SYSTEM_CREATE,
107 IOTA_CLOCK_CREATE,
108 IOTA_AUTHENTICATOR_STATE_CREATE,
109 IOTA_RANDOMNESS_STATE_CREATE,
110 IOTA_DENY_LIST_CREATE,
111 IOTA_TRANSACTION_DENY_RULES_CREATE,
112 IOTA_BRIDGE_CREATE,
113];
114
115impl AbstractValue {
116 pub fn join(&self, value: &AbstractValue) -> AbstractValue {
117 if self == value {
118 *value
119 } else {
120 AbstractValue::Other
121 }
122 }
123}
124
125pub fn verify_module(
126 module: &CompiledModule,
127 meter: &mut (impl Meter + ?Sized),
128) -> Result<(), ExecutionError> {
129 verify_id_leak(module, meter)
130}
131
132fn verify_id_leak(
133 module: &CompiledModule,
134 meter: &mut (impl Meter + ?Sized),
135) -> Result<(), ExecutionError> {
136 for (index, func_def) in module.function_defs.iter().enumerate() {
137 let code = match func_def.code.as_ref() {
138 Some(code) => code,
139 None => continue,
140 };
141 let handle = module.function_handle_at(func_def.function);
142 let function_context =
143 FunctionContext::new(module, FunctionDefinitionIndex(index as u16), code, handle);
144 let initial_state = AbstractState::new(&function_context);
145 let mut verifier = IDLeakAnalysis::new(module, &function_context);
146 let function_to_verify = verifier.cur_function();
147 if FUNCTIONS_TO_SKIP.contains(&function_to_verify) {
148 continue;
149 }
150 analyze_function(&function_context, meter, &mut verifier, initial_state).map_err(
151 |err| {
152 if check_for_verifier_timeout(&err.major_status()) {
154 to_verification_timeout_error(err.to_string())
155 } else if let Some(message) = err.source().as_ref() {
156 let function_name =
157 module.identifier_at(module.function_handle_at(func_def.function).name);
158 let module_name = module.self_id();
159 verification_failure(format!(
160 "{message} Found in {module_name}::{function_name}"
161 ))
162 } else {
163 verification_failure(err.to_string())
164 }
165 },
166 )?;
167 }
168
169 Ok(())
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub(crate) struct AbstractState {
174 locals: BTreeMap<LocalIndex, AbstractValue>,
175}
176
177impl AbstractState {
178 pub fn new(function_context: &FunctionContext) -> Self {
180 let mut state = AbstractState {
181 locals: BTreeMap::new(),
182 };
183
184 for param_idx in 0..function_context.parameters().len() {
185 state
186 .locals
187 .insert(param_idx as LocalIndex, AbstractValue::Other);
188 }
189
190 state
191 }
192}
193
194impl AbstractDomain for AbstractState {
195 fn join(
197 &mut self,
198 state: &AbstractState,
199 meter: &mut (impl Meter + ?Sized),
200 ) -> Result<JoinResult, PartialVMError> {
201 meter.add(Scope::Function, JOIN_BASE_COST)?;
202 meter.add_items(Scope::Function, JOIN_PER_LOCAL_COST, state.locals.len())?;
203 let mut changed = false;
204 for (local, value) in &state.locals {
205 let old_value = *self.locals.get(local).unwrap_or(&AbstractValue::Other);
206 let new_value = value.join(&old_value);
207 changed |= new_value != old_value;
208 self.locals.insert(*local, new_value);
209 }
210 if changed {
211 Ok(JoinResult::Changed)
212 } else {
213 Ok(JoinResult::Unchanged)
214 }
215 }
216}
217
218struct IDLeakAnalysis<'a> {
219 binary_view: &'a CompiledModule,
220 function_context: &'a FunctionContext<'a>,
221 stack: AbstractStack<AbstractValue>,
222}
223
224impl<'a> IDLeakAnalysis<'a> {
225 fn new(binary_view: &'a CompiledModule, function_context: &'a FunctionContext<'a>) -> Self {
226 Self {
227 binary_view,
228 function_context,
229 stack: AbstractStack::new(),
230 }
231 }
232
233 fn stack_popn(&mut self, n: u64) -> Result<(), PartialVMError> {
234 let Some(n) = NonZeroU64::new(n) else {
235 return Ok(());
236 };
237 self.stack.pop_any_n(n).map_err(|e| {
238 PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION)
239 .with_message(format!("Unexpected stack error on pop_n: {e}"))
240 })
241 }
242
243 fn stack_push(&mut self, val: AbstractValue) -> Result<(), PartialVMError> {
244 self.stack.push(val).map_err(|e| {
245 PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION)
246 .with_message(format!("Unexpected stack error on push: {e}"))
247 })
248 }
249
250 fn stack_pushn(&mut self, n: u64, val: AbstractValue) -> Result<(), PartialVMError> {
251 self.stack.push_n(val, n).map_err(|e| {
252 PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION)
253 .with_message(format!("Unexpected stack error on push_n: {e}"))
254 })
255 }
256
257 fn resolve_function(&self, function_handle: &FunctionHandle) -> FunctionIdent<'a> {
258 let m = self.binary_view.module_handle_at(function_handle.module);
259 let address = self.binary_view.address_identifier_at(m.address);
260 let module = self.binary_view.identifier_at(m.name);
261 let function = self.binary_view.identifier_at(function_handle.name);
262 (address, module, function)
263 }
264
265 fn cur_function(&self) -> FunctionIdent<'a> {
266 let fdef = self
267 .binary_view
268 .function_def_at(self.function_context.index().unwrap());
269 let handle = self.binary_view.function_handle_at(fdef.function);
270 self.resolve_function(handle)
271 }
272}
273
274impl TransferFunctions for IDLeakAnalysis<'_> {
275 type State = AbstractState;
276
277 fn execute(
278 &mut self,
279 state: &mut Self::State,
280 bytecode: &Bytecode,
281 index: CodeOffset,
282 (_first_index, last_index): (u16, u16),
283 meter: &mut (impl Meter + ?Sized),
284 ) -> Result<(), PartialVMError> {
285 execute_inner(self, state, bytecode, index, meter)?;
286 if index == last_index && !self.stack.is_empty() {
290 let msg = "Invalid stack transitions. Non-zero stack size at the end of the block"
291 .to_string();
292 debug_assert!(false, "{msg}",);
293 return Err(
294 PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION).with_message(msg),
295 );
296 }
297 Ok(())
298 }
299}
300
301fn call(
302 verifier: &mut IDLeakAnalysis,
303 function_handle: &FunctionHandle,
304) -> Result<(), PartialVMError> {
305 let parameters = verifier
306 .binary_view
307 .signature_at(function_handle.parameters);
308 verifier.stack_popn(parameters.len() as u64)?;
309
310 let return_ = verifier.binary_view.signature_at(function_handle.return_);
311 let function = verifier.resolve_function(function_handle);
312 if FRESH_ID_FUNCTIONS.contains(&function) {
313 if return_.0.len() != 1 {
314 debug_assert!(false, "{function:?} should have a single return value");
315 return Err(PartialVMError::new(StatusCode::UNKNOWN_VERIFICATION_ERROR)
316 .with_message("Should have a single return value".to_string())
317 .with_sub_status(
318 VMMVerifierErrorSubStatusCode::MULTIPLE_RETURN_VALUES_NOT_ALLOWED as u64,
319 ));
320 }
321 verifier.stack_push(AbstractValue::Fresh)?;
322 } else {
323 verifier.stack_pushn(return_.0.len() as u64, AbstractValue::Other)?;
324 }
325 Ok(())
326}
327
328fn num_fields(struct_def: &StructDefinition) -> u64 {
329 match &struct_def.field_information {
330 StructFieldInformation::Native => 0,
331 StructFieldInformation::Declared(fields) => fields.len() as u64,
332 }
333}
334
335fn pack(
336 verifier: &mut IDLeakAnalysis,
337 struct_def: &StructDefinition,
338) -> Result<(), PartialVMError> {
339 let handle = verifier
343 .binary_view
344 .datatype_handle_at(struct_def.struct_handle);
345 let num_fields = num_fields(struct_def);
346 verifier.stack_popn(num_fields - 1)?;
347 let last_value = verifier.stack.pop().unwrap();
348 if handle.abilities.has_key() && last_value != AbstractValue::Fresh {
349 let (cur_package, cur_module, cur_function) = verifier.cur_function();
350 let msg = format!(
351 "Invalid object creation in {cur_package}::{cur_module}::{cur_function}. \
352 Object created without a newly created UID. \
353 The UID must come directly from iota::{}::{}. \
354 Or for tests, it can come from iota::{}::{}",
355 OBJECT_NEW.1, OBJECT_NEW.2, TS_NEW_OBJECT.1, TS_NEW_OBJECT.2,
356 );
357
358 return Err(PartialVMError::new(StatusCode::UNKNOWN_VERIFICATION_ERROR)
359 .with_message(msg)
360 .with_sub_status(VMMVerifierErrorSubStatusCode::INVALID_OBJECT_CREATION as u64));
361 }
362 verifier.stack_push(AbstractValue::Other)?;
363 Ok(())
364}
365
366fn unpack(
367 verifier: &mut IDLeakAnalysis,
368 struct_def: &StructDefinition,
369) -> Result<(), PartialVMError> {
370 verifier.stack.pop().unwrap();
371 verifier.stack_pushn(num_fields(struct_def), AbstractValue::Other)
372}
373
374fn execute_inner(
375 verifier: &mut IDLeakAnalysis,
376 state: &mut AbstractState,
377 bytecode: &Bytecode,
378 _: CodeOffset,
379 meter: &mut (impl Meter + ?Sized),
380) -> Result<(), PartialVMError> {
381 meter.add(Scope::Function, STEP_BASE_COST)?;
382 match bytecode {
384 Bytecode::Pop => {
385 verifier.stack.pop().unwrap();
386 }
387 Bytecode::CopyLoc(_local) => {
388 verifier.stack_push(AbstractValue::Other)?;
390 }
391 Bytecode::MoveLoc(local) => {
392 let value = state.locals.remove(local).unwrap();
393 verifier.stack_push(value)?;
394 }
395 Bytecode::StLoc(local) => {
396 let value = verifier.stack.pop().unwrap();
397 state.locals.insert(*local, value);
398 }
399
400 Bytecode::FreezeRef
402 | Bytecode::ReadRef
404 | Bytecode::CastU8
406 | Bytecode::CastU16
407 | Bytecode::CastU32
408 | Bytecode::CastU64
409 | Bytecode::CastU128
410 | Bytecode::CastU256
411 | Bytecode::Not
412 | Bytecode::VecLen(_)
413 | Bytecode::VecPopBack(_) => {
414 verifier.stack.pop().unwrap();
415 verifier.stack_push(AbstractValue::Other)?;
416 }
417
418 Bytecode::Branch(_)
420 | Bytecode::Nop => {}
421
422 Bytecode::Eq
424 | Bytecode::Neq
425 | Bytecode::Add
426 | Bytecode::Sub
427 | Bytecode::Mul
428 | Bytecode::Mod
429 | Bytecode::Div
430 | Bytecode::BitOr
431 | Bytecode::BitAnd
432 | Bytecode::Xor
433 | Bytecode::Shl
434 | Bytecode::Shr
435 | Bytecode::Or
436 | Bytecode::And
437 | Bytecode::Lt
438 | Bytecode::Gt
439 | Bytecode::Le
440 | Bytecode::Ge
441 | Bytecode::VecImmBorrow(_)
442 | Bytecode::VecMutBorrow(_) => {
443 verifier.stack.pop().unwrap();
444 verifier.stack.pop().unwrap();
445 verifier.stack_push(AbstractValue::Other)?;
446 }
447 Bytecode::WriteRef => {
448 verifier.stack.pop().unwrap();
449 verifier.stack.pop().unwrap();
450 }
451
452 Bytecode::MutBorrowLoc(_)
454 | Bytecode::ImmBorrowLoc(_) => verifier.stack_push(AbstractValue::Other)?,
455
456 | Bytecode::MutBorrowField(_)
457 | Bytecode::MutBorrowFieldGeneric(_)
458 | Bytecode::ImmBorrowField(_)
459 | Bytecode::ImmBorrowFieldGeneric(_) => {
460 verifier.stack.pop().unwrap();
461 verifier.stack_push(AbstractValue::Other)?;
462 }
463
464 Bytecode::MoveFromDeprecated(_)
467 | Bytecode::MoveFromGenericDeprecated(_)
468 | Bytecode::MoveToDeprecated(_)
469 | Bytecode::MoveToGenericDeprecated(_)
470 | Bytecode::ImmBorrowGlobalDeprecated(_)
471 | Bytecode::MutBorrowGlobalDeprecated(_)
472 | Bytecode::ImmBorrowGlobalGenericDeprecated(_)
473 | Bytecode::MutBorrowGlobalGenericDeprecated(_)
474 | Bytecode::ExistsDeprecated(_)
475 | Bytecode::ExistsGenericDeprecated(_) => {
476 panic!("Should have been checked by global_storage_access_verifier.");
477 }
478
479 Bytecode::Call(idx) => {
480 let function_handle = verifier.binary_view.function_handle_at(*idx);
481 call(verifier, function_handle)?;
482 }
483 Bytecode::CallGeneric(idx) => {
484 let func_inst = verifier.binary_view.function_instantiation_at(*idx);
485 let function_handle = verifier.binary_view.function_handle_at(func_inst.handle);
486 call(verifier, function_handle)?;
487 }
488
489 Bytecode::Ret => {
490 verifier.stack_popn(verifier.function_context.return_().len() as u64)?
491 }
492
493 Bytecode::BrTrue(_) | Bytecode::BrFalse(_) | Bytecode::Abort => {
494 verifier.stack.pop().unwrap();
495 }
496
497 Bytecode::LdTrue | Bytecode::LdFalse | Bytecode::LdU8(_) | Bytecode::LdU16(_)| Bytecode::LdU32(_) | Bytecode::LdU64(_) | Bytecode::LdU128(_)| Bytecode::LdU256(_) | Bytecode::LdConst(_) => {
499 verifier.stack_push(AbstractValue::Other)?;
500 }
501
502 Bytecode::Pack(idx) => {
503 let struct_def = verifier.binary_view.struct_def_at(*idx);
504 pack(verifier, struct_def)?;
505 }
506 Bytecode::PackGeneric(idx) => {
507 let struct_inst = verifier.binary_view.struct_instantiation_at(*idx);
508 let struct_def = verifier.binary_view.struct_def_at(struct_inst.def);
509 pack(verifier, struct_def)?;
510 }
511 Bytecode::Unpack(idx) => {
512 let struct_def = verifier.binary_view.struct_def_at(*idx);
513 unpack(verifier, struct_def)?;
514 }
515 Bytecode::UnpackGeneric(idx) => {
516 let struct_inst = verifier.binary_view.struct_instantiation_at(*idx);
517 let struct_def = verifier.binary_view.struct_def_at(struct_inst.def);
518 unpack(verifier, struct_def)?;
519 }
520
521 Bytecode::VecPack(_, num) => {
522 verifier.stack_popn(*num )?;
523 verifier.stack_push(AbstractValue::Other)?;
524 }
525
526 Bytecode::VecPushBack(_) => {
527 verifier.stack.pop().unwrap();
528 verifier.stack.pop().unwrap();
529 }
530
531 Bytecode::VecUnpack(_, num) => {
532 verifier.stack.pop().unwrap();
533 verifier.stack_pushn(*num, AbstractValue::Other)?;
534 }
535
536 Bytecode::VecSwap(_) => {
537 verifier.stack.pop().unwrap();
538 verifier.stack.pop().unwrap();
539 verifier.stack.pop().unwrap();
540 }
541 Bytecode::PackVariant(vidx) => {
542 let handle = verifier.binary_view.variant_handle_at(*vidx);
543 let variant = verifier.binary_view.variant_def_at(handle.enum_def, handle.variant);
544 let num_fields = variant.fields.len();
545 verifier.stack_popn(num_fields as u64)?;
546 verifier.stack_push(AbstractValue::Other)?;
547 }
548 Bytecode::PackVariantGeneric(vidx) => {
549 let handle = verifier.binary_view.variant_instantiation_handle_at(*vidx);
550 let enum_inst = verifier.binary_view.enum_instantiation_at(handle.enum_def);
551 let variant = verifier.binary_view.variant_def_at(enum_inst.def, handle.variant);
552 let num_fields = variant.fields.len();
553 verifier.stack_popn(num_fields as u64)?;
554 verifier.stack_push(AbstractValue::Other)?;
555 }
556 Bytecode::UnpackVariant(vidx)
557 | Bytecode::UnpackVariantImmRef(vidx)
558 | Bytecode::UnpackVariantMutRef(vidx) => {
559 let handle = verifier.binary_view.variant_handle_at(*vidx);
560 let variant = verifier.binary_view.variant_def_at(handle.enum_def, handle.variant);
561 let num_fields = variant.fields.len();
562 verifier.stack.pop().unwrap();
563 verifier.stack_pushn(num_fields as u64, AbstractValue::Other)?;
564 }
565 Bytecode::UnpackVariantGeneric(vidx)
566 | Bytecode::UnpackVariantGenericImmRef(vidx)
567 | Bytecode::UnpackVariantGenericMutRef(vidx) => {
568 let handle = verifier.binary_view.variant_instantiation_handle_at(*vidx);
569 let enum_inst = verifier.binary_view.enum_instantiation_at(handle.enum_def);
570 let variant = verifier.binary_view.variant_def_at(enum_inst.def, handle.variant);
571 let num_fields = variant.fields.len();
572 verifier.stack.pop().unwrap();
573 verifier.stack_pushn(num_fields as u64, AbstractValue::Other)?;
574 }
575 Bytecode::VariantSwitch(_) => {
576 verifier.stack.pop().unwrap();
577 }
578 };
579 Ok(())
580}