diff --git a/crates/e2e-move-tests/src/tests/args.rs b/crates/e2e-move-tests/src/tests/args.rs index 8ad61eb2..3a6eab77 100644 --- a/crates/e2e-move-tests/src/tests/args.rs +++ b/crates/e2e-move-tests/src/tests/args.rs @@ -27,7 +27,9 @@ fn success_generic(ty_args: Vec, tests: Vec) { h.initialize(); // publish package - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); // Check in initial state, resource does not exist. @@ -75,7 +77,9 @@ fn fail_generic(ty_args: Vec, tests: Vec<(&str, Vec>, StatusCod h.initialize(); // publish package - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); // Check in initial state, resource does not exist. @@ -750,7 +754,9 @@ fn json_object_args() { h.initialize(); // publish package - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); // execute create_object @@ -795,7 +801,9 @@ fn biguint_bigdecimal() { h.initialize(); // publish package - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); // execute create_object diff --git a/crates/e2e-move-tests/src/tests/code.rs b/crates/e2e-move-tests/src/tests/code.rs index eb51e068..dd06c51d 100644 --- a/crates/e2e-move-tests/src/tests/code.rs +++ b/crates/e2e-move-tests/src/tests/code.rs @@ -9,17 +9,20 @@ fn setup_harness() -> (MoveHarness, AccountAddress) { (h, acc) } -fn publish_and_commit(h: &mut MoveHarness, acc: &AccountAddress, path: &str, policy: UpgradePolicy) { - let output = h.publish_package(acc, path, policy).expect("should succeed"); +fn publish_and_commit( + h: &mut MoveHarness, + acc: &AccountAddress, + path: &str, + policy: UpgradePolicy, +) { + let output = h + .publish_package(acc, path, policy) + .expect("should succeed"); h.commit(output, true); } fn view_string(h: &mut MoveHarness, path: &str) -> String { - let view_function = h.create_view_function( - str::parse(path).unwrap(), - vec![], - vec![], - ); + let view_function = h.create_view_function(str::parse(path).unwrap(), vec![], vec![]); h.run_view_function(view_function).expect("should succeed") } @@ -27,12 +30,22 @@ fn view_string(h: &mut MoveHarness, path: &str) -> String { #[test] fn test_simple_publish_compatible() { let (mut h, acc) = setup_harness(); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer", UpgradePolicy::Compatible); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer", + UpgradePolicy::Compatible, + ); let view_output = view_string(&mut h, "0x9999::string_viewer::view_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer2", UpgradePolicy::Compatible); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer2", + UpgradePolicy::Compatible, + ); let view_output = view_string(&mut h, "0x9999::string_viewer2::view_my_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); @@ -41,12 +54,22 @@ fn test_simple_publish_compatible() { #[test] fn test_simple_publish_immutable() { let (mut h, acc) = setup_harness(); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer", UpgradePolicy::Immutable); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer", + UpgradePolicy::Immutable, + ); let view_output = view_string(&mut h, "0x9999::string_viewer::view_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer2", UpgradePolicy::Immutable); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer2", + UpgradePolicy::Immutable, + ); let view_output = view_string(&mut h, "0x9999::string_viewer2::view_my_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); @@ -55,24 +78,40 @@ fn test_simple_publish_immutable() { #[test] fn test_publish_immutable_referring_compatible() { let (mut h, acc) = setup_harness(); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer", UpgradePolicy::Compatible); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer", + UpgradePolicy::Compatible, + ); let view_output = view_string(&mut h, "0x9999::string_viewer::view_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); let path = "src/tests/string_viewer.data/viewer2"; - h.publish_package(&acc, path, UpgradePolicy::Immutable).expect_err("expected an error during package publishing"); + h.publish_package(&acc, path, UpgradePolicy::Immutable) + .expect_err("expected an error during package publishing"); } #[test] fn test_publish_compatible_referring_immutable() { let (mut h, acc) = setup_harness(); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer", UpgradePolicy::Immutable); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer", + UpgradePolicy::Immutable, + ); let view_output = view_string(&mut h, "0x9999::string_viewer::view_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); - publish_and_commit(&mut h, &acc, "src/tests/string_viewer.data/viewer2", UpgradePolicy::Compatible); + publish_and_commit( + &mut h, + &acc, + "src/tests/string_viewer.data/viewer2", + UpgradePolicy::Compatible, + ); let view_output = view_string(&mut h, "0x9999::string_viewer2::view_my_string"); assert_eq!("\"Hello, World!\"".to_string(), view_output); diff --git a/crates/e2e-move-tests/src/tests/cosmos.rs b/crates/e2e-move-tests/src/tests/cosmos.rs index ecc733ab..8a482104 100644 --- a/crates/e2e-move-tests/src/tests/cosmos.rs +++ b/crates/e2e-move-tests/src/tests/cosmos.rs @@ -63,7 +63,9 @@ fn run_tests(tests: Vec) { h.initialize(); // publish package - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); for (sender, entry, ty_args, args, exp_output) in tests { diff --git a/crates/e2e-move-tests/src/tests/infinite_loop.rs b/crates/e2e-move-tests/src/tests/infinite_loop.rs index 427e0694..b703a065 100644 --- a/crates/e2e-move-tests/src/tests/infinite_loop.rs +++ b/crates/e2e-move-tests/src/tests/infinite_loop.rs @@ -13,7 +13,9 @@ fn empty_while_loop() { h.initialize(); - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); let err = h diff --git a/crates/e2e-move-tests/src/tests/max_loop_depth.rs b/crates/e2e-move-tests/src/tests/max_loop_depth.rs index 6c4b160f..629093f5 100644 --- a/crates/e2e-move-tests/src/tests/max_loop_depth.rs +++ b/crates/e2e-move-tests/src/tests/max_loop_depth.rs @@ -9,7 +9,9 @@ fn module_loop_depth_at_limit() { let mut h = MoveHarness::new(); h.initialize(); - let _ = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let _ = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); } #[test] @@ -18,6 +20,8 @@ fn module_loop_depth_just_above_limit() { let path = "src/tests/max_loop_depth.data/pack-bad"; let mut h = MoveHarness::new(); h.initialize(); - let status = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect_err("should error"); + let status = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect_err("should error"); assert!(status.status_code() == StatusCode::LOOP_MAX_DEPTH_REACHED); } diff --git a/crates/e2e-move-tests/src/tests/memory_quota.rs b/crates/e2e-move-tests/src/tests/memory_quota.rs index f78b1dd8..b1ac3d95 100644 --- a/crates/e2e-move-tests/src/tests/memory_quota.rs +++ b/crates/e2e-move-tests/src/tests/memory_quota.rs @@ -10,7 +10,9 @@ fn clone_large_vectors() { let mut h = MoveHarness::new(); h.initialize(); - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); let _ = h @@ -42,7 +44,9 @@ fn add_vec_to_table() { // Load the code h.initialize(); - let output = h.publish_package(&acc, path, UpgradePolicy::Compatible).expect("should success"); + let output = h + .publish_package(&acc, path, UpgradePolicy::Compatible) + .expect("should success"); h.commit(output, true); let status = h diff --git a/crates/json/src/json_to_move.rs b/crates/json/src/json_to_move.rs index 0eaeeb1c..c4609b17 100644 --- a/crates/json/src/json_to_move.rs +++ b/crates/json/src/json_to_move.rs @@ -34,11 +34,8 @@ pub trait StructResolver { index: StructNameIndex, module_storage: &impl ModuleStorage, ) -> Option>; - fn type_to_type_tag( - &self, - ty: &Type, - module_storage: &impl ModuleStorage, - ) -> VMResult; + fn type_to_type_tag(&self, ty: &Type, module_storage: &impl ModuleStorage) + -> VMResult; } // deserialize json argument to JSONValue and convert to MoveValue, @@ -395,7 +392,8 @@ mod json_arg_testing { Struct { idx, .. } => { let struct_ty = self.get_struct_type(*idx, module_storage).ok_or_else(|| { - PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR).finish(Location::Undefined) + PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR) + .finish(Location::Undefined) })?; Ok(TypeTag::Struct(Box::new(StructTag { address: struct_ty.module.address, @@ -404,7 +402,9 @@ mod json_arg_testing { type_args: vec![], }))) } - _ => Err(PartialVMError::new(StatusCode::TYPE_MISMATCH).finish(Location::Undefined)), + _ => { + Err(PartialVMError::new(StatusCode::TYPE_MISMATCH).finish(Location::Undefined)) + } } } } diff --git a/crates/natives/src/code.rs b/crates/natives/src/code.rs index d3b153c5..8c764ccc 100644 --- a/crates/natives/src/code.rs +++ b/crates/natives/src/code.rs @@ -128,8 +128,11 @@ fn native_request_publish( context.charge(gas_params.code_request_publish_base_cost)?; - let upgrade_policy = UpgradePolicy::try_from(safely_pop_arg!(arguments, u8)) - .map_err(|_| SafeNativeError::Abort { abort_code: EINVALID_UPGRADE_POLICY})?; + let upgrade_policy = UpgradePolicy::try_from(safely_pop_arg!(arguments, u8)).map_err(|_| { + SafeNativeError::Abort { + abort_code: EINVALID_UPGRADE_POLICY, + } + })?; let mut code: Vec> = vec![]; for module_code in safely_pop_vec_arg!(arguments, Vec) { diff --git a/crates/storage/src/code_scale.rs b/crates/storage/src/code_scale.rs index e3292845..382ac6ea 100644 --- a/crates/storage/src/code_scale.rs +++ b/crates/storage/src/code_scale.rs @@ -1,7 +1,6 @@ +use clru::WeightScale; use std::sync::Arc; -use clru::WeightScale; -use get_size::GetSize; use move_binary_format::file_format::CompiledScript; use move_binary_format::CompiledModule; use move_vm_runtime::Module; @@ -10,75 +9,13 @@ use move_vm_types::code::{Code, ModuleCode}; use crate::module_cache::BytesWithHash; use crate::module_cache::NoVersion; -use crate::move_core_type::code::Code as MyCode; -use crate::move_core_type::code::ModuleCode as MyModuleCode; -use crate::move_core_type::file_format::CompiledScript as MyCompiledScript; -use crate::move_core_type::script::Script as MyScript; - -use crate::move_core_type::file_format::CompiledModule as MyCompiledModule; -use crate::move_core_type::modules::Module as MyModule; use crate::state_view::Checksum; -#[cfg(any(test, feature = "testing"))] -use pretty_assertions::assert_eq; -#[cfg(any(test, feature = "testing"))] -use move_vm_types::code::{WithBytes, WithHash}; - pub struct CodeScale; -unsafe fn convert_to_my_code( - code: &Code, -) -> &MyCode { - let my_code = &*(code as *const Code - as *const MyCode); - #[cfg(any(test, feature = "testing"))] - { - match &my_code { - MyCode::Deserialized(compiled_script) => { - assert_eq!(format!("{:?}", code.deserialized().as_ref()), format!("{:?}", compiled_script.as_ref())); - } - MyCode::Verified(script) => { - assert_eq!(format!("{:?}", code.verified().as_ref()), format!("{:?}", script.as_ref())); - } - }; - } - my_code -} - -unsafe fn convert_to_my_module_code( - code: &ModuleCode, -) -> &MyModuleCode { - let my_module_code = &*(code as *const ModuleCode - as *const MyModuleCode); - #[cfg(any(test, feature = "testing"))] - { - assert_eq!(*my_module_code.extension.bytes(), code.extension().bytes()); - assert_eq!(*my_module_code.extension.hash(), *code.extension().hash()); - assert_eq!(my_module_code.version, code.version()); - - match &my_module_code.code { - MyCode::Deserialized(compiled_module) => { - assert_eq!(format!("{:?}", code.code().deserialized().as_ref()), format!("{:?}", compiled_module.as_ref())); - } - MyCode::Verified(module) => { - assert_eq!(format!("{:?}", code.code().verified().as_ref()), format!("{:?}", module.as_ref())); - } - }; - } - my_module_code -} - impl WeightScale> for CodeScale { - fn weight(&self, _key: &Checksum, value: &Code) -> usize { - unsafe { - let converted_value = convert_to_my_code(value); - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| converted_value.get_size())) - .unwrap_or_else(|_| { - eprintln!("Failed to convert script code to custom code"); - // If the conversion fails, return a temporary value - 1024 * 1024 - }) - } + fn weight(&self, _key: &Checksum, _value: &Code) -> usize { + 1 } } @@ -90,231 +27,8 @@ impl WeightScale>, + _value: &Arc>, ) -> usize { - unsafe { - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {convert_to_my_module_code(value).get_size()})) - .unwrap_or_else(|_| { - eprintln!("Failed to convert module code to custom code"); - // If the conversion fails, return a temporary value - 1024 * 1024 - }) - } + 1 } } - -#[cfg(test)] -mod test { - use core::panic; - use std::str::FromStr; - use std::sync::Arc; - - use move_binary_format::file_format::{basic_test_module, empty_script_with_dependencies}; - use move_core_types::account_address::AccountAddress; - use move_core_types::identifier::Identifier; - use move_core_types::language_storage::ModuleId; - use move_vm_runtime::{CodeStorage, ModuleStorage, RuntimeEnvironment}; - use move_vm_types::{code::{Code, ModuleCode, WithBytes, WithHash}, sha3_256}; - - use crate::code_storage::test::make_script; - use crate::code_storage::AsInitiaCodeStorage; - use crate::memory_module_storage::InMemoryStorage; - use crate::module_cache::{BytesWithHash, InitiaModuleCache, NoVersion}; - use crate::module_storage::test::{add_module_bytes, TEST_CACHE_CAPACITY}; - use crate::module_storage::AsInitiaModuleStorage; - use crate::move_core_type::code::Code as MyCode; - use crate::move_core_type::file_format::{AbilitySet, AddressIdentifierIndex, Bytecode, CodeUnit, FieldDefinition, FunctionDefinition, FunctionHandle, FunctionHandleIndex, IdentifierIndex, ModuleHandle, ModuleHandleIndex, SignatureIndex, SignatureToken, StructDefinition, StructFieldInformation, StructHandle, StructHandleIndex, TableIndex, TypeSignature, Visibility}; - use crate::move_core_type::move_core_type::{AccountAddress as MyAccountAddress, Identifier as MyIdentifier}; - use crate::script_cache::InitiaScriptCache; - - use pretty_assertions::assert_eq; - - #[test] - fn test_compiled_module_convert_to_my_module_code() { - let version = NoVersion{}; - let extension = Arc::new(BytesWithHash::new(vec![1, 2, 3].into(), [1u8; 32])); - let module_code = ModuleCode::from_deserialized(basic_test_module(), extension, version); - let my_module_code = unsafe { super::convert_to_my_module_code(&module_code) }; - - match &my_module_code.code { - MyCode::Deserialized(compiled_module) => { - assert_eq!(compiled_module.function_handles.len(), 1); - assert_eq!(*compiled_module.function_handles.get(0).unwrap(), FunctionHandle { - module: ModuleHandleIndex(0), - name: IdentifierIndex(1), - parameters: SignatureIndex(0), - return_: SignatureIndex(0), - type_parameters: vec![], - access_specifiers: None, - }); - - assert_eq!(compiled_module.identifiers.len(), 4); - assert_eq!(*compiled_module.identifiers.get(1).unwrap(), MyIdentifier::from_str("foo").unwrap()); - assert_eq!(*compiled_module.identifiers.get(2).unwrap(), MyIdentifier::from_str("Bar").unwrap()); - assert_eq!(*compiled_module.identifiers.get(3).unwrap(), MyIdentifier::from_str("x").unwrap()); - - assert_eq!(compiled_module.function_defs.len(), 1); - assert_eq!(*compiled_module.function_defs.get(0).unwrap(), FunctionDefinition { - function: FunctionHandleIndex(0), - visibility: Visibility::Private, - is_entry: false, - acquires_global_resources: vec![], - code: Some(CodeUnit { - locals: SignatureIndex(0), - code: vec![Bytecode::Ret], - }), - }); - - assert_eq!(compiled_module.struct_handles.len(), 1); - assert_eq!(*compiled_module.struct_handles.get(0).unwrap(), StructHandle { - module: ModuleHandleIndex(0), - name: IdentifierIndex(2), - abilities: AbilitySet(0), - type_parameters: vec![], - }); - - assert_eq!(compiled_module.struct_defs.len(), 1); - assert_eq!(*compiled_module.struct_defs.get(0).unwrap(), StructDefinition { - struct_handle: StructHandleIndex(0), - field_information: StructFieldInformation::Declared(vec![FieldDefinition { - name: IdentifierIndex(3), - signature: TypeSignature(SignatureToken::U64), - }]), - }); - } - MyCode::Verified(_) => { - panic!("Expected deserialized code"); - } - } - } - - #[test] - fn test_convert_to_my_code() { - let code = Code::from_deserialized(empty_script_with_dependencies(vec!["a", "b", "c"])); - let my_code = unsafe { super::convert_to_my_code(&code) }; - - match &my_code { - MyCode::Deserialized(compiled_script) => { - assert_eq!(compiled_script.code, CodeUnit{ - locals: SignatureIndex(0), - code: vec![Bytecode::Ret], - }); - - assert_eq!(compiled_script.address_identifiers.len(), 1); - assert_eq!(*compiled_script.address_identifiers.get(0).unwrap(), MyAccountAddress([0u8; 32])); - - assert_eq!(compiled_script.identifiers.len(), 3); - assert_eq!(*compiled_script.identifiers.get(0).unwrap(), MyIdentifier::from_str("a").unwrap()); - assert_eq!(*compiled_script.identifiers.get(1).unwrap(), MyIdentifier::from_str("b").unwrap()); - assert_eq!(*compiled_script.identifiers.get(2).unwrap(), MyIdentifier::from_str("c").unwrap()); - - assert_eq!(compiled_script.module_handles.len(), 3); - assert_eq!(*compiled_script.module_handles.get(0).unwrap(), ModuleHandle { - address: AddressIdentifierIndex(0), - name: IdentifierIndex(0 as TableIndex), - }); - assert_eq!(*compiled_script.module_handles.get(1).unwrap(), ModuleHandle { - address: AddressIdentifierIndex(0), - name: IdentifierIndex(1 as TableIndex), - }); - assert_eq!(*compiled_script.module_handles.get(2).unwrap(), ModuleHandle { - address: AddressIdentifierIndex(0), - name: IdentifierIndex(2 as TableIndex), - }); - } - MyCode::Verified(_) => { - panic!("Expected deserialized code") - } - } - } - - #[test] - fn test_module_convert_to_my_module_code() { - let mut module_bytes_storage = InMemoryStorage::new(); - let module_cache = InitiaModuleCache::new(TEST_CACHE_CAPACITY); - - let a_id = ModuleId::new(AccountAddress::ZERO, Identifier::new("a").unwrap()); - ModuleId::new(AccountAddress::ZERO, Identifier::new("b").unwrap()); - ModuleId::new(AccountAddress::ZERO, Identifier::new("c").unwrap()); - - add_module_bytes(&mut module_bytes_storage, "a", vec!["b"], vec!["d"]); - add_module_bytes(&mut module_bytes_storage, "b", vec!["c"], vec![]); - add_module_bytes(&mut module_bytes_storage, "c", vec![], vec![]); - add_module_bytes(&mut module_bytes_storage, "d", vec![], vec!["c"]); - - let runtime_environment = RuntimeEnvironment::new(vec![]); - let module_storage = - module_bytes_storage.into_initia_module_storage(&runtime_environment, module_cache); - - let module = module_storage.fetch_verified_module(a_id.address(), a_id.name()).unwrap().unwrap(); - let module_code = ModuleCode::from_verified(module.as_ref().clone(), Arc::new(BytesWithHash::new(vec![1, 2, 3].into(), [1u8; 32])), NoVersion{}); - let my_module_code = unsafe { super::convert_to_my_module_code(&module_code) }; - - assert_eq!(my_module_code.extension.bytes().to_vec(), vec![1, 2, 3]); - assert_eq!(*my_module_code.extension.hash(), [1u8; 32]); - assert_eq!(my_module_code.version, NoVersion{}); - - let converted_module = match &my_module_code.code { - MyCode::Deserialized(_) => panic!("Expected verified code"), - MyCode::Verified(code) => code - }; - - assert_eq!(format!("{:?}", module.as_ref()), format!("{:?}", converted_module.as_ref())); - } - - #[test] - fn test_script_convert_to_my_code() { - let mut module_bytes_storage = InMemoryStorage::new(); - let module_cache = InitiaModuleCache::new(TEST_CACHE_CAPACITY); - let script_cache = InitiaScriptCache::new(TEST_CACHE_CAPACITY); - - ModuleId::new(AccountAddress::ZERO, Identifier::new("a").unwrap()); - ModuleId::new(AccountAddress::ZERO, Identifier::new("b").unwrap()); - ModuleId::new(AccountAddress::ZERO, Identifier::new("c").unwrap()); - - add_module_bytes(&mut module_bytes_storage, "a", vec!["b", "c"], vec![]); - add_module_bytes(&mut module_bytes_storage, "b", vec![], vec![]); - add_module_bytes(&mut module_bytes_storage, "c", vec![], vec![]); - - let runtime_environment = RuntimeEnvironment::new(vec![]); - let code_storage = module_bytes_storage.into_initia_code_storage( - &runtime_environment, - script_cache, - module_cache, - ); - - let serialized_script = make_script(vec!["a"]); - sha3_256(&serialized_script); - code_storage.deserialize_and_cache_script(&serialized_script).unwrap(); - let script = code_storage.verify_and_cache_script(&serialized_script).unwrap(); - - let script_code = Code::from_verified(script.as_ref().clone()); - let my_script_code = unsafe { super::convert_to_my_code(&script_code) }; - - let converted_script = match my_script_code { - MyCode::Deserialized(_) => panic!("Expected verified code"), - MyCode::Verified(code) => { - code - } - }; - assert_eq!(format!("{:?}", script.as_ref()), format!("{:?}", converted_script.as_ref())); - } - - // #[test] - // fn test_panic_on_conversion_failure() { - // let code = unsafe { - // let mut script = empty_script(); - // std::ptr::write_bytes(&mut script, 0, 10); - // Code::Deserialized(Arc::new(script)) - // }; - - // let script_cache = InitiaScriptCache::new(TEST_CACHE_CAPACITY); - // let mut cache = script_cache.script_cache.lock(); - - // assert_eq!(cache.weight(), 0); - // if cache.put_with_weight([0u8; 32], code).is_err() { - // panic!("Failed to put code in cache"); - // } - // assert_eq!(cache.weight(), 1024*1024); - // } -} \ No newline at end of file diff --git a/crates/storage/src/code_storage.rs b/crates/storage/src/code_storage.rs index 415d5d3e..0dfe76d1 100644 --- a/crates/storage/src/code_storage.rs +++ b/crates/storage/src/code_storage.rs @@ -12,8 +12,7 @@ use move_vm_runtime::{ }; use move_vm_types::{ code::{Code, ModuleBytesStorage}, - module_linker_error, - sha3_256 + module_linker_error, sha3_256, }; use std::sync::Arc; diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 31a8508b..f02a8b72 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -10,5 +10,3 @@ pub mod module_storage; pub mod script_cache; pub mod code_scale; - -mod move_core_type; diff --git a/crates/storage/src/memory_module_storage.rs b/crates/storage/src/memory_module_storage.rs index c09ad579..aea0fa92 100644 --- a/crates/storage/src/memory_module_storage.rs +++ b/crates/storage/src/memory_module_storage.rs @@ -22,7 +22,7 @@ use move_core_types::{ use move_vm_types::{ code::ModuleBytesStorage, resolver::{resource_size, ModuleResolver, ResourceResolver}, - sha3_256 + sha3_256, }; use std::{ collections::{btree_map, BTreeMap}, diff --git a/crates/storage/src/module_cache.rs b/crates/storage/src/module_cache.rs index b147e954..c0924e58 100644 --- a/crates/storage/src/module_cache.rs +++ b/crates/storage/src/module_cache.rs @@ -14,9 +14,9 @@ use parking_lot::Mutex; use crate::{code_scale::ModuleCodeScale, state_view::Checksum}; -fn handle_cache_error(module_id: ModuleId) -> VMError { - PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) - .with_message("Module storage cache eviction error".to_string()) +fn handle_cache_error(module_id: ModuleId) -> VMError { + PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) + .with_message("Module storage cache eviction error".to_string()) .finish(Location::Module(module_id)) } @@ -59,6 +59,7 @@ impl WithHash for BytesWithHash { pub struct NoVersion; pub struct InitiaModuleCache { + #[allow(clippy::type_complexity)] pub(crate) module_cache: Mutex< CLruCache< Checksum, @@ -71,11 +72,10 @@ pub struct InitiaModuleCache { impl InitiaModuleCache { pub fn new(cache_capacity: usize) -> Arc { - let capacity = NonZeroUsize::new(cache_capacity.saturating_mul(1024 * 1024)).unwrap(); + let capacity = NonZeroUsize::new(cache_capacity).unwrap(); Arc::new(InitiaModuleCache { module_cache: Mutex::new(CLruCache::with_config( - CLruCacheConfig::new(capacity) - .with_scale(ModuleCodeScale), + CLruCacheConfig::new(capacity).with_scale(ModuleCodeScale), )), }) } @@ -145,6 +145,7 @@ impl InitiaModuleCache { } } + #[allow(clippy::type_complexity)] pub(crate) fn get_module_or_build_with( &self, id: &ModuleId, diff --git a/crates/storage/src/move_core_type/code.rs b/crates/storage/src/move_core_type/code.rs deleted file mode 100644 index 6583a9f9..00000000 --- a/crates/storage/src/move_core_type/code.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::sync::Arc; - -use get_size::GetSize; - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum Code { - /// Deserialized code, not yet verified with bytecode verifier. - Deserialized(Arc), - /// Fully-verified code. - Verified(Arc), -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct ModuleCode { - /// Module's code, either deserialized or verified. - pub code: Code, - /// Module's extension - any additional metadata associated with this module. - pub extension: Arc, - /// Version of the code (e.g., which transaction within the block published this module). - pub version: V, -} diff --git a/crates/storage/src/move_core_type/file_format.rs b/crates/storage/src/move_core_type/file_format.rs deleted file mode 100644 index ce16d578..00000000 --- a/crates/storage/src/move_core_type/file_format.rs +++ /dev/null @@ -1,852 +0,0 @@ -use std::fmt; - -use super::move_core_type::{AccountAddress, Identifier, Metadata}; -use get_size::GetSize; -use primitive_types::U256 as PrimitiveU256; - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq)] -pub enum Bytecode { - Pop, - Ret, - BrTrue(CodeOffset), - BrFalse(CodeOffset), - Branch(CodeOffset), - LdU8(u8), - LdU64(u64), - LdU128(u128), - CastU8, - CastU64, - CastU128, - LdConst(ConstantPoolIndex), - LdTrue, - LdFalse, - CopyLoc(LocalIndex), - MoveLoc(LocalIndex), - StLoc(LocalIndex), - Call(FunctionHandleIndex), - CallGeneric(FunctionInstantiationIndex), - Pack(StructDefinitionIndex), - PackGeneric(StructDefInstantiationIndex), - PackVariant(StructVariantHandleIndex), - PackVariantGeneric(StructVariantInstantiationIndex), - Unpack(StructDefinitionIndex), - UnpackGeneric(StructDefInstantiationIndex), - UnpackVariant(StructVariantHandleIndex), - UnpackVariantGeneric(StructVariantInstantiationIndex), - TestVariant(StructVariantHandleIndex), - TestVariantGeneric(StructVariantInstantiationIndex), - ReadRef, - WriteRef, - FreezeRef, - MutBorrowLoc(LocalIndex), - ImmBorrowLoc(LocalIndex), - MutBorrowField(FieldHandleIndex), - MutBorrowVariantField(VariantFieldHandleIndex), - MutBorrowFieldGeneric(FieldInstantiationIndex), - MutBorrowVariantFieldGeneric(VariantFieldInstantiationIndex), - ImmBorrowField(FieldHandleIndex), - ImmBorrowVariantField(VariantFieldHandleIndex), - ImmBorrowFieldGeneric(FieldInstantiationIndex), - ImmBorrowVariantFieldGeneric(VariantFieldInstantiationIndex), - MutBorrowGlobal(StructDefinitionIndex), - MutBorrowGlobalGeneric(StructDefInstantiationIndex), - ImmBorrowGlobal(StructDefinitionIndex), - ImmBorrowGlobalGeneric(StructDefInstantiationIndex), - Add, - Sub, - Mul, - Mod, - Div, - BitOr, - BitAnd, - Xor, - Or, - And, - Not, - Eq, - Neq, - Lt, - Gt, - Le, - Ge, - Abort, - Nop, - Exists(StructDefinitionIndex), - ExistsGeneric(StructDefInstantiationIndex), - MoveFrom(StructDefinitionIndex), - MoveFromGeneric(StructDefInstantiationIndex), - MoveTo(StructDefinitionIndex), - MoveToGeneric(StructDefInstantiationIndex), - Shl, - Shr, - VecPack(SignatureIndex, u64), - VecLen(SignatureIndex), - VecImmBorrow(SignatureIndex), - VecMutBorrow(SignatureIndex), - VecPushBack(SignatureIndex), - VecPopBack(SignatureIndex), - VecUnpack(SignatureIndex, u64), - VecSwap(SignatureIndex), - LdU16(u16), - LdU32(u32), - LdU256(U256), - CastU16, - CastU32, - CastU256, -} - -impl ::std::fmt::Debug for Bytecode { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match self { - Bytecode::Pop => write!(f, "Pop"), - Bytecode::Ret => write!(f, "Ret"), - Bytecode::BrTrue(a) => write!(f, "BrTrue({})", a), - Bytecode::BrFalse(a) => write!(f, "BrFalse({})", a), - Bytecode::Branch(a) => write!(f, "Branch({})", a), - Bytecode::LdU8(a) => write!(f, "LdU8({})", a), - Bytecode::LdU16(a) => write!(f, "LdU16({})", a), - Bytecode::LdU32(a) => write!(f, "LdU32({})", a), - Bytecode::LdU64(a) => write!(f, "LdU64({})", a), - Bytecode::LdU128(a) => write!(f, "LdU128({})", a), - Bytecode::LdU256(a) => write!(f, "LdU256({})", a), - Bytecode::CastU8 => write!(f, "CastU8"), - Bytecode::CastU16 => write!(f, "CastU16"), - Bytecode::CastU32 => write!(f, "CastU32"), - Bytecode::CastU64 => write!(f, "CastU64"), - Bytecode::CastU128 => write!(f, "CastU128"), - Bytecode::CastU256 => write!(f, "CastU256"), - Bytecode::LdConst(a) => write!(f, "LdConst({})", a), - Bytecode::LdTrue => write!(f, "LdTrue"), - Bytecode::LdFalse => write!(f, "LdFalse"), - Bytecode::CopyLoc(a) => write!(f, "CopyLoc({})", a), - Bytecode::MoveLoc(a) => write!(f, "MoveLoc({})", a), - Bytecode::StLoc(a) => write!(f, "StLoc({})", a), - Bytecode::Call(a) => write!(f, "Call({})", a), - Bytecode::CallGeneric(a) => write!(f, "CallGeneric({})", a), - Bytecode::Pack(a) => write!(f, "Pack({})", a), - Bytecode::PackGeneric(a) => write!(f, "PackGeneric({})", a), - Bytecode::PackVariant(a) => write!(f, "PackVariant({})", a), - Bytecode::TestVariant(a) => write!(f, "TestVariant({})", a), - Bytecode::PackVariantGeneric(a) => write!(f, "PackVariantGeneric({})", a), - Bytecode::TestVariantGeneric(a) => write!(f, "TestVariantGeneric({})", a), - Bytecode::Unpack(a) => write!(f, "Unpack({})", a), - Bytecode::UnpackGeneric(a) => write!(f, "UnpackGeneric({})", a), - Bytecode::UnpackVariant(a) => write!(f, "UnpackVariant({})", a), - Bytecode::UnpackVariantGeneric(a) => write!(f, "UnpackVariantGeneric({})", a), - Bytecode::ReadRef => write!(f, "ReadRef"), - Bytecode::WriteRef => write!(f, "WriteRef"), - Bytecode::FreezeRef => write!(f, "FreezeRef"), - Bytecode::MutBorrowLoc(a) => write!(f, "MutBorrowLoc({})", a), - Bytecode::ImmBorrowLoc(a) => write!(f, "ImmBorrowLoc({})", a), - Bytecode::MutBorrowField(a) => write!(f, "MutBorrowField({:?})", a), - Bytecode::MutBorrowFieldGeneric(a) => write!(f, "MutBorrowFieldGeneric({:?})", a), - Bytecode::MutBorrowVariantField(a) => write!(f, "MutBorrowVariantField({:?})", a), - Bytecode::MutBorrowVariantFieldGeneric(a) => { - write!(f, "MutBorrowVariantFieldGeneric({:?})", a) - }, - Bytecode::ImmBorrowField(a) => write!(f, "ImmBorrowField({:?})", a), - Bytecode::ImmBorrowFieldGeneric(a) => write!(f, "ImmBorrowFieldGeneric({:?})", a), - Bytecode::ImmBorrowVariantField(a) => write!(f, "ImmBorrowVariantField({:?})", a), - Bytecode::ImmBorrowVariantFieldGeneric(a) => { - write!(f, "ImmBorrowVariantFieldGeneric({:?})", a) - }, - Bytecode::MutBorrowGlobal(a) => write!(f, "MutBorrowGlobal({:?})", a), - Bytecode::MutBorrowGlobalGeneric(a) => write!(f, "MutBorrowGlobalGeneric({:?})", a), - Bytecode::ImmBorrowGlobal(a) => write!(f, "ImmBorrowGlobal({:?})", a), - Bytecode::ImmBorrowGlobalGeneric(a) => write!(f, "ImmBorrowGlobalGeneric({:?})", a), - Bytecode::Add => write!(f, "Add"), - Bytecode::Sub => write!(f, "Sub"), - Bytecode::Mul => write!(f, "Mul"), - Bytecode::Mod => write!(f, "Mod"), - Bytecode::Div => write!(f, "Div"), - Bytecode::BitOr => write!(f, "BitOr"), - Bytecode::BitAnd => write!(f, "BitAnd"), - Bytecode::Xor => write!(f, "Xor"), - Bytecode::Shl => write!(f, "Shl"), - Bytecode::Shr => write!(f, "Shr"), - Bytecode::Or => write!(f, "Or"), - Bytecode::And => write!(f, "And"), - Bytecode::Not => write!(f, "Not"), - Bytecode::Eq => write!(f, "Eq"), - Bytecode::Neq => write!(f, "Neq"), - Bytecode::Lt => write!(f, "Lt"), - Bytecode::Gt => write!(f, "Gt"), - Bytecode::Le => write!(f, "Le"), - Bytecode::Ge => write!(f, "Ge"), - Bytecode::Abort => write!(f, "Abort"), - Bytecode::Nop => write!(f, "Nop"), - Bytecode::Exists(a) => write!(f, "Exists({:?})", a), - Bytecode::ExistsGeneric(a) => write!(f, "ExistsGeneric({:?})", a), - Bytecode::MoveFrom(a) => write!(f, "MoveFrom({:?})", a), - Bytecode::MoveFromGeneric(a) => write!(f, "MoveFromGeneric({:?})", a), - Bytecode::MoveTo(a) => write!(f, "MoveTo({:?})", a), - Bytecode::MoveToGeneric(a) => write!(f, "MoveToGeneric({:?})", a), - Bytecode::VecPack(a, n) => write!(f, "VecPack({}, {})", a, n), - Bytecode::VecLen(a) => write!(f, "VecLen({})", a), - Bytecode::VecImmBorrow(a) => write!(f, "VecImmBorrow({})", a), - Bytecode::VecMutBorrow(a) => write!(f, "VecMutBorrow({})", a), - Bytecode::VecPushBack(a) => write!(f, "VecPushBack({})", a), - Bytecode::VecPopBack(a) => write!(f, "VecPopBack({})", a), - Bytecode::VecUnpack(a, n) => write!(f, "VecUnpack({}, {})", a, n), - Bytecode::VecSwap(a) => write!(f, "VecSwap({})", a), - } - } -} - -#[allow(dead_code)] -#[derive(Debug, PartialEq, Eq)] -pub struct U256(PrimitiveU256); - -impl GetSize for U256 { - fn get_size(&self) -> usize { - 32 - } -} -impl fmt::Display for U256 { - fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result { - self.0.fmt(f) - } -} - -/// Generic index into one of the tables in the binary format. -pub type TableIndex = u16; - -macro_rules! define_index { - { - name: $name: ident, - kind: $kind: ident, - doc: $comment: literal, - } => { - #[derive(GetSize, PartialEq, Eq)] - pub struct $name(pub TableIndex); - - impl ::std::fmt::Display for $name { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - write!(f, "{}", self.0) - } - } - - impl ::std::fmt::Debug for $name { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - write!(f, "{}({})", stringify!($name), self.0) - } - } - }; -} - -define_index! { - name: ModuleHandleIndex, - kind: ModuleHandle, - doc: "Index into the `ModuleHandle` table.", -} -define_index! { - name: StructHandleIndex, - kind: StructHandle, - doc: "Index into the `StructHandle` table.", -} -define_index! { - name: FunctionHandleIndex, - kind: FunctionHandle, - doc: "Index into the `FunctionHandle` table.", -} -define_index! { - name: FieldHandleIndex, - kind: FieldHandle, - doc: "Index into the `FieldHandle` table.", -} -define_index! { - name: StructDefInstantiationIndex, - kind: StructDefInstantiation, - doc: "Index into the `StructInstantiation` table.", -} -define_index! { - name: FunctionInstantiationIndex, - kind: FunctionInstantiation, - doc: "Index into the `FunctionInstantiation` table.", -} -define_index! { - name: FieldInstantiationIndex, - kind: FieldInstantiation, - doc: "Index into the `FieldInstantiation` table.", -} -define_index! { - name: IdentifierIndex, - kind: Identifier, - doc: "Index into the `Identifier` table.", -} -define_index! { - name: AddressIdentifierIndex, - kind: AddressIdentifier, - doc: "Index into the `AddressIdentifier` table.", -} -define_index! { - name: ConstantPoolIndex, - kind: ConstantPool, - doc: "Index into the `ConstantPool` table.", -} -define_index! { - name: SignatureIndex, - kind: Signature, - doc: "Index into the `Signature` table.", -} -define_index! { - name: StructDefinitionIndex, - kind: StructDefinition, - doc: "Index into the `StructDefinition` table.", -} -define_index! { - name: FunctionDefinitionIndex, - kind: FunctionDefinition, - doc: "Index into the `FunctionDefinition` table.", -} - -// Since bytecode version 7 -define_index! { - name: StructVariantHandleIndex, - kind: StructVariantHandle, - doc: "Index into the `StructVariantHandle` table.", -} -define_index! { - name: StructVariantInstantiationIndex, - kind: StructVariantInstantiation, - doc: "Index into the `StructVariantInstantiation` table.", -} -define_index! { - name: VariantFieldHandleIndex, - kind: VariantFieldHandle, - doc: "Index into the `VariantFieldHandle` table.", -} -define_index! { - name: VariantFieldInstantiationIndex, - kind: VariantFieldInstantiation, - doc: "Index into the `VariantFieldInstantiation` table.", -} - -/// Index of a local variable in a function. -/// -/// Bytecodes that operate on locals carry indexes to the locals of a function. -pub type LocalIndex = u8; -/// Max number of fields in a `StructDefinition`. -pub type MemberCount = u16; -/// Max number of variants in a `StructDefinition`, as well as index for variants. -pub type VariantIndex = u16; -/// Index into the code stream for a jump. The offset is relative to the beginning of -/// the instruction stream. -pub type CodeOffset = u16; - -/// The pool of identifiers. -pub type IdentifierPool = Vec; -/// The pool of address identifiers (addresses used in ModuleHandles/ModuleIds). -/// Does not include runtime values. Those are placed in the `ConstantPool` -pub type AddressIdentifierPool = Vec; -/// The pool of `Constant` values -pub type ConstantPool = Vec; -/// The pool of `TypeSignature` instances. Those are system and user types used and -/// their composition (e.g. &U64). -#[allow(dead_code)] -pub type TypeSignaturePool = Vec; -/// The pool of `Signature` instances. Every function definition must define the set of -/// locals used and their types. -pub type SignaturePool = Vec; - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct ModuleHandle { - /// Index into the `AddressIdentifierIndex`. Identifies module-holding account's address. - pub address: AddressIdentifierIndex, - /// The name of the module published in the code section for the account in `address`. - pub name: IdentifierIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct StructHandle { - /// The module that defines the type. - pub module: ModuleHandleIndex, - /// The name of the type. - pub name: IdentifierIndex, - /// Contains the abilities for this struct - /// For any instantiation of this type, the abilities of this type are predicated on - /// that ability being satisfied for all type parameters. - pub abilities: AbilitySet, - /// The type formals (identified by their index into the vec) - pub type_parameters: Vec, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct StructTypeParameter { - /// The type parameter constraints. - pub constraints: AbilitySet, - /// Whether the parameter is declared as phantom. - pub is_phantom: bool, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FunctionHandle { - /// The module that defines the function. - pub module: ModuleHandleIndex, - /// The name of the function. - pub name: IdentifierIndex, - /// The list of arguments to the function. - pub parameters: SignatureIndex, - /// The list of return types. - pub return_: SignatureIndex, - /// The type formals (identified by their index into the vec) and their constraints - pub type_parameters: Vec, - /// An optional list of access specifiers. If this is unspecified, the function is assumed - /// to access arbitrary resources. Otherwise, each specifier approximates a set of resources - /// which are read/written by the function. An empty list indicates the function is pure and - /// does not depend on any global state. - pub access_specifiers: Option>, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FieldHandle { - pub owner: StructDefinitionIndex, - pub field: MemberCount, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct VariantFieldHandle { - /// The structure which defines the variant. - pub struct_index: StructDefinitionIndex, - /// The sequence of variants which share the field at the given - /// field offset. - pub variants: Vec, - /// The field offset. - pub field: MemberCount, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct StructVariantHandle { - pub struct_index: StructDefinitionIndex, - pub variant: VariantIndex, -} - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum StructFieldInformation { - Native, - Declared(Vec), - DeclaredVariants(Vec), -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct StructDefInstantiation { - pub def: StructDefinitionIndex, - pub type_parameters: SignatureIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct StructVariantInstantiation { - pub handle: StructVariantHandleIndex, - pub type_parameters: SignatureIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FunctionInstantiation { - pub handle: FunctionHandleIndex, - pub type_parameters: SignatureIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FieldInstantiation { - pub handle: FieldHandleIndex, - pub type_parameters: SignatureIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct VariantFieldInstantiation { - pub handle: VariantFieldHandleIndex, - pub type_parameters: SignatureIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct StructDefinition { - /// The `StructHandle` for this `StructDefinition`. This has the name and the abilities - /// for the type. - pub struct_handle: StructHandleIndex, - /// Contains either - /// - Information indicating the struct is native and has no accessible fields - /// - Information indicating the number of fields and the start `FieldDefinition`s - pub field_information: StructFieldInformation, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FieldDefinition { - /// The name of the field. - pub name: IdentifierIndex, - /// The type of the field. - pub signature: TypeSignature, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct VariantDefinition { - pub name: IdentifierIndex, - pub fields: Vec, -} - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum Visibility { - /// Accessible within its defining module only. - Private = 0x0, - /// Accessible by any module or script outside of its declaring module. - Public = 0x1, - // DEPRECATED for separate entry modifier - // Accessible by any script or other `Script` functions from any module - // Script = 0x2, - /// Accessible by this module as well as modules declared in the friend list. - Friend = 0x3, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FunctionDefinition { - /// The prototype of the function (module, name, signature). - pub function: FunctionHandleIndex, - /// The visibility of this function. - pub visibility: Visibility, - /// Marker if the function is intended as an entry function. That is - pub is_entry: bool, - /// List of locally defined types (declared in this module) with the `Key` ability - /// that the procedure might access, either through: BorrowGlobal, MoveFrom, or transitively - /// through another procedure - /// This list of acquires grants the borrow checker the ability to statically verify the safety - /// of references into global storage - /// - /// Not in the signature as it is not needed outside of the declaring module - /// - /// Note, there is no SignatureIndex with each struct definition index, so all instantiations of - /// that type are considered as being acquired - pub acquires_global_resources: Vec, - /// Code for this function. - pub code: Option, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct TypeSignature(pub SignatureToken); - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct FunctionSignature { - /// The list of return types. - pub return_: Vec, - /// The list of arguments to the function. - pub parameters: Vec, - /// The type formals (identified by their index into the vec) and their constraints - pub type_parameters: Vec, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct Signature(pub Vec); - -/// Type parameters are encoded as indices. This index can also be used to lookup the kind of a -/// type parameter in the `FunctionHandle` and `StructHandle`. -pub type TypeParameterIndex = u16; - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum Ability { - /// Allows values of types with this ability to be copied, via CopyLoc or ReadRef - Copy = 0x1, - /// Allows values of types with this ability to be dropped, via Pop, WriteRef, StLoc, Eq, Neq, - /// or if left in a local when Ret is invoked - /// Technically also needed for numeric operations (Add, BitAnd, Shift, etc), but all - /// of the types that can be used with those operations have Drop - Drop = 0x2, - /// Allows values of types with this ability to exist inside a struct in global storage - Store = 0x4, - /// Allows the type to serve as a key for global storage operations: MoveTo, MoveFrom, etc. - Key = 0x8, -} - -impl Ability { - fn from_u8(u: u8) -> Option { - match u { - 0x1 => Some(Ability::Copy), - 0x2 => Some(Ability::Drop), - 0x4 => Some(Ability::Store), - 0x8 => Some(Ability::Key), - _ => None, - } - } -} - -#[derive(GetSize, PartialEq, Eq, Copy, Clone)] -pub struct AbilitySet(pub u8); - -#[allow(dead_code)] -impl AbilitySet { - /// Ability set containing all abilities - pub const ALL: Self = Self( - // Cannot use AbilitySet bitor because it is not const - (Ability::Copy as u8) - | (Ability::Drop as u8) - | (Ability::Store as u8) - | (Ability::Key as u8), - ); - /// The empty ability set - pub const EMPTY: Self = Self(0); - /// Abilities for `Functions` - pub const FUNCTIONS: AbilitySet = Self(Ability::Drop as u8); - /// Abilities for `Bool`, `U8`, `U64`, `U128`, and `Address` - pub const PRIMITIVES: AbilitySet = - Self((Ability::Copy as u8) | (Ability::Drop as u8) | (Ability::Store as u8)); - /// Abilities for `Reference` and `MutableReference` - pub const REFERENCES: AbilitySet = Self((Ability::Copy as u8) | (Ability::Drop as u8)); - /// Abilities for `Signer` - pub const SIGNER: AbilitySet = Self(Ability::Drop as u8); - /// Abilities for `Vector`, note they are predicated on the type argument - pub const VECTOR: AbilitySet = - Self((Ability::Copy as u8) | (Ability::Drop as u8) | (Ability::Store as u8)); - - #[inline] - fn is_subset_bits(sub: u8, sup: u8) -> bool { - (sub & sup) == sub - } - - pub fn from_u8(byte: u8) -> Option { - // If there is a bit set in the read `byte`, that bit must be set in the - // `AbilitySet` containing all `Ability`s - // This corresponds the byte being a bit set subset of ALL - // The byte is a subset of ALL if the intersection of the two is the original byte - if Self::is_subset_bits(byte, Self::ALL.0) { - Some(Self(byte)) - } else { - None - } - } -} - -impl IntoIterator for AbilitySet { - type IntoIter = AbilitySetIterator; - type Item = Ability; - - fn into_iter(self) -> Self::IntoIter { - AbilitySetIterator { - idx: 0x1, - set: self, - } - } -} - -impl std::fmt::Debug for AbilitySet { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - write!(f, "[")?; - for ability in *self { - write!(f, "{:?}, ", ability)?; - } - write!(f, "]") - } -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct AbilitySetIterator { - set: AbilitySet, - idx: u8, -} - -impl Iterator for AbilitySetIterator { - type Item = Ability; - - fn next(&mut self) -> Option { - while self.idx <= 0x8 { - let next = Ability::from_u8(self.set.0 & self.idx); - self.idx <<= 1; - if next.is_some() { - return next; - } - } - None - } -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct AccessSpecifier { - /// The kind of access: read, write, or both. - pub kind: AccessKind, - /// Whether the specifier is negated. - pub negated: bool, - /// The resource specifier. - pub resource: ResourceSpecifier, - /// The address where the resource is stored. - pub address: AddressSpecifier, -} - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum AccessKind { - Reads, - Writes, - Acquires, // reads or writes -} - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum ResourceSpecifier { - /// Any resource - Any, - /// A resource declared at the given address. - DeclaredAtAddress(AddressIdentifierIndex), - /// A resource declared in the given module. - DeclaredInModule(ModuleHandleIndex), - /// An explicit resource - Resource(StructHandleIndex), - /// A resource instantiation. - ResourceInstantiation(StructHandleIndex, SignatureIndex), -} - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum AddressSpecifier { - /// Resource can be stored at any address. - Any, - /// A literal address representation. - Literal(AddressIdentifierIndex), - /// An address derived from a parameter of the current function. - Parameter( - /// The index of a parameter of the current function. If `modifier` is not given, the - /// parameter must have address type. Otherwise `modifier` must be a function which takes - /// a value (or reference) of the parameter type and delivers an address. - LocalIndex, - /// If given, a function applied to the parameter. This is a well-known function which - /// extracts an address from a value, e.g. `object::address_of`. - Option, - ), -} - -#[allow(dead_code)] -#[derive(GetSize, PartialEq, Eq, Debug)] -pub enum SignatureToken { - /// Boolean, `true` or `false`. - Bool, - /// Unsigned integers, 8 bits length. - U8, - /// Unsigned integers, 64 bits length. - U64, - /// Unsigned integers, 128 bits length. - U128, - /// Address, a 16 bytes immutable type. - Address, - /// Signer, a 16 bytes immutable type representing the capability to publish at an address - Signer, - /// Vector - Vector(Box), - /// User defined type - Struct(StructHandleIndex), - StructInstantiation(StructHandleIndex, Vec), - /// Reference to a type. - Reference(Box), - /// Mutable reference to a type. - MutableReference(Box), - /// Type parameter. - TypeParameter(TypeParameterIndex), - /// Unsigned integers, 16 bits length. - U16, - /// Unsigned integers, 32 bits length. - U32, - /// Unsigned integers, 256 bits length. - #[get_size(ignore)] - U256, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct SignatureTokenPreorderTraversalIter<'a> { - stack: Vec<&'a SignatureToken>, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct SignatureTokenPreorderTraversalIterWithDepth<'a> { - stack: Vec<(&'a SignatureToken, usize)>, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct Constant { - pub type_: SignatureToken, - pub data: Vec, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct CodeUnit { - /// List of locals type. All locals are typed. - pub locals: SignatureIndex, - /// Code stream, function body. - pub code: Vec, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct CompiledScript { - /// Version number found during deserialization - pub version: u32, - /// Handles to all modules referenced. - pub module_handles: Vec, - /// Handles to external/imported types. - pub struct_handles: Vec, - /// Handles to external/imported functions. - pub function_handles: Vec, - - /// Function instantiations. - pub function_instantiations: Vec, - - pub signatures: SignaturePool, - - /// All identifiers used in this transaction. - pub identifiers: IdentifierPool, - /// All address identifiers used in this transaction. - pub address_identifiers: AddressIdentifierPool, - /// Constant pool. The constant values used in the transaction. - pub constant_pool: ConstantPool, - - pub metadata: Vec, - - pub code: CodeUnit, - pub type_parameters: Vec, - - pub parameters: SignatureIndex, -} - -#[derive(GetSize, PartialEq, Eq, Debug)] -pub struct CompiledModule { - /// Version number found during deserialization - pub version: u32, - /// Handle to self. - pub self_module_handle_idx: ModuleHandleIndex, - /// Handles to external dependency modules and self. - pub module_handles: Vec, - /// Handles to external and internal types. - pub struct_handles: Vec, - /// Handles to external and internal functions. - pub function_handles: Vec, - /// Handles to fields. - pub field_handles: Vec, - /// Friend declarations, represented as a collection of handles to external friend modules. - pub friend_decls: Vec, - - /// Struct instantiations. - pub struct_def_instantiations: Vec, - /// Function instantiations. - pub function_instantiations: Vec, - /// Field instantiations. - pub field_instantiations: Vec, - - /// Locals signature pool. The signature for all locals of the functions defined in the module. - pub signatures: SignaturePool, - - /// All identifiers used in this module. - pub identifiers: IdentifierPool, - /// All address identifiers used in this module. - pub address_identifiers: AddressIdentifierPool, - /// Constant pool. The constant values used in the module. - pub constant_pool: ConstantPool, - - pub metadata: Vec, - - /// Types defined in this module. - pub struct_defs: Vec, - /// Function defined in this module. - pub function_defs: Vec, - - /// Since bytecode version 7: variant related handle tables - pub struct_variant_handles: Vec, - pub struct_variant_instantiations: Vec, - pub variant_field_handles: Vec, - pub variant_field_instantiations: Vec, -} diff --git a/crates/storage/src/move_core_type/function.rs b/crates/storage/src/move_core_type/function.rs deleted file mode 100644 index d4597d84..00000000 --- a/crates/storage/src/move_core_type/function.rs +++ /dev/null @@ -1,67 +0,0 @@ -use std::{fmt::Debug, sync::Arc}; - -use super::{ - file_format::{AbilitySet, Bytecode, FunctionDefinitionIndex}, modules::Module, move_core_type::{Identifier, ModuleId}, runtime_access_specifier::AccessSpecifier, runtime_types::Type, script::Script -}; -use get_size::GetSize; -use move_vm_runtime::native_functions::NativeFunction; - -#[allow(dead_code)] -#[derive(GetSize)] -pub struct Function { - pub(crate) file_format_version: u32, - pub(crate) index: FunctionDefinitionIndex, - pub(crate) code: Vec, - pub(crate) ty_param_abilities: Vec, - #[get_size(ignore)] - pub(crate) native: Option, - pub(crate) is_native: bool, - pub(crate) is_friend_or_private: bool, - pub(crate) is_entry: bool, - pub(crate) name: Identifier, - pub(crate) return_tys: Vec, - pub(crate) local_tys: Vec, - pub(crate) param_tys: Vec, - pub(crate) access_specifier: AccessSpecifier, -} - -impl Debug for Function { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - f.debug_struct("Function") - .field("name", &self.name) - .finish() - } -} - -#[allow(dead_code)] -#[derive(GetSize)] -/// For loaded function representation, specifies the owner: a script or a module. -pub(crate) enum LoadedFunctionOwner { - Script(Arc