1use std::{
35 collections::{BTreeMap, BTreeSet},
36 hash::Hash,
37};
38
39use derive_more::Display;
40use iota_protocol_config::ProtocolConfig;
41use iota_sdk_move_types::iota_framework::{
42 object::{ID, UID},
43 package::UpgradeTicket,
44 vec_map::{Entry, VecMap},
45};
46use iota_sdk_types::{
47 Identifier, MovePackage, ObjectId, PackageUpgradeError, StructTag, TypeOrigin, TypeTag,
48 UpgradeInfo, Version,
49};
50use move_binary_format::{
51 binary_config::BinaryConfig,
52 file_format::CompiledModule,
53 file_format_common::{IOTA_METADATA_KEY, VERSION_6},
54 normalized,
55};
56use move_core_types::identifier::IdentStr;
57use serde::{Deserialize, Serialize};
58use serde_with::{Bytes, serde_as};
59
60use crate::{
61 Address,
62 error::{ExecutionError, ExecutionErrorKind, IotaError, IotaResult},
63 iota_sdk_types_conversions::identifier_core_to_sdk,
64 iota_serde::TypeName,
65};
66
67pub const PACKAGE_METADATA_MODULE_NAME: Identifier = Identifier::from_static("package_metadata");
68pub const PACKAGE_METADATA_V1_STRUCT_NAME: Identifier =
69 Identifier::from_static("PackageMetadataV1");
70pub const PACKAGE_METADATA_KEY_STRUCT_NAME: Identifier =
71 Identifier::from_static("PackageMetadataKey");
72
73#[derive(Clone, Debug)]
74pub struct FnInfo {
76 pub is_test: bool,
79 pub authenticator_version: Option<u8>,
82 pub is_view: bool,
83}
84
85#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
86pub struct FnInfoKey {
88 pub fn_name: String,
89 pub mod_name: String,
90 pub mod_addr: Address,
91}
92
93pub type FnInfoMap = BTreeMap<FnInfoKey, FnInfo>;
95
96#[repr(u8)]
101#[derive(Display, Debug, Clone, Copy)]
102pub enum UpgradePolicy {
103 #[display("COMPATIBLE")]
104 Compatible = 0,
105 #[display("ADDITIVE")]
106 Additive = 128,
107 #[display("DEP_ONLY")]
108 DepOnly = 192,
109}
110
111impl UpgradePolicy {
112 pub const COMPATIBLE: u8 = Self::Compatible as u8;
114 pub const ADDITIVE: u8 = Self::Additive as u8;
115 pub const DEP_ONLY: u8 = Self::DepOnly as u8;
116
117 pub fn is_valid_policy(policy: &u8) -> bool {
118 Self::try_from(*policy).is_ok()
119 }
120}
121
122impl TryFrom<u8> for UpgradePolicy {
123 type Error = ();
124 fn try_from(value: u8) -> Result<Self, Self::Error> {
125 match value {
126 x if x == Self::Compatible as u8 => Ok(Self::Compatible),
127 x if x == Self::Additive as u8 => Ok(Self::Additive),
128 x if x == Self::DepOnly as u8 => Ok(Self::DepOnly),
129 _ => Err(()),
130 }
131 }
132}
133
134#[derive(Debug, Serialize, Deserialize)]
136pub struct UpgradeCap {
137 pub id: UID,
138 pub package: ID,
139 pub version: u64,
140 pub policy: u8,
141}
142
143#[derive(Debug, Serialize, Deserialize)]
145pub struct UpgradeReceipt {
146 pub cap: ID,
147 pub package: ID,
148}
149
150mod move_package_ext {
151 pub trait Sealed {}
152 impl Sealed for super::MovePackage {}
153}
154
155pub trait MovePackageExt: Sized + move_package_ext::Sealed {
156 fn new_initial<'p>(
157 modules: &[CompiledModule],
158 protocol_config: &ProtocolConfig,
159 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
160 ) -> Result<MovePackage, ExecutionError>;
161
162 fn new_upgraded<'p>(
163 &self,
164 storage_id: ObjectId,
165 modules: &[CompiledModule],
166 protocol_config: &ProtocolConfig,
167 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
168 ) -> Result<MovePackage, ExecutionError>;
169
170 fn new_system(
171 version: Version,
172 modules: &[CompiledModule],
173 dependencies: impl IntoIterator<Item = ObjectId>,
174 ) -> MovePackage;
175
176 fn from_module_iter_with_type_origin_table<'p>(
177 storage_id: ObjectId,
178 self_id: ObjectId,
179 version: Version,
180 modules: &[CompiledModule],
181 protocol_config: &ProtocolConfig,
182 type_origin_table: Vec<TypeOrigin>,
183 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
184 ) -> Result<MovePackage, ExecutionError>;
185
186 fn original_package_id(&self) -> ObjectId;
187
188 fn deserialize_module(
189 &self,
190 module: &Identifier,
191 binary_config: &BinaryConfig,
192 ) -> IotaResult<CompiledModule>;
193
194 fn normalize<S: Hash + Eq + Clone + ToString, Pool: normalized::StringPool<String = S>>(
195 &self,
196 pool: &mut Pool,
197 binary_config: &BinaryConfig,
198 include_code: bool,
199 ) -> IotaResult<BTreeMap<String, normalized::Module<S>>>;
200}
201
202impl MovePackageExt for MovePackage {
203 fn new_initial<'p>(
211 modules: &[CompiledModule],
212 protocol_config: &ProtocolConfig,
213 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
214 ) -> Result<MovePackage, ExecutionError> {
215 let module = modules
216 .first()
217 .expect("Tried to build a Move package from an empty iterator of Compiled modules");
218 let runtime_id = ObjectId::new(module.address().into_bytes());
219 let storage_id = runtime_id;
220 let type_origin_table = build_initial_type_origin_table(modules);
221
222 MovePackage::from_module_iter_with_type_origin_table(
223 storage_id,
224 runtime_id,
225 Version::OBJECT_START,
226 modules,
227 protocol_config,
228 type_origin_table,
229 transitive_dependencies,
230 )
231 }
232
233 fn new_upgraded<'p>(
241 &self,
242 storage_id: ObjectId,
243 modules: &[CompiledModule],
244 protocol_config: &ProtocolConfig,
245 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
246 ) -> Result<MovePackage, ExecutionError> {
247 let module = modules
248 .first()
249 .expect("Tried to build a Move package from an empty iterator of Compiled modules");
250 let runtime_id = ObjectId::new(module.address().into_bytes());
251 let type_origin_table = build_upgraded_type_origin_table(self, modules, storage_id)?;
252 let mut new_version = self.version();
253 new_version.increment().unwrap();
254
255 MovePackage::from_module_iter_with_type_origin_table(
256 storage_id,
257 runtime_id,
258 new_version,
259 modules,
260 protocol_config,
261 type_origin_table,
262 transitive_dependencies,
263 )
264 }
265
266 fn new_system(
267 version: Version,
268 modules: &[CompiledModule],
269 dependencies: impl IntoIterator<Item = ObjectId>,
270 ) -> MovePackage {
271 let module = modules
272 .first()
273 .expect("Tried to build a Move package from an empty iterator of Compiled modules");
274
275 let storage_id = ObjectId::new(module.address().into_bytes());
276 let type_origin_table = build_initial_type_origin_table(modules);
277
278 let linkage_table = BTreeMap::from_iter(dependencies.into_iter().map(|dep| {
279 let info = UpgradeInfo {
280 upgraded_id: dep,
281 upgraded_version: Version::default(),
293 };
294 (dep, info)
295 }));
296
297 let module_map = BTreeMap::from_iter(modules.iter().map(|module| {
298 let name = identifier_core_to_sdk(module.name());
299 let mut bytes = Vec::new();
300 module
301 .serialize_with_version(module.version, &mut bytes)
302 .unwrap();
303 (name, bytes)
304 }));
305
306 MovePackage::new(
310 storage_id,
311 version,
312 module_map,
313 type_origin_table,
314 linkage_table,
315 )
316 }
317
318 fn from_module_iter_with_type_origin_table<'p>(
319 storage_id: ObjectId,
320 self_id: ObjectId,
321 version: Version,
322 modules: &[CompiledModule],
323 protocol_config: &ProtocolConfig,
324 type_origin_table: Vec<TypeOrigin>,
325 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
326 ) -> Result<MovePackage, ExecutionError> {
327 let mut module_map = BTreeMap::new();
328 let mut immediate_dependencies = BTreeSet::new();
329
330 for module in modules {
331 let name = identifier_core_to_sdk(module.name());
332
333 immediate_dependencies.extend(
334 module
335 .immediate_dependencies()
336 .into_iter()
337 .map(|dep| ObjectId::new(dep.address().into_bytes())),
338 );
339
340 let mut bytes = Vec::new();
341 let version = if protocol_config.move_binary_format_version() > VERSION_6 {
342 module.version
343 } else {
344 VERSION_6
345 };
346 module.serialize_with_version(version, &mut bytes).unwrap();
347 module_map.insert(name, bytes);
348 }
349
350 immediate_dependencies.remove(&self_id);
351 let linkage_table = build_linkage_table(
352 immediate_dependencies,
353 transitive_dependencies,
354 protocol_config,
355 )?;
356
357 let package = MovePackage::new(
358 storage_id,
359 version,
360 module_map,
361 type_origin_table,
362 linkage_table,
363 );
364 package.check_size(max_package_size(storage_id, protocol_config))?;
372
373 Ok(package)
374 }
375
376 fn original_package_id(&self) -> ObjectId {
384 if self.version == Version::OBJECT_START {
385 return self.id;
387 }
388
389 let bytes = self.modules.values().next().expect("Empty module map");
390 let module = CompiledModule::deserialize_with_defaults(bytes)
394 .expect("A Move package contains a module that cannot be deserialized");
395 ObjectId::new(module.address().into_bytes())
396 }
397
398 fn deserialize_module(
399 &self,
400 module: &Identifier,
401 binary_config: &BinaryConfig,
402 ) -> IotaResult<CompiledModule> {
403 let bytes =
405 self.serialized_module_map()
406 .get(module)
407 .ok_or_else(|| IotaError::ModuleNotFound {
408 module_name: module.to_string(),
409 })?;
410
411 CompiledModule::deserialize_with_config(bytes, binary_config).map_err(|error| {
412 IotaError::ModuleDeserializationFailure {
413 error: error.to_string(),
414 }
415 })
416 }
417
418 fn normalize<S: Hash + Eq + Clone + ToString, Pool: normalized::StringPool<String = S>>(
421 &self,
422 pool: &mut Pool,
423 binary_config: &BinaryConfig,
424 include_code: bool,
425 ) -> IotaResult<BTreeMap<String, normalized::Module<S>>> {
426 normalize_modules(pool, self.modules.values(), binary_config, include_code)
427 }
428}
429
430impl UpgradeCap {
431 pub fn new(uid: ObjectId, package_id: ObjectId) -> Self {
434 UpgradeCap {
435 id: UID::new(uid),
436 package: ID::new(package_id),
437 version: 1,
438 policy: UpgradePolicy::COMPATIBLE,
439 }
440 }
441}
442
443impl UpgradeReceipt {
444 pub fn new(upgrade_ticket: UpgradeTicket, upgraded_package_id: ObjectId) -> Self {
447 UpgradeReceipt {
448 cap: upgrade_ticket.cap,
449 package: ID::new(upgraded_package_id),
450 }
451 }
452}
453
454pub fn is_test_fun(name: &str, module: &CompiledModule, fn_info_map: &FnInfoMap) -> bool {
456 let mod_handle = module.self_handle();
457 let mod_addr = Address::new(
458 module
459 .address_identifier_at(mod_handle.address)
460 .into_bytes(),
461 );
462 let mod_name = module.name().to_string();
463 let fn_info_key = FnInfoKey {
464 fn_name: name.to_string(),
465 mod_name,
466 mod_addr,
467 };
468 match fn_info_map.get(&fn_info_key) {
469 Some(fn_info) => fn_info.is_test,
470 None => false,
471 }
472}
473
474pub fn get_authenticator_version_from_fun(
475 name: &str,
476 module: &CompiledModule,
477 fn_info_map: &FnInfoMap,
478) -> Option<u8> {
479 let mod_handle = module.self_handle();
480 let mod_addr = Address::from(
481 module
482 .address_identifier_at(mod_handle.address)
483 .into_bytes(),
484 );
485 let mod_name = module.name().to_string();
486 let fn_info_key = FnInfoKey {
487 fn_name: name.to_string(),
488 mod_name,
489 mod_addr,
490 };
491 match fn_info_map.get(&fn_info_key) {
492 Some(FnInfo {
493 is_test: _,
494 authenticator_version: Some(v),
495 is_view: _,
496 }) => Some(*v),
497 _ => None,
498 }
499}
500
501pub fn is_view_function_from_fn_info(
503 name: &IdentStr,
504 module: &CompiledModule,
505 fn_info_map: &FnInfoMap,
506) -> bool {
507 let fn_name = name.to_string();
508 let mod_handle = module.self_handle();
509 let mod_addr = Address::from(
510 module
511 .address_identifier_at(mod_handle.address)
512 .into_bytes(),
513 );
514 let mod_name = module.name().to_string();
515 let fn_info_key = FnInfoKey {
516 fn_name,
517 mod_name,
518 mod_addr,
519 };
520 fn_info_map
521 .get(&fn_info_key)
522 .map(|info| info.is_view)
523 .unwrap_or(false)
524}
525
526pub fn normalize_modules<
529 'a,
530 S: Hash + Eq + Clone + ToString,
531 Pool: normalized::StringPool<String = S>,
532 I,
533>(
534 pool: &mut Pool,
535 modules: I,
536 binary_config: &BinaryConfig,
537 include_code: bool,
538) -> IotaResult<BTreeMap<String, normalized::Module<S>>>
539where
540 I: Iterator<Item = &'a Vec<u8>>,
541{
542 let mut normalized_modules = BTreeMap::new();
543 for bytecode in modules {
544 let module =
545 CompiledModule::deserialize_with_config(bytecode, binary_config).map_err(|error| {
546 IotaError::ModuleDeserializationFailure {
547 error: error.to_string(),
548 }
549 })?;
550 let normalized_module = normalized::Module::new(pool, &module, include_code);
551 normalized_modules.insert(normalized_module.name().to_string(), normalized_module);
552 }
553 Ok(normalized_modules)
554}
555
556pub fn normalize_modules_with_metadata<
562 'a,
563 S: Hash + Eq + Clone + ToString,
564 Pool: normalized::StringPool<String = S>,
565 I,
566>(
567 pool: &mut Pool,
568 modules: I,
569 binary_config: &BinaryConfig,
570 include_code: bool,
571 protocol_config: Option<&ProtocolConfig>,
572) -> IotaResult<BTreeMap<String, (normalized::Module<S>, RuntimeModuleMetadata)>>
573where
574 I: Iterator<Item = &'a Vec<u8>>,
575{
576 let mut normalized_modules = BTreeMap::new();
577 for bytecode in modules {
578 let module =
579 CompiledModule::deserialize_with_config(bytecode, binary_config).map_err(|error| {
580 IotaError::ModuleDeserializationFailure {
581 error: error.to_string(),
582 }
583 })?;
584 let metadata = runtime_module_metadata(&module, protocol_config)?;
585 let normalized_module = normalized::Module::new(pool, &module, include_code);
586 normalized_modules.insert(
587 normalized_module.name().to_string(),
588 (normalized_module, metadata),
589 );
590 }
591 Ok(normalized_modules)
592}
593
594pub fn normalize_deserialized_modules<
597 'a,
598 S: Hash + Eq + Clone + ToString,
599 Pool: normalized::StringPool<String = S>,
600 I,
601>(
602 pool: &mut Pool,
603 modules: I,
604 include_code: bool,
605) -> BTreeMap<String, normalized::Module<S>>
606where
607 I: Iterator<Item = &'a CompiledModule>,
608{
609 let mut normalized_modules = BTreeMap::new();
610 for module in modules {
611 let normalized_module = normalized::Module::new(pool, module, include_code);
612 normalized_modules.insert(normalized_module.name().to_string(), normalized_module);
613 }
614 normalized_modules
615}
616
617pub fn normalize_deserialized_modules_with_metadata<
623 'a,
624 S: Hash + Eq + Clone + ToString,
625 Pool: normalized::StringPool<String = S>,
626 I,
627>(
628 pool: &mut Pool,
629 modules: I,
630 include_code: bool,
631 protocol_config: Option<&ProtocolConfig>,
632) -> IotaResult<BTreeMap<String, (normalized::Module<S>, RuntimeModuleMetadata)>>
633where
634 I: Iterator<Item = &'a CompiledModule>,
635{
636 let mut normalized_modules = BTreeMap::new();
637 for module in modules {
638 let metadata = runtime_module_metadata(module, protocol_config)?;
639 let normalized_module = normalized::Module::new(pool, module, include_code);
640 normalized_modules.insert(
641 normalized_module.name().to_string(),
642 (normalized_module, metadata),
643 );
644 }
645 Ok(normalized_modules)
646}
647
648fn runtime_module_metadata(
649 module: &CompiledModule,
650 protocol_config: Option<&ProtocolConfig>,
651) -> IotaResult<RuntimeModuleMetadata> {
652 let build_config = ProtocolBuildConfig::from(protocol_config);
653 let Some(metadata) = module
654 .metadata
655 .iter()
656 .find(|metadata| metadata.key == IOTA_METADATA_KEY)
657 else {
658 if build_config.allow_view_function {
659 return Ok(RuntimeModuleMetadata::v2());
660 } else {
661 return Ok(RuntimeModuleMetadata::v1());
662 }
663 };
664
665 let metadata_wrapper: RuntimeModuleMetadataWrapper =
666 bcs::from_bytes(&metadata.value).map_err(|error| {
667 IotaError::RuntimeModuleMetadataDeserialization {
668 error: error.to_string(),
669 }
670 })?;
671 metadata_wrapper.try_into_runtime_module_metadata(&build_config)
672}
673
674pub fn max_package_size(storage_id: ObjectId, protocol_config: &ProtocolConfig) -> u64 {
684 if storage_id.is_system_package() {
685 protocol_config
686 .max_move_system_package_size_as_option()
687 .unwrap_or_else(|| protocol_config.max_move_package_size())
688 } else {
689 protocol_config.max_move_package_size()
690 }
691}
692
693fn build_linkage_table<'p>(
694 mut immediate_dependencies: BTreeSet<ObjectId>,
695 transitive_dependencies: impl IntoIterator<Item = &'p MovePackage>,
696 protocol_config: &ProtocolConfig,
697) -> Result<BTreeMap<ObjectId, UpgradeInfo>, ExecutionError> {
698 let mut linkage_table = BTreeMap::new();
699 let mut dep_linkage_tables = vec![];
700
701 for transitive_dep in transitive_dependencies.into_iter() {
702 let original_id = MovePackage::original_package_id(transitive_dep);
706
707 let imm_dep = immediate_dependencies.remove(&original_id);
708
709 if protocol_config.dependency_linkage_error() {
710 dep_linkage_tables.push(&transitive_dep.linkage_table);
711
712 let existing = linkage_table.insert(
713 original_id,
714 UpgradeInfo {
715 upgraded_id: transitive_dep.id,
716 upgraded_version: transitive_dep.version,
717 },
718 );
719
720 if existing.is_some() {
721 return Err(ExecutionErrorKind::InvalidLinkage.into());
722 }
723 } else {
724 if imm_dep {
725 dep_linkage_tables.push(&transitive_dep.linkage_table);
728 }
729 linkage_table.insert(
730 original_id,
731 UpgradeInfo {
732 upgraded_id: transitive_dep.id,
733 upgraded_version: transitive_dep.version,
734 },
735 );
736 }
737 }
738 if !immediate_dependencies.is_empty() {
740 return Err(ExecutionErrorKind::PublishUpgradeMissingDependency.into());
741 }
742
743 for dep_linkage_table in dep_linkage_tables {
745 for (original_id, dep_info) in dep_linkage_table {
746 let Some(our_info) = linkage_table.get(original_id) else {
747 return Err(ExecutionErrorKind::PublishUpgradeMissingDependency.into());
748 };
749
750 if our_info.upgraded_version < dep_info.upgraded_version {
751 return Err(ExecutionErrorKind::PublishUpgradeDependencyDowngrade.into());
752 }
753 }
754 }
755
756 Ok(linkage_table)
757}
758
759fn build_initial_type_origin_table(modules: &[CompiledModule]) -> Vec<TypeOrigin> {
760 modules
761 .iter()
762 .flat_map(|m| {
763 m.struct_defs()
764 .iter()
765 .map(|struct_def| {
766 let struct_handle = m.datatype_handle_at(struct_def.struct_handle);
767 let package = ObjectId::new(m.self_id().address().into_bytes());
768 TypeOrigin {
769 module_name: identifier_core_to_sdk(m.name()),
770 datatype_name: identifier_core_to_sdk(m.identifier_at(struct_handle.name)),
771 package,
772 }
773 })
774 .chain(m.enum_defs().iter().map(|enum_def| {
775 let enum_handle = m.datatype_handle_at(enum_def.enum_handle);
776 let package = ObjectId::new(m.self_id().address().into_bytes());
777 TypeOrigin {
778 module_name: identifier_core_to_sdk(m.name()),
779 datatype_name: identifier_core_to_sdk(m.identifier_at(enum_handle.name)),
780 package,
781 }
782 }))
783 })
784 .collect()
785}
786
787fn build_upgraded_type_origin_table(
788 predecessor: &MovePackage,
789 modules: &[CompiledModule],
790 storage_id: ObjectId,
791) -> Result<Vec<TypeOrigin>, ExecutionError> {
792 let mut new_table = vec![];
793 let mut existing_table = predecessor.type_origin_map();
794 for m in modules {
795 for struct_def in m.struct_defs() {
796 let struct_handle = m.datatype_handle_at(struct_def.struct_handle);
797 let module_name = identifier_core_to_sdk(m.name());
798 let struct_name = identifier_core_to_sdk(m.identifier_at(struct_handle.name));
799 let mod_key = (module_name.clone(), struct_name.clone());
800 let package = existing_table.remove(&mod_key).unwrap_or(storage_id);
803 new_table.push(TypeOrigin {
804 module_name,
805 datatype_name: struct_name,
806 package,
807 });
808 }
809
810 for enum_def in m.enum_defs() {
811 let enum_handle = m.datatype_handle_at(enum_def.enum_handle);
812 let module_name = identifier_core_to_sdk(m.name());
813 let enum_name = identifier_core_to_sdk(m.identifier_at(enum_handle.name));
814 let mod_key = (module_name.clone(), enum_name.clone());
815 let package = existing_table.remove(&mod_key).unwrap_or(storage_id);
818 new_table.push(TypeOrigin {
819 module_name,
820 datatype_name: enum_name,
821 package,
822 });
823 }
824 }
825
826 if !existing_table.is_empty() {
827 Err(ExecutionError::from_kind(
828 ExecutionErrorKind::PackageUpgradeError {
829 kind: PackageUpgradeError::IncompatibleUpgrade,
830 },
831 ))
832 } else {
833 Ok(new_table)
834 }
835}
836
837#[derive(Debug, Clone, Copy)]
847pub struct ProtocolBuildConfig {
848 pub allow_view_function: bool,
851 pub max_move_package_size: Option<u64>,
855 pub max_move_system_package_size: Option<u64>,
861}
862
863impl Default for ProtocolBuildConfig {
864 fn default() -> Self {
865 Self {
866 allow_view_function: true,
867 max_move_package_size: None,
868 max_move_system_package_size: None,
869 }
870 }
871}
872
873impl ProtocolBuildConfig {
874 pub fn from_protocol_config(protocol_config: &ProtocolConfig) -> Self {
876 Self {
877 allow_view_function: protocol_config.package_metadata_with_dynamic_module_metadata(),
878 max_move_package_size: Some(protocol_config.max_move_package_size()),
879 max_move_system_package_size: protocol_config.max_move_system_package_size_as_option(),
880 }
881 }
882}
883
884impl From<&ProtocolConfig> for ProtocolBuildConfig {
885 fn from(protocol_config: &ProtocolConfig) -> Self {
886 Self::from_protocol_config(protocol_config)
887 }
888}
889
890impl From<Option<&ProtocolConfig>> for ProtocolBuildConfig {
891 fn from(protocol_config: Option<&ProtocolConfig>) -> Self {
892 protocol_config
893 .map(Self::from_protocol_config)
894 .unwrap_or_default()
895 }
896}
897
898#[serde_as]
900#[derive(Debug, Clone, Serialize, Deserialize)]
901pub struct RuntimeModuleMetadataWrapper {
902 pub version: u64,
903 #[serde_as(as = "Bytes")]
904 pub inner: Vec<u8>,
905}
906
907impl RuntimeModuleMetadataWrapper {
908 pub fn to_bcs_bytes(&self) -> Vec<u8> {
909 bcs::to_bytes(&self).unwrap()
911 }
912
913 pub fn try_into_runtime_module_metadata(
914 &self,
915 protocol_build_config: &ProtocolBuildConfig,
916 ) -> Result<RuntimeModuleMetadata, IotaError> {
917 match self.version {
918 1 => {
919 let inner: RuntimeModuleMetadataV1 = bcs::from_bytes(&self.inner).map_err(|e| {
920 IotaError::RuntimeModuleMetadataDeserialization {
921 error: e.to_string(),
922 }
923 })?;
924 Ok(RuntimeModuleMetadata::V1(inner))
925 }
926 2 if protocol_build_config.allow_view_function => {
927 let inner: RuntimeModuleMetadataV2 = bcs::from_bytes(&self.inner).map_err(|e| {
928 IotaError::RuntimeModuleMetadataDeserialization {
929 error: e.to_string(),
930 }
931 })?;
932 Ok(RuntimeModuleMetadata::V2(inner))
933 }
934 _ => Err(IotaError::RuntimeModuleMetadataDeserialization {
935 error: format!(
936 "Unsupported runtime module metadata version: {}",
937 self.version
938 ),
939 }),
940 }
941 }
942}
943
944impl From<RuntimeModuleMetadata> for RuntimeModuleMetadataWrapper {
945 fn from(metadata: RuntimeModuleMetadata) -> Self {
946 match metadata {
947 RuntimeModuleMetadata::V1(inner) => RuntimeModuleMetadataWrapper {
948 version: 1,
949 inner: inner.to_bcs_bytes(),
950 },
951 RuntimeModuleMetadata::V2(inner) => RuntimeModuleMetadataWrapper {
952 version: 2,
953 inner: inner.to_bcs_bytes(),
954 },
955 }
956 }
957}
958
959#[derive(Debug, Clone, Serialize, Deserialize)]
961pub enum RuntimeModuleMetadata {
962 V1(RuntimeModuleMetadataV1),
963 V2(RuntimeModuleMetadataV2),
964}
965
966impl RuntimeModuleMetadata {
967 pub fn v1() -> Self {
968 RuntimeModuleMetadata::V1(RuntimeModuleMetadataV1::default())
969 }
970
971 pub fn v2() -> Self {
972 RuntimeModuleMetadata::V2(RuntimeModuleMetadataV2::default())
973 }
974
975 pub fn add_function_attribute(&mut self, function_name: String, attribute: IotaAttribute) {
986 match (self, attribute) {
987 (RuntimeModuleMetadata::V1(metadata), IotaAttribute::V1(attribute)) => {
988 metadata.add_function_attribute(function_name, attribute)
989 }
990 (RuntimeModuleMetadata::V2(metadata), IotaAttribute::V2(attribute)) => {
991 metadata.add_function_attribute(function_name, attribute)
992 }
993 _ => panic!("attribute version does not match runtime module metadata version"),
994 }
995 }
996
997 pub fn is_empty(&self) -> bool {
998 match self {
999 RuntimeModuleMetadata::V1(metadata) => metadata.is_empty(),
1000 RuntimeModuleMetadata::V2(metadata) => metadata.is_empty(),
1001 }
1002 }
1003}
1004
1005#[derive(Debug, Clone)]
1010pub enum IotaAttribute {
1011 V1(IotaAttributeV1),
1012 V2(IotaAttributeV2),
1013}
1014
1015#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1017pub enum IotaAttributeV1 {
1018 Authenticator(AuthenticatorAttribute),
1019}
1020
1021#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1023pub enum IotaAttributeV2 {
1024 Authenticator(AuthenticatorAttribute),
1025 View,
1026}
1027
1028#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1029pub struct AuthenticatorAttribute {
1030 pub version: u8,
1031}
1032
1033impl IotaAttributeV1 {
1034 pub fn authenticator_attribute(version: u8) -> Self {
1035 IotaAttributeV1::Authenticator(AuthenticatorAttribute { version })
1036 }
1037}
1038
1039impl IotaAttributeV2 {
1040 pub fn authenticator_attribute(version: u8) -> Self {
1041 IotaAttributeV2::Authenticator(AuthenticatorAttribute { version })
1042 }
1043
1044 pub fn view_attribute() -> Self {
1045 IotaAttributeV2::View
1046 }
1047}
1048
1049#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1051pub struct RuntimeModuleMetadataV1 {
1052 pub fun_attributes: BTreeMap<String, Vec<IotaAttributeV1>>,
1054}
1055
1056#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1058pub struct RuntimeModuleMetadataV2 {
1059 pub fun_attributes: BTreeMap<String, Vec<IotaAttributeV2>>,
1061}
1062
1063impl RuntimeModuleMetadataV1 {
1064 pub fn add_function_attribute(&mut self, function_name: String, attribute: IotaAttributeV1) {
1065 self.fun_attributes
1066 .entry(function_name)
1067 .or_default()
1068 .push(attribute);
1069 }
1070
1071 pub fn is_empty(&self) -> bool {
1072 self.fun_attributes.is_empty()
1073 }
1074
1075 pub fn fun_attributes_iter(&self) -> impl Iterator<Item = (&String, &Vec<IotaAttributeV1>)> {
1076 self.fun_attributes.iter()
1077 }
1078
1079 pub fn to_bcs_bytes(&self) -> Vec<u8> {
1080 bcs::to_bytes(&self).unwrap()
1082 }
1083}
1084
1085impl RuntimeModuleMetadataV2 {
1086 pub fn add_function_attribute(&mut self, function_name: String, attribute: IotaAttributeV2) {
1087 self.fun_attributes
1088 .entry(function_name)
1089 .or_default()
1090 .push(attribute);
1091 }
1092
1093 pub fn is_empty(&self) -> bool {
1094 self.fun_attributes.is_empty()
1095 }
1096 pub fn fun_attributes_iter(&self) -> impl Iterator<Item = (&String, &Vec<IotaAttributeV2>)> {
1097 self.fun_attributes.iter()
1098 }
1099
1100 pub fn to_bcs_bytes(&self) -> Vec<u8> {
1101 bcs::to_bytes(&self).unwrap()
1103 }
1104}
1105
1106#[derive(Debug, Clone, Serialize, Deserialize)]
1111pub enum PackageMetadata {
1112 V1(PackageMetadataV1),
1113}
1114
1115impl PackageMetadata {
1116 pub fn new_v1(
1119 uid: ObjectId,
1120 storage_id: ObjectId,
1121 runtime_id: ObjectId,
1122 package_version: u64,
1123 modules_metadata_map: BTreeMap<String, BTreeMap<String, TypeTag>>,
1124 ) -> Self {
1125 PackageMetadata::V1(PackageMetadataV1::new(
1126 uid,
1127 storage_id,
1128 runtime_id,
1129 package_version,
1130 modules_metadata_map,
1131 ))
1132 }
1133
1134 pub fn struct_tag(&self) -> StructTag {
1135 match self {
1136 PackageMetadata::V1(_) => StructTag::new_package_metadata_v1(),
1137 }
1138 }
1139
1140 pub fn to_bcs_bytes(&self) -> Vec<u8> {
1141 match self {
1142 PackageMetadata::V1(inner) => inner.to_bcs_bytes(),
1143 }
1144 }
1145}
1146
1147#[derive(Debug, Default, Serialize, Deserialize, Clone, Eq, PartialEq)]
1148pub struct PackageMetadataKey {
1149 dummy_field: bool,
1153}
1154
1155impl PackageMetadataKey {
1156 pub fn to_bcs_bytes(&self) -> Vec<u8> {
1157 bcs::to_bytes(&self).unwrap()
1159 }
1160}
1161
1162pub fn derive_package_metadata_id(package_storage_id: ObjectId) -> ObjectId {
1163 package_storage_id.derive_object_id(
1164 &StructTag::new_package_metadata_key().into(),
1165 &PackageMetadataKey::default().to_bcs_bytes(),
1166 )
1167}
1168
1169#[derive(Debug, Clone, Serialize, Deserialize)]
1171pub struct PackageMetadataV1 {
1172 pub uid: UID,
1174 pub storage_id: ID,
1178 pub runtime_id: ID,
1181 pub package_version: u64,
1183 pub modules_metadata: VecMap<String, ModuleMetadataV1>,
1185}
1186
1187impl PackageMetadataV1 {
1188 fn new(
1189 uid: ObjectId,
1190 storage_id: ObjectId,
1191 runtime_id: ObjectId,
1192 package_version: u64,
1193 modules_metadata_map: BTreeMap<String, BTreeMap<String, TypeTag>>,
1194 ) -> Self {
1195 let mut modules_metadata = VecMap { contents: vec![] };
1196
1197 for (module_name, module_metadata_map) in modules_metadata_map {
1198 let mut module_metadata = ModuleMetadataV1 {
1199 authenticator_metadata: vec![],
1200 };
1201 for (function_name, account_type) in module_metadata_map {
1202 module_metadata
1203 .authenticator_metadata
1204 .push(AuthenticatorMetadataV1 {
1205 function_name,
1206 account_type,
1207 });
1208 }
1209 modules_metadata.contents.push(Entry {
1210 key: module_name,
1211 value: module_metadata,
1212 });
1213 }
1214
1215 Self {
1216 uid: UID::new(uid),
1217 storage_id: ID::new(storage_id),
1218 runtime_id: ID::new(runtime_id),
1219 package_version,
1220 modules_metadata,
1221 }
1222 }
1223
1224 pub fn to_bcs_bytes(&self) -> Vec<u8> {
1225 bcs::to_bytes(&self).unwrap()
1227 }
1228}
1229
1230#[derive(Debug, Clone, Serialize, Deserialize)]
1232pub struct ModuleMetadataV1 {
1233 pub authenticator_metadata: Vec<AuthenticatorMetadataV1>,
1234}
1235
1236impl ModuleMetadataV1 {
1237 pub fn is_empty(&self) -> bool {
1238 self.authenticator_metadata.is_empty()
1239 }
1240}
1241
1242#[serde_as]
1244#[derive(Debug, Clone, Serialize, Deserialize)]
1245pub struct AuthenticatorMetadataV1 {
1246 pub function_name: String,
1247 #[serde_as(as = "TypeName")]
1248 pub account_type: TypeTag,
1249}
1250
1251#[cfg(test)]
1252mod tests {
1253 use iota_protocol_config::{Chain, ProtocolVersion};
1254
1255 use super::*;
1256
1257 const VERSION_WITHOUT_SYSTEM_PACKAGE_SIZE: u64 = 37;
1259
1260 fn config(version: u64) -> ProtocolConfig {
1261 ProtocolConfig::get_for_version(ProtocolVersion::new(version), Chain::Unknown)
1262 }
1263
1264 #[test]
1265 fn user_packages_keep_the_user_bound() {
1266 let protocol_config = config(ProtocolVersion::MAX.as_u64());
1267 let user_package = ObjectId::random();
1268
1269 assert!(!user_package.is_system_package());
1270 assert_eq!(
1271 max_package_size(user_package, &protocol_config),
1272 protocol_config.max_move_package_size(),
1273 );
1274 }
1275
1276 #[test]
1277 fn system_packages_get_the_system_bound() {
1278 let protocol_config = config(ProtocolVersion::MAX.as_u64());
1279
1280 assert_eq!(
1281 max_package_size(ObjectId::FRAMEWORK, &protocol_config),
1282 protocol_config.max_move_system_package_size(),
1283 );
1284 assert!(
1285 protocol_config.max_move_system_package_size()
1286 > protocol_config.max_move_package_size(),
1287 );
1288 }
1289
1290 #[test]
1291 fn system_packages_fall_back_to_the_user_bound_when_unset() {
1292 let protocol_config = config(VERSION_WITHOUT_SYSTEM_PACKAGE_SIZE);
1293
1294 assert!(
1295 protocol_config
1296 .max_move_system_package_size_as_option()
1297 .is_none()
1298 );
1299 assert_eq!(
1300 max_package_size(ObjectId::FRAMEWORK, &protocol_config),
1301 protocol_config.max_move_package_size(),
1302 );
1303 }
1304}