diff --git a/.cargo/config b/.cargo/config index 0312fa7f565c1..385edeb08cb4b 100644 --- a/.cargo/config +++ b/.cargo/config @@ -22,6 +22,11 @@ move-clippy = [ "-Aclippy::new_without_default", "-Aclippy::box_default", "-Aclippy::manual_slice_size_calculation", + "-Aclippy::unwrap-or-default", + "-Aclippy::incorrect_partial_ord_impl_on_ord_type", + "-Aclippy::useless_attribute", + "-Aclippy::manual_while_let_some", + "-Aclippy::redundant_closure", ] [build] diff --git a/crates/mysten-common/src/sync/notify_once.rs b/crates/mysten-common/src/sync/notify_once.rs index b9e7c6a5234a0..d83f2a7da1fcd 100644 --- a/crates/mysten-common/src/sync/notify_once.rs +++ b/crates/mysten-common/src/sync/notify_once.rs @@ -35,7 +35,9 @@ impl NotifyOnce { /// This method returns errors if called more then once #[allow(clippy::result_unit_err)] pub fn notify(&self) -> Result<(), ()> { - let Some(notify) = self.notify.lock().take() else { return Err(()) }; + let Some(notify) = self.notify.lock().take() else { + return Err(()); + }; // At this point all `register` either registered with current notify, // or will be returning immediately notify.notify_waiters(); diff --git a/crates/mysten-common/src/sync/notify_read.rs b/crates/mysten-common/src/sync/notify_read.rs index c9dc6a117590b..698f7d35bb801 100644 --- a/crates/mysten-common/src/sync/notify_read.rs +++ b/crates/mysten-common/src/sync/notify_read.rs @@ -96,7 +96,9 @@ impl NotifyRead { fn cleanup(&self, key: &K) { let mut pending = self.pending(key); // it is possible that registration was fulfilled before we get here - let Some(registrations) = pending.get_mut(key) else { return; }; + let Some(registrations) = pending.get_mut(key) else { + return; + }; let mut count_deleted = 0usize; registrations.retain(|s| { let delete = s.is_closed(); diff --git a/crates/mysten-metrics/src/histogram.rs b/crates/mysten-metrics/src/histogram.rs index a9973021dcebb..2125ac3c35c3c 100644 --- a/crates/mysten-metrics/src/histogram.rs +++ b/crates/mysten-metrics/src/histogram.rs @@ -109,7 +109,7 @@ impl HistogramVec { register_int_counter_vec_with_registry!(sum_name, desc, labels, registry).unwrap(); let count = register_int_counter_vec_with_registry!(count_name, desc, labels, registry).unwrap(); - let labels: Vec<_> = labels.iter().cloned().chain(["pct"].into_iter()).collect(); + let labels: Vec<_> = labels.iter().cloned().chain(["pct"]).collect(); let gauge = register_int_gauge_vec_with_registry!(name, desc, &labels, registry).unwrap(); Self::new(gauge, sum, count, percentiles, name) } diff --git a/crates/mysten-metrics/src/metered_channel.rs b/crates/mysten-metrics/src/metered_channel.rs index 088896a6f52bf..70136b2598cf4 100644 --- a/crates/mysten-metrics/src/metered_channel.rs +++ b/crates/mysten-metrics/src/metered_channel.rs @@ -17,7 +17,7 @@ use tokio::sync::mpsc::{ #[path = "tests/metered_channel_tests.rs"] mod metered_channel_tests; -/// An [`mpsc::Sender`](tokio::sync::mpsc::Sender) with an [`IntGauge`] +/// An [`mpsc::Sender`] with an [`IntGauge`] /// counting the number of currently queued items. #[derive(Debug)] pub struct Sender { @@ -34,7 +34,7 @@ impl Clone for Sender { } } -/// An [`mpsc::Receiver`](tokio::sync::mpsc::Receiver) with an [`IntGauge`] +/// An [`mpsc::Receiver`] with an [`IntGauge`] /// counting the number of currently queued items. #[derive(Debug)] pub struct Receiver { diff --git a/crates/sui-aws-orchestrator/src/measurement.rs b/crates/sui-aws-orchestrator/src/measurement.rs index 65bdffa040592..0b2ac4e5cab89 100644 --- a/crates/sui-aws-orchestrator/src/measurement.rs +++ b/crates/sui-aws-orchestrator/src/measurement.rs @@ -198,7 +198,7 @@ impl MeasurementsCollection { pub fn add(&mut self, scraper_id: ScraperId, measurement: Measurement) { self.scrapers .entry(scraper_id) - .or_insert_with(Vec::new) + .or_default() .push(measurement); } diff --git a/crates/sui-aws-orchestrator/src/protocol/sui.rs b/crates/sui-aws-orchestrator/src/protocol/sui.rs index 1ad34216a910e..a869cbe7efdf8 100644 --- a/crates/sui-aws-orchestrator/src/protocol/sui.rs +++ b/crates/sui-aws-orchestrator/src/protocol/sui.rs @@ -259,7 +259,7 @@ impl ProtocolMetrics for SuiProtocol { .validator_config_info .expect("No validator in genesis") .iter() - .zip(instances.into_iter()) + .zip(instances) .map(|(config, instance)| { let path = format!( "{}:{}{}", diff --git a/crates/sui-benchmark/src/bank.rs b/crates/sui-benchmark/src/bank.rs index 6a466b90128e5..1b64e51615b62 100644 --- a/crates/sui-benchmark/src/bank.rs +++ b/crates/sui-benchmark/src/bank.rs @@ -98,7 +98,7 @@ impl BenchmarkBank { async fn pay_sui( &mut self, coin_configs: &[GasCoinConfig], - mut init_coin: &mut Gas, + init_coin: &mut Gas, gas_price: u64, ) -> Result { let recipient_addresses: Vec = coin_configs.iter().map(|g| g.address).collect(); diff --git a/crates/sui-cluster-test/src/test_case/shared_object_test.rs b/crates/sui-cluster-test/src/test_case/shared_object_test.rs index f52c52714b1a5..02bab303b7930 100644 --- a/crates/sui-cluster-test/src/test_case/shared_object_test.rs +++ b/crates/sui-cluster-test/src/test_case/shared_object_test.rs @@ -63,8 +63,11 @@ impl TestCaseImpl for SharedCounterTest { .mutated() .iter() .find_map(|obj| { - let Owner::Shared { initial_shared_version } = obj.owner else { - return None + let Owner::Shared { + initial_shared_version, + } = obj.owner + else { + return None; }; if obj.reference.object_id == counter_id diff --git a/crates/sui-core/src/authority.rs b/crates/sui-core/src/authority.rs index 57bb3b37c97ae..06de0a801e705 100644 --- a/crates/sui-core/src/authority.rs +++ b/crates/sui-core/src/authority.rs @@ -1670,8 +1670,10 @@ impl AuthorityState { ); assert_eq!(new_object.version(), oref.1, "tx_digest={:?} error processing object owner index, object {:?} from written has mismatched version. Actual: {}, expected: {}", tx_digest, id, new_object.version(), oref.1); - let Some(df_info) = self.try_create_dynamic_field_info(new_object, written, module_resolver) - .expect("try_create_dynamic_field_info should not fail.") else { + let Some(df_info) = self + .try_create_dynamic_field_info(new_object, written, module_resolver) + .expect("try_create_dynamic_field_info should not fail.") + else { // Skip indexing for non dynamic field objects. continue; }; @@ -2109,8 +2111,8 @@ impl AuthorityState { genesis_objects: &[Object], epoch_store: &Arc, ) -> SuiResult { - let Some(index_store) = &self.indexes else{ - return Ok(()) + let Some(index_store) = &self.indexes else { + return Ok(()); }; if !index_store.is_empty() { return Ok(()); @@ -2126,7 +2128,12 @@ impl AuthorityState { )), Owner::ObjectOwner(object_id) => { let id = o.id(); - let Some(info) = self.try_create_dynamic_field_info(o, &BTreeMap::new(), epoch_store.module_cache())? else{ + let Some(info) = self.try_create_dynamic_field_info( + o, + &BTreeMap::new(), + epoch_store.module_cache(), + )? + else { continue; }; new_dynamic_fields.push(((ObjectID::from(object_id), id), info)); @@ -2532,7 +2539,9 @@ impl AuthorityState { epoch_store: &AuthorityPerEpochStore, ) -> SuiResult> { let checkpoint = self.get_transaction_checkpoint_sequence(digest, epoch_store)?; - let Some(checkpoint) = checkpoint else { return Ok(None); }; + let Some(checkpoint) = checkpoint else { + return Ok(None); + }; let checkpoint = self .checkpoint_store .get_checkpoint_by_sequence_number(checkpoint)?; @@ -2540,7 +2549,9 @@ impl AuthorityState { } pub fn get_object_read(&self, object_id: &ObjectID) -> SuiResult { - let Some((object_key, store_object)) = self.database.get_latest_object_or_tombstone(*object_id)? else { + let Some((object_key, store_object)) = + self.database.get_latest_object_or_tombstone(*object_id)? + else { return Ok(ObjectRead::NotExists(*object_id)); }; if let Some(object_ref) = self @@ -2608,7 +2619,10 @@ impl AuthorityState { version: SequenceNumber, ) -> SuiResult { // Firstly we see if the object ever existed by getting its latest data - let Some(obj_ref) = self.database.get_latest_object_ref_or_tombstone(*object_id)? else { + let Some(obj_ref) = self + .database + .get_latest_object_ref_or_tombstone(*object_id)? + else { return Ok(PastObjectRead::ObjectNotExists(*object_id)); }; @@ -3626,7 +3640,9 @@ impl AuthorityState { system_package.dependencies().to_vec(), max_binary_format_version, no_extraneous_module_bytes, - ).await else { + ) + .await + else { return vec![]; }; results.push(obj_ref); @@ -3908,11 +3924,14 @@ impl AuthorityState { // since system packages are created during the current epoch, they should abide by the // rules of the current epoch, including the current epoch's max Move binary format version let config = epoch_store.protocol_config(); - let Some(next_epoch_system_package_bytes) = self.get_system_package_bytes( - next_epoch_system_packages.clone(), - config.move_binary_format_version(), - config.no_extraneous_module_bytes(), - ).await else { + let Some(next_epoch_system_package_bytes) = self + .get_system_package_bytes( + next_epoch_system_packages.clone(), + config.move_binary_format_version(), + config.no_extraneous_module_bytes(), + ) + .await + else { error!( "upgraded system packages {:?} are not locally available, cannot create \ ChangeEpochTx. validator binary must be upgraded to the correct version!", @@ -3926,7 +3945,9 @@ impl AuthorityState { // state sync, and execute it. This will upgrade the framework packages, reconfigure, // and most likely shut down in the new epoch (this validator likely doesn't support // the new protocol version, or else it should have had the packages.) - return Err(anyhow!("missing system packages: cannot form ChangeEpochTx")); + return Err(anyhow!( + "missing system packages: cannot form ChangeEpochTx" + )); }; let tx = if epoch_store diff --git a/crates/sui-core/src/authority/authority_notify_read.rs b/crates/sui-core/src/authority/authority_notify_read.rs index a28f290bb1f71..48fb5a27190fa 100644 --- a/crates/sui-core/src/authority/authority_notify_read.rs +++ b/crates/sui-core/src/authority/authority_notify_read.rs @@ -55,7 +55,7 @@ impl EffectsNotifyRead for Arc { let mut needs_wait = false; let mut results: FuturesUnordered<_> = effects .into_iter() - .zip(registrations.into_iter()) + .zip(registrations) .map(|(e, r)| match e { // Note that Some() clause also drops registration that is already fulfilled Some(ready) => Either::Left(futures::future::ready(ready)), @@ -100,7 +100,7 @@ impl EffectsNotifyRead for Arc { let results = effects_digests .into_iter() - .zip(registrations.into_iter()) + .zip(registrations) .map(|(a, r)| match a { // Note that Some() clause also drops registration that is already fulfilled Some(ready) => Either::Left(futures::future::ready(ready)), diff --git a/crates/sui-core/src/authority/authority_per_epoch_store.rs b/crates/sui-core/src/authority/authority_per_epoch_store.rs index 332611ea86415..63635220738bc 100644 --- a/crates/sui-core/src/authority/authority_per_epoch_store.rs +++ b/crates/sui-core/src/authority/authority_per_epoch_store.rs @@ -1296,7 +1296,13 @@ impl AuthorityPerEpochStore { let mut result = Vec::with_capacity(digests.len()); for (signatures, digest) in signatures.into_iter().zip(digests.iter()) { let Some(signatures) = signatures else { - return Err(SuiError::from(format!("Can not find user signature for checkpoint for transaction {:?}", digest).as_str())); + return Err(SuiError::from( + format!( + "Can not find user signature for checkpoint for transaction {:?}", + digest + ) + .as_str(), + )); }; result.push(signatures); } diff --git a/crates/sui-core/src/authority/authority_store.rs b/crates/sui-core/src/authority/authority_store.rs index dc6a7f1849607..85f1fbc9a7859 100644 --- a/crates/sui-core/src/authority/authority_store.rs +++ b/crates/sui-core/src/authority/authority_store.rs @@ -1496,7 +1496,7 @@ impl AuthorityStore { pub async fn revert_state_update(&self, tx_digest: &TransactionDigest) -> SuiResult { let Some(effects) = self.get_executed_effects(tx_digest)? else { debug!("Not reverting {:?} as it was not executed", tx_digest); - return Ok(()) + return Ok(()); }; info!(?tx_digest, ?effects, "reverting transaction"); @@ -1991,7 +1991,7 @@ impl ChildObjectResolver for AuthorityStore { let Some(child_object) = self.find_object_lt_or_eq_version(*child, child_version_upper_bound) else { - return Ok(None) + return Ok(None); }; let parent = *parent; @@ -2012,8 +2012,10 @@ impl ChildObjectResolver for AuthorityStore { receive_object_at_version: SequenceNumber, epoch_id: EpochId, ) -> SuiResult> { - let Some(recv_object) = self.get_object_by_key(receiving_object_id, receive_object_at_version)? else { - return Ok(None) + let Some(recv_object) = + self.get_object_by_key(receiving_object_id, receive_object_at_version)? + else { + return Ok(None); }; // Check for: diff --git a/crates/sui-core/src/authority/authority_store_pruner.rs b/crates/sui-core/src/authority/authority_store_pruner.rs index 9b600cf0bb431..1ac8b98cd7995 100644 --- a/crates/sui-core/src/authority/authority_store_pruner.rs +++ b/crates/sui-core/src/authority/authority_store_pruner.rs @@ -339,7 +339,12 @@ impl AuthorityStorePruner { let mut effects_to_prune = vec![]; loop { - let Some(ckpt) = checkpoint_store.certified_checkpoints.get(&(checkpoint_number + 1))? else {break;}; + let Some(ckpt) = checkpoint_store + .certified_checkpoints + .get(&(checkpoint_number + 1))? + else { + break; + }; let checkpoint = ckpt.into_inner(); // Skipping because checkpoint's epoch or checkpoint number is too new. // We have to respect the highest executed checkpoint watermark because there might be @@ -450,7 +455,9 @@ impl AuthorityStorePruner { } sst_file_for_compaction = Some(sst_file); } - let Some(sst_file) = sst_file_for_compaction else {return Ok(None);}; + let Some(sst_file) = sst_file_for_compaction else { + return Ok(None); + }; info!( "Manual compaction of sst file {:?}. Size: {:?}, level: {:?}", sst_file.name, sst_file.size, sst_file.level diff --git a/crates/sui-core/src/authority/authority_store_tables.rs b/crates/sui-core/src/authority/authority_store_tables.rs index 83d273ecaeae8..b6226ff69527b 100644 --- a/crates/sui-core/src/authority/authority_store_tables.rs +++ b/crates/sui-core/src/authority/authority_store_tables.rs @@ -154,10 +154,12 @@ impl AuthorityPerpetualTables { object_id: ObjectID, version: SequenceNumber, ) -> Option { - let Ok(iter) = self.objects + let Ok(iter) = self + .objects .range_iter(ObjectKey::min_for_id(&object_id)..=ObjectKey::max_for_id(&object_id)) - .skip_prior_to(&ObjectKey(object_id, version))else { - return None + .skip_prior_to(&ObjectKey(object_id, version)) + else { + return None; }; iter.reverse() .next() @@ -186,7 +188,9 @@ impl AuthorityPerpetualTables { object_key: &ObjectKey, store_object: StoreObjectWrapper, ) -> Result, SuiError> { - let StoreObject::Value(store_object) = store_object.migrate().into_inner() else {return Ok(None)}; + let StoreObject::Value(store_object) = store_object.migrate().into_inner() else { + return Ok(None); + }; Ok(Some(self.construct_object(object_key, store_object)?)) } diff --git a/crates/sui-core/src/checkpoints/causal_order.rs b/crates/sui-core/src/checkpoints/causal_order.rs index fdff6ab43c696..d16de5baddee8 100644 --- a/crates/sui-core/src/checkpoints/causal_order.rs +++ b/crates/sui-core/src/checkpoints/causal_order.rs @@ -151,9 +151,13 @@ impl RWLockDependencyBuilder { digest: TransactionDigest, v: &mut BTreeSet, ) { - let Some(overwrites) = self.overwrite_versions.get(&digest) else {return;}; + let Some(overwrites) = self.overwrite_versions.get(&digest) else { + return; + }; for obj_ver in overwrites { - let Some(reads) = self.read_version.get(obj_ver) else {continue;}; + let Some(reads) = self.read_version.get(obj_ver) else { + continue; + }; for dep in reads { trace!( "Assuming additional dependency when constructing checkpoint {:?} -> {:?}", diff --git a/crates/sui-core/src/checkpoints/checkpoint_executor/mod.rs b/crates/sui-core/src/checkpoints/checkpoint_executor/mod.rs index f74714f95dc93..a11fd6a09a841 100644 --- a/crates/sui-core/src/checkpoints/checkpoint_executor/mod.rs +++ b/crates/sui-core/src/checkpoints/checkpoint_executor/mod.rs @@ -290,10 +290,9 @@ impl CheckpointExecutor { let Some(latest_synced_checkpoint) = self .checkpoint_store .get_highest_synced_checkpoint() - .expect("Failed to read highest synced checkpoint") else { - debug!( - "No checkpoints to schedule, highest synced checkpoint is None", - ); + .expect("Failed to read highest synced checkpoint") + else { + debug!("No checkpoints to schedule, highest synced checkpoint is None",); return; }; @@ -936,7 +935,7 @@ fn get_unexecuted_transactions( let executable_txns: Vec<_> = if let Some(full_contents_txns) = full_contents_txns { unexecuted_txns .into_iter() - .zip(expected_effects_digests.into_iter()) + .zip(expected_effects_digests) .map(|(tx_digest, expected_effects_digest)| { let tx = &full_contents_txns.get(&tx_digest).unwrap().transaction; ( @@ -954,7 +953,7 @@ fn get_unexecuted_transactions( .multi_get_transaction_blocks(&unexecuted_txns) .expect("Failed to get checkpoint txes from store") .into_iter() - .zip(expected_effects_digests.into_iter()) + .zip(expected_effects_digests) .enumerate() .map(|(i, (tx, expected_effects_digest))| { let tx = tx.unwrap_or_else(|| diff --git a/crates/sui-core/src/checkpoints/checkpoint_executor/tests.rs b/crates/sui-core/src/checkpoints/checkpoint_executor/tests.rs index 35754958a8d61..1256ff4654abb 100644 --- a/crates/sui-core/src/checkpoints/checkpoint_executor/tests.rs +++ b/crates/sui-core/src/checkpoints/checkpoint_executor/tests.rs @@ -38,12 +38,10 @@ pub async fn test_checkpoint_executor_crash_recovery() { CommitteeFixture, ) = init_executor_test(buffer_size, checkpoint_store.clone()).await; - assert!(matches!( - checkpoint_store - .get_highest_executed_checkpoint_seq_number() - .unwrap(), - None, - )); + assert!(checkpoint_store + .get_highest_executed_checkpoint_seq_number() + .unwrap() + .is_none()); let checkpoints = sync_new_checkpoints( &checkpoint_store, &checkpoint_sender, @@ -127,12 +125,10 @@ pub async fn test_checkpoint_executor_cross_epoch() { let epoch = epoch_store.epoch(); assert_eq!(epoch, 0); - assert!(matches!( - checkpoint_store - .get_highest_executed_checkpoint_seq_number() - .unwrap(), - None, - )); + assert!(checkpoint_store + .get_highest_executed_checkpoint_seq_number() + .unwrap() + .is_none()); // sync 20 checkpoints let cold_start_checkpoints = sync_new_checkpoints( @@ -291,12 +287,10 @@ pub async fn test_reconfig_crash_recovery() { ) .await; - assert!(matches!( - checkpoint_store - .get_highest_executed_checkpoint_seq_number() - .unwrap(), - None, - )); + assert!(checkpoint_store + .get_highest_executed_checkpoint_seq_number() + .unwrap() + .is_none()); // sync 1 checkpoint let checkpoint = sync_new_checkpoints( diff --git a/crates/sui-core/src/checkpoints/mod.rs b/crates/sui-core/src/checkpoints/mod.rs index 3a7835422bef8..b70deb88072de 100644 --- a/crates/sui-core/src/checkpoints/mod.rs +++ b/crates/sui-core/src/checkpoints/mod.rs @@ -1160,7 +1160,7 @@ impl CheckpointBuilder { let effects = self.effects_store.multi_get_executed_effects(&pending)?; let effects = effects .into_iter() - .zip(pending.into_iter()) + .zip(pending) .map(|(opt, digest)| match opt { Some(x) => x, None => panic!( @@ -1250,7 +1250,12 @@ impl CheckpointAggregator { } current } else { - let Some(summary) = self.epoch_store.get_built_checkpoint_summary(next_to_certify)? else { return Ok(result); }; + let Some(summary) = self + .epoch_store + .get_built_checkpoint_summary(next_to_certify)? + else { + return Ok(result); + }; self.current = Some(CheckpointSignatureAggregator { next_index: 0, digest: summary.digest(), diff --git a/crates/sui-core/src/transaction_manager.rs b/crates/sui-core/src/transaction_manager.rs index 8f0a9f8b06954..3eb3ad947fabf 100644 --- a/crates/sui-core/src/transaction_manager.rs +++ b/crates/sui-core/src/transaction_manager.rs @@ -532,7 +532,7 @@ impl TransactionManager { ) .expect("Checking object existence cannot fail!") .into_iter() - .zip(input_object_cache_misses.into_iter()); + .zip(input_object_cache_misses); // After this point, the function cannot return early and must run to the end. Otherwise, // it can lead to data inconsistencies and potentially some transactions will never get diff --git a/crates/sui-core/src/transaction_orchestrator.rs b/crates/sui-core/src/transaction_orchestrator.rs index 6ce65c9a9394c..86afe50377a51 100644 --- a/crates/sui-core/src/transaction_orchestrator.rs +++ b/crates/sui-core/src/transaction_orchestrator.rs @@ -201,10 +201,7 @@ where ExecuteTransactionRequestType::WaitForLocalExecution ); - let Ok(result) = timeout( - WAIT_FOR_FINALITY_TIMEOUT, - ticket, - ).await else { + let Ok(result) = timeout(WAIT_FOR_FINALITY_TIMEOUT, ticket).await else { debug!(?tx_digest, "Timeout waiting for transaction finality."); self.metrics.wait_for_finality_timeout.inc(); return Err(QuorumDriverError::TimeoutBeforeFinality); diff --git a/crates/sui-core/src/unit_tests/authority_tests.rs b/crates/sui-core/src/unit_tests/authority_tests.rs index 86f5e29521611..de5361e9fe9e0 100644 --- a/crates/sui-core/src/unit_tests/authority_tests.rs +++ b/crates/sui-core/src/unit_tests/authority_tests.rs @@ -1482,10 +1482,14 @@ async fn test_handle_transfer_transaction_ok() { ); // Check the final state of the locks - let Some(envelope) = authority_state.get_transaction_lock( - &(object_id, before_object_version, object.digest()), - &authority_state.epoch_store_for_testing(), - ).await.unwrap() else { + let Some(envelope) = authority_state + .get_transaction_lock( + &(object_id, before_object_version, object.digest()), + &authority_state.epoch_store_for_testing(), + ) + .await + .unwrap() + else { panic!("No verified envelope for transaction"); }; @@ -3064,7 +3068,10 @@ async fn test_invalid_mutable_clock_parameter() { let transaction = to_sender_signed_transaction(tx_data, &sender_key); let transaction = authority_state.verify_transaction(transaction).unwrap(); - let Err(e) = authority_state.handle_transaction(&epoch_store, transaction).await else { + let Err(e) = authority_state + .handle_transaction(&epoch_store, transaction) + .await + else { panic!("Expected handling transaction to fail"); }; diff --git a/crates/sui-core/src/unit_tests/execution_driver_tests.rs b/crates/sui-core/src/unit_tests/execution_driver_tests.rs index 1fbcd94b0f4d8..258ef56f197ff 100644 --- a/crates/sui-core/src/unit_tests/execution_driver_tests.rs +++ b/crates/sui-core/src/unit_tests/execution_driver_tests.rs @@ -512,8 +512,9 @@ async fn test_per_object_overload() { .unwrap(); let (shared_counter_ref, owner) = create_counter_effects.created()[0]; let Owner::Shared { - initial_shared_version: shared_counter_initial_version - } = owner else { + initial_shared_version: shared_counter_initial_version, + } = owner + else { panic!("Not a shared object! {:?} {:?}", shared_counter_ref, owner); }; diff --git a/crates/sui-core/src/unit_tests/move_package_publish_tests.rs b/crates/sui-core/src/unit_tests/move_package_publish_tests.rs index 12db840d7fff7..fa469a6263ab0 100644 --- a/crates/sui-core/src/unit_tests/move_package_publish_tests.rs +++ b/crates/sui-core/src/unit_tests/move_package_publish_tests.rs @@ -52,9 +52,8 @@ async fn test_publishing_with_unpublished_deps() { ) .await; - let ObjectRead::Exists(read_ref, package_obj, _) = authority - .get_object_read(&package.0) - .unwrap() + let ObjectRead::Exists(read_ref, package_obj, _) = + authority.get_object_read(&package.0).unwrap() else { panic!("Can't read package") }; @@ -209,7 +208,7 @@ async fn test_generate_lock_file() { .read_to_string(&mut lock_file_contents) .expect("Error reading Move.lock file"); - let expected = expect![[r##" + let expected = expect![[r#" # @generated by Move, please check-in and do not edit manually. [move] @@ -241,7 +240,7 @@ async fn test_generate_lock_file() { dependencies = [ { name = "MoveStdlib" }, ] - "##]]; + "#]]; expected.assert_eq(lock_file_contents.as_str()); } @@ -296,7 +295,7 @@ async fn test_custom_property_check_unpublished_dependencies() { check_unpublished_dependencies(&gather_published_ids(&resolution_graph).1.unpublished) .err() .unwrap() - else { + else { panic!("Expected ModulePublishFailure") }; diff --git a/crates/sui-core/src/unit_tests/narwhal_manager_tests.rs b/crates/sui-core/src/unit_tests/narwhal_manager_tests.rs index 5685757e54cc4..1e323abb9f8ef 100644 --- a/crates/sui-core/src/unit_tests/narwhal_manager_tests.rs +++ b/crates/sui-core/src/unit_tests/narwhal_manager_tests.rs @@ -138,7 +138,7 @@ async fn test_narwhal_manager() { latest_protocol_version(), worker_cache.clone(), execution_state, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, ) .await; @@ -200,7 +200,7 @@ async fn test_narwhal_manager() { latest_protocol_version(), worker_cache.clone(), execution_state, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, ) .await; diff --git a/crates/sui-core/src/unit_tests/transfer_to_object_tests.rs b/crates/sui-core/src/unit_tests/transfer_to_object_tests.rs index 745dbea520dc6..9e323e42792cd 100644 --- a/crates/sui-core/src/unit_tests/transfer_to_object_tests.rs +++ b/crates/sui-core/src/unit_tests/transfer_to_object_tests.rs @@ -44,14 +44,18 @@ use move_core_types::ident_str; macro_rules! transfer_test_runner { (gas_objects: $num:expr, $expr:expr) => { let runner = TestRunner::new_with_objects("tto", $num, false).await; + #[allow(clippy::redundant_closure_call)] $expr(runner).await; let runner = TestRunner::new_with_objects("tto", $num, true).await; + #[allow(clippy::redundant_closure_call)] $expr(runner).await; }; ($expr:expr) => { let runner = TestRunner::new("tto", false).await; + #[allow(clippy::redundant_closure_call)] $expr(runner).await; let runner = TestRunner::new("tto", true).await; + #[allow(clippy::redundant_closure_call)] $expr(runner).await; }; } diff --git a/crates/sui-e2e-tests/tests/reconfiguration_tests.rs b/crates/sui-e2e-tests/tests/reconfiguration_tests.rs index cff33dfa22995..22b82eeaca7de 100644 --- a/crates/sui-e2e-tests/tests/reconfiguration_tests.rs +++ b/crates/sui-e2e-tests/tests/reconfiguration_tests.rs @@ -594,8 +594,7 @@ async fn test_reconfig_with_committee_change_stress() { .build() .await; - while !candidates.is_empty() { - let v1 = candidates.pop().unwrap(); + while let Some(v1) = candidates.pop() { let v2 = candidates.pop().unwrap(); execute_add_validator_transactions(&test_cluster, &v1).await; execute_add_validator_transactions(&test_cluster, &v2).await; diff --git a/crates/sui-e2e-tests/tests/shared_objects_version_tests.rs b/crates/sui-e2e-tests/tests/shared_objects_version_tests.rs index 0b527e9a665a0..982c5865912df 100644 --- a/crates/sui-e2e-tests/tests/shared_objects_version_tests.rs +++ b/crates/sui-e2e-tests/tests/shared_objects_version_tests.rs @@ -29,7 +29,10 @@ async fn objects_transitioning_to_shared_remember_their_previous_version() { assert_ne!(counter.1, OBJECT_START_VERSION); let ExecutionFailureStatus::MoveAbort(location, code) = - env.share_counter(counter).await.unwrap_err() else { panic!() }; + env.share_counter(counter).await.unwrap_err() + else { + panic!() + }; assert_eq!(location.module.address(), &SUI_FRAMEWORK_ADDRESS); assert_eq!(location.module.name().as_str(), "transfer"); assert_eq!(code, 0 /* ESharedNonNewObject */); @@ -42,7 +45,10 @@ async fn shared_object_owner_doesnt_change_on_write() { let (inc_counter, _) = env.increment_owned_counter(counter).await; let ExecutionFailureStatus::MoveAbort(location, code) = - env.share_counter(inc_counter).await.unwrap_err() else { panic!() }; + env.share_counter(inc_counter).await.unwrap_err() + else { + panic!() + }; assert_eq!(location.module.address(), &SUI_FRAMEWORK_ADDRESS); assert_eq!(location.module.name().as_str(), "transfer"); assert_eq!(code, 0 /* ESharedNonNewObject */); @@ -55,7 +61,10 @@ async fn initial_shared_version_mismatch_start_version() { let (counter, _) = env.increment_owned_counter(counter).await; let ExecutionFailureStatus::MoveAbort(location, code) = - env.share_counter(counter).await.unwrap_err() else { panic!() }; + env.share_counter(counter).await.unwrap_err() + else { + panic!() + }; assert_eq!(location.module.address(), &SUI_FRAMEWORK_ADDRESS); assert_eq!(location.module.name().as_str(), "transfer"); assert_eq!(code, 0 /* ESharedNonNewObject */); @@ -67,7 +76,10 @@ async fn initial_shared_version_mismatch_current_version() { let (counter, _) = env.create_counter().await; let ExecutionFailureStatus::MoveAbort(location, code) = - env.share_counter(counter).await.unwrap_err() else { panic!() }; + env.share_counter(counter).await.unwrap_err() + else { + panic!() + }; assert_eq!(location.module.address(), &SUI_FRAMEWORK_ADDRESS); assert_eq!(location.module.name().as_str(), "transfer"); assert_eq!(code, 0 /* ESharedNonNewObject */); diff --git a/crates/sui-faucet/src/faucet/simple_faucet.rs b/crates/sui-faucet/src/faucet/simple_faucet.rs index 900d1946ff7dd..5c5b142f9f89f 100644 --- a/crates/sui-faucet/src/faucet/simple_faucet.rs +++ b/crates/sui-faucet/src/faucet/simple_faucet.rs @@ -236,7 +236,8 @@ impl SimpleFaucet { // If the gas candidate queue is exhausted, the request will be suspended indefinitely until // a producer puts in more candidate gas objects. At the same time, other requests will be // blocked by the lock acquisition as well. - let Ok(mut consumer) = tokio::time::timeout(LOCK_TIMEOUT, self.consumer.lock()).await else { + let Ok(mut consumer) = tokio::time::timeout(LOCK_TIMEOUT, self.consumer.lock()).await + else { error!(?uuid, "Timeout when getting consumer lock"); return None; }; @@ -261,7 +262,9 @@ impl SimpleFaucet { // If the gas candidate queue is exhausted, the request will be suspended indefinitely until // a producer puts in more candidate gas objects. At the same time, other requests will be // blocked by the lock acquisition as well. - let Ok(mut batch_consumer) = tokio::time::timeout(LOCK_TIMEOUT, self.batch_consumer.lock()).await else { + let Ok(mut batch_consumer) = + tokio::time::timeout(LOCK_TIMEOUT, self.batch_consumer.lock()).await + else { error!(?uuid, "Timeout when getting batch consumer lock"); return None; }; @@ -760,7 +763,7 @@ impl SimpleFaucet { // Insert the coins into the map based on the destination address address_coins_map .entry(owner.get_owner_address().unwrap()) - .or_insert_with(Vec::new) + .or_default() .push(coin_obj_ref); }); @@ -775,7 +778,7 @@ impl SimpleFaucet { let index = *request_count.entry(addy).or_insert(0); // The address coin map should contain the coins transferred in the given request. - let coins_created_for_address = address_coins_map.entry(addy).or_insert_with(Vec::new); + let coins_created_for_address = address_coins_map.entry(addy).or_default(); if number_of_coins as u64 + index > coins_created_for_address.len() as u64 { return Err(FaucetError::CoinAmountTransferredIncorrect(format!( @@ -950,7 +953,7 @@ pub async fn batch_gather( ) -> Result<(), FaucetError> { // Gather the rest of the batch after the first item has been taken. for _ in 1..batch_request_size { - let Some(req) = request_consumer.recv().await else { + let Some(req) = request_consumer.recv().await else { error!("Request consumer queue closed"); return Err(FaucetError::ChannelClosed); }; @@ -1459,7 +1462,9 @@ mod tests { let faucet_address = faucet.active_address; let uuid = Uuid::new_v4(); - let GasCoinResponse::ValidGasCoin(coin_id) = faucet.prepare_gas_coin(100, uuid, false).await else { + let GasCoinResponse::ValidGasCoin(coin_id) = + faucet.prepare_gas_coin(100, uuid, false).await + else { panic!("prepare_gas_coin did not give a valid coin.") }; @@ -1743,7 +1748,9 @@ mod tests { let faucet_address = faucet.active_address; let uuid = Uuid::new_v4(); - let GasCoinResponse::ValidGasCoin(coin_id) = faucet.prepare_gas_coin(100, uuid, false).await else { + let GasCoinResponse::ValidGasCoin(coin_id) = + faucet.prepare_gas_coin(100, uuid, false).await + else { panic!("prepare_gas_coin did not give a valid coin.") }; diff --git a/crates/sui-faucet/src/main.rs b/crates/sui-faucet/src/main.rs index e6e98b9ab6d8e..a6143b23b2e25 100644 --- a/crates/sui-faucet/src/main.rs +++ b/crates/sui-faucet/src/main.rs @@ -146,7 +146,7 @@ async fn batch_request_gas( Json(BatchFaucetResponse::from(FaucetError::Internal( "Input Error.".to_string(), ))), - ) + ); }; if state.config.batch_enabled { diff --git a/crates/sui-genesis-builder/src/lib.rs b/crates/sui-genesis-builder/src/lib.rs index 71e1dd5168d3b..edf00f9fadb02 100644 --- a/crates/sui-genesis-builder/src/lib.rs +++ b/crates/sui-genesis-builder/src/lib.rs @@ -454,8 +454,8 @@ impl Builder { .iter() .find(|(_k, (o, s))| { let Owner::AddressOwner(owner) = &o.owner else { - panic!("gas object owner must be address owner"); - }; + panic!("gas object owner must be address owner"); + }; *owner == allocation.recipient_address && s.principal() == allocation.amount_mist && s.pool_id() == staking_pool_id @@ -960,7 +960,7 @@ fn process_package( } let loaded_dependencies: Vec<_> = dependencies .iter() - .zip(dependency_objects.into_iter()) + .zip(dependency_objects) .filter_map(|(dependency, object)| { Some(( InputObjectKind::MovePackage(*dependency), diff --git a/crates/sui-graphql-rpc/src/context_data/db_data_provider.rs b/crates/sui-graphql-rpc/src/context_data/db_data_provider.rs index d48b1ec167e98..f8cdbb2c99162 100644 --- a/crates/sui-graphql-rpc/src/context_data/db_data_provider.rs +++ b/crates/sui-graphql-rpc/src/context_data/db_data_provider.rs @@ -107,7 +107,7 @@ impl PgManager { config: Option, ) -> Result { // TODO (wlmyng): support config - let mut config = config.unwrap_or(PgConnectionPoolConfig::default()); + let mut config = config.unwrap_or_default(); config.set_pool_size(30); let inner = IndexerReader::new_with_config(db_url, config) .map_err(|e| Error::Internal(e.to_string()))?; diff --git a/crates/sui-graphql-rpc/src/extensions/logger.rs b/crates/sui-graphql-rpc/src/extensions/logger.rs index c6be25f8618a7..a0b6166a45812 100644 --- a/crates/sui-graphql-rpc/src/extensions/logger.rs +++ b/crates/sui-graphql-rpc/src/extensions/logger.rs @@ -54,9 +54,7 @@ struct LoggerExtension { impl LoggerExtension { async fn set_session_id(&self, ip: Option) { - let ip_component = ip - .map(|ip| format!("{}-", ip)) - .unwrap_or_else(|| "".to_string()); + let ip_component = ip.map(|ip| format!("{}-", ip)).unwrap_or_default(); let uuid_component = format!("{}", Uuid::new_v4()); *self.session_id.lock().await = format!("{}{}", ip_component, uuid_component); } diff --git a/crates/sui-graphql-rpc/src/server/version.rs b/crates/sui-graphql-rpc/src/server/version.rs index 2550d73949c74..d5191fbf0ee48 100644 --- a/crates/sui-graphql-rpc/src/server/version.rs +++ b/crates/sui-graphql-rpc/src/server/version.rs @@ -73,7 +73,8 @@ pub(crate) async fn check_version_middleware( code::BAD_REQUEST, format!("Failed to parse {VERSION_HEADER}: Not a UTF8 string."), ), - ).into_response(); + ) + .into_response(); }; let Some((year, month)) = parse_version(req_version) else { @@ -86,7 +87,8 @@ pub(crate) async fn check_version_middleware( . version.", ), ), - ).into_response(); + ) + .into_response(); }; if year != RPC_VERSION_YEAR || month != RPC_VERSION_MONTH { diff --git a/crates/sui-graphql-rpc/src/types/address.rs b/crates/sui-graphql-rpc/src/types/address.rs index a201513943de2..3591675d53a15 100644 --- a/crates/sui-graphql-rpc/src/types/address.rs +++ b/crates/sui-graphql-rpc/src/types/address.rs @@ -29,6 +29,7 @@ pub(crate) enum AddressTransactionBlockRelationship { Paid, // Transactions that were paid for by this address } +#[allow(clippy::diverging_sub_expression)] #[allow(unreachable_code)] #[allow(unused_variables)] #[Object] diff --git a/crates/sui-graphql-rpc/src/types/object.rs b/crates/sui-graphql-rpc/src/types/object.rs index df4ba7d2ddc2b..0e66569210b0f 100644 --- a/crates/sui-graphql-rpc/src/types/object.rs +++ b/crates/sui-graphql-rpc/src/types/object.rs @@ -57,6 +57,7 @@ pub(crate) struct ObjectKey { version: u64, } +#[allow(clippy::diverging_sub_expression)] #[allow(unreachable_code)] #[allow(unused_variables)] #[Object] diff --git a/crates/sui-graphql-rpc/src/types/owner.rs b/crates/sui-graphql-rpc/src/types/owner.rs index 0b4022d356ab3..7c25e39a1f580 100644 --- a/crates/sui-graphql-rpc/src/types/owner.rs +++ b/crates/sui-graphql-rpc/src/types/owner.rs @@ -78,6 +78,7 @@ pub(crate) struct Owner { pub address: SuiAddress, } +#[allow(clippy::diverging_sub_expression)] #[allow(unreachable_code)] #[allow(unused_variables)] #[Object] diff --git a/crates/sui-graphql-rpc/src/types/stake.rs b/crates/sui-graphql-rpc/src/types/stake.rs index 715e5b5f188c9..611c3c6f1b6ad 100644 --- a/crates/sui-graphql-rpc/src/types/stake.rs +++ b/crates/sui-graphql-rpc/src/types/stake.rs @@ -5,6 +5,7 @@ use async_graphql::*; pub(crate) struct Stake; +#[allow(clippy::diverging_sub_expression)] #[allow(unreachable_code)] #[allow(unused_variables)] #[Object] diff --git a/crates/sui-indexer/src/indexer_reader.rs b/crates/sui-indexer/src/indexer_reader.rs index 2953424e8fd40..5dd9ef8bf789c 100644 --- a/crates/sui-indexer/src/indexer_reader.rs +++ b/crates/sui-indexer/src/indexer_reader.rs @@ -1135,7 +1135,7 @@ impl IndexerReader { .map(StoredObject::try_into_expectant_dynamic_field_info) .collect::, _>>()?; - for mut df in dynamic_fields.iter_mut() { + for df in dynamic_fields.iter_mut() { if let Some(obj_ref) = object_refs.get(&df.object_id) { df.version = obj_ref.1; df.digest = obj_ref.2; diff --git a/crates/sui-indexer/src/store/pg_indexer_store.rs b/crates/sui-indexer/src/store/pg_indexer_store.rs index 62273388f215e..36ff4d8192840 100644 --- a/crates/sui-indexer/src/store/pg_indexer_store.rs +++ b/crates/sui-indexer/src/store/pg_indexer_store.rs @@ -72,7 +72,7 @@ use crate::PgConnectionPool; const MAX_EVENT_PAGE_SIZE: usize = 1000; const PG_COMMIT_CHUNK_SIZE: usize = 1000; -const GET_PARTITION_SQL: &str = r#" +const GET_PARTITION_SQL: &str = r" SELECT parent.relname AS table_name, MAX(SUBSTRING(child.relname FROM '\d$')) AS last_partition FROM pg_inherits @@ -82,7 +82,7 @@ FROM pg_inherits JOIN pg_namespace nmsp_child ON nmsp_child.oid = child.relnamespace WHERE parent.relkind = 'p' GROUP BY table_name; -"#; +"; #[derive(QueryableByName, Debug, Clone)] struct TempDigestTable { diff --git a/crates/sui-json-rpc-types/src/sui_transaction.rs b/crates/sui-json-rpc-types/src/sui_transaction.rs index c18c1646f2216..33330d0bfd7dc 100644 --- a/crates/sui-json-rpc-types/src/sui_transaction.rs +++ b/crates/sui-json-rpc-types/src/sui_transaction.rs @@ -1226,7 +1226,9 @@ impl SuiProgrammableTransactionBlock { match command { Command::MoveCall(c) => { let id = ModuleId::new(c.package.into(), c.module.clone()); - let Some(types) = get_signature_types(id, c.function.as_ident_str(), module_cache) else { + let Some(types) = + get_signature_types(id, c.function.as_ident_str(), module_cache) + else { return result_types; }; for (arg, type_) in c.arguments.iter().zip(types) { diff --git a/crates/sui-json-rpc/src/read_api.rs b/crates/sui-json-rpc/src/read_api.rs index a9332c4f5b11f..40a054deb28cd 100644 --- a/crates/sui-json-rpc/src/read_api.rs +++ b/crates/sui-json-rpc/src/read_api.rs @@ -1096,8 +1096,12 @@ async fn get_display_fields( original_object: &Object, original_layout: &Option, ) -> Result { - let Some((object_type, layout)) = get_object_type_and_struct(original_object, original_layout)? else { - return Ok(DisplayFieldsResponse { data: None, error: None }); + let Some((object_type, layout)) = get_object_type_and_struct(original_object, original_layout)? + else { + return Ok(DisplayFieldsResponse { + data: None, + error: None, + }); }; if let Some(display_object) = get_display_object_by_type(kv_store, fullnode_api, &object_type).await? @@ -1238,10 +1242,10 @@ fn get_value_from_move_struct( ) -> Result { let parts: Vec<&str> = var_name.split('.').collect(); if parts.is_empty() { - return Err(anyhow!("Display template value cannot be empty"))?; + Err(anyhow!("Display template value cannot be empty"))?; } if parts.len() > MAX_DISPLAY_NESTED_LEVEL { - return Err(anyhow!( + Err(anyhow!( "Display template value nested depth cannot exist {}", MAX_DISPLAY_NESTED_LEVEL ))?; @@ -1257,13 +1261,13 @@ fn get_value_from_move_struct( if let Some(value) = fields.get(part) { current_value = value; } else { - return Err(anyhow!( + Err(anyhow!( "Field value {} cannot be found in struct", var_name ))?; } } else { - return Err(Error::UnexpectedError(format!( + Err(Error::UnexpectedError(format!( "Unexpected move struct type for field {}", var_name )))?; diff --git a/crates/sui-json/src/tests.rs b/crates/sui-json/src/tests.rs index 0c51cd5197026..7895ff91b6a20 100644 --- a/crates/sui-json/src/tests.rs +++ b/crates/sui-json/src/tests.rs @@ -560,7 +560,7 @@ fn test_basic_args_linter_top_level() { let addr = json!(format!("{address}")); // They have to be ordered - let args = vec![value, addr] + let args = [value, addr] .iter() .map(|q| SuiJsonValue::new(q.clone()).unwrap()) .collect(); @@ -596,7 +596,7 @@ fn test_basic_args_linter_top_level() { let addr = json!(format!("{address}")); // They have to be ordered - let args = vec![object_id, addr] + let args = [object_id, addr] .iter() .map(|q| SuiJsonValue::new(q.clone()).unwrap()) .collect(); diff --git a/crates/sui-move-build/src/lib.rs b/crates/sui-move-build/src/lib.rs index 0d2e15313ac33..d7ef1f0732e17 100644 --- a/crates/sui-move-build/src/lib.rs +++ b/crates/sui-move-build/src/lib.rs @@ -515,7 +515,7 @@ impl CompiledPackage { pub fn is_system_package(&self) -> bool { // System packages always have "published-at" addresses let Ok(published_at) = self.published_at else { - return false + return false; }; is_system_package(published_at) diff --git a/crates/sui-move-build/src/linters/custom_state_change.rs b/crates/sui-move-build/src/linters/custom_state_change.rs index 7b82dcd7234d8..38909184cfb31 100644 --- a/crates/sui-move-build/src/linters/custom_state_change.rs +++ b/crates/sui-move-build/src/linters/custom_state_change.rs @@ -91,7 +91,7 @@ impl SimpleAbsIntConstructor for CustomStateChangeVerifier { _init_state: &mut as SimpleAbsInt>::State, ) -> Option> { let Some(_) = &context.module else { - return None + return None; }; let MemberName::Function(fn_name) = context.member else { return None; diff --git a/crates/sui-move-build/src/linters/freeze_wrapped.rs b/crates/sui-move-build/src/linters/freeze_wrapped.rs index b5fe817a68de1..85fafdfbed7ea 100644 --- a/crates/sui-move-build/src/linters/freeze_wrapped.rs +++ b/crates/sui-move-build/src/linters/freeze_wrapped.rs @@ -103,7 +103,7 @@ impl<'a> TypingVisitorContext for Context<'a> { // not an (potentially dereferenced) N::Type_::Apply nor N::Type_::Param return false; }; - let N::Type_::Apply(_,tname, _) = &bt.value else { + let N::Type_::Apply(_, tname, _) = &bt.value else { // not a struct type return false; }; @@ -204,7 +204,7 @@ impl<'a> Context<'a> { ) -> Option { let sdef = self.program_info.struct_definition(&mident, &sname); let N::StructFields::Defined(sfields) = &sdef.fields else { - return None + return None; }; sfields.iter().find_map(|(_, fname, (_, ftype))| { let res = self.wraps_object(ftype); diff --git a/crates/sui-move-build/src/linters/self_transfer.rs b/crates/sui-move-build/src/linters/self_transfer.rs index 45b82d9a92898..867fbd3aa0372 100644 --- a/crates/sui-move-build/src/linters/self_transfer.rs +++ b/crates/sui-move-build/src/linters/self_transfer.rs @@ -86,7 +86,7 @@ impl SimpleAbsIntConstructor for SelfTransferVerifier { _init_state: &mut as SimpleAbsInt>::State, ) -> Option> { let Some(_) = &context.module else { - return None + return None; }; let MemberName::Function(name) = context.member else { diff --git a/crates/sui-move-build/src/linters/share_owned.rs b/crates/sui-move-build/src/linters/share_owned.rs index 0078fe137ad39..6614032ab1809 100644 --- a/crates/sui-move-build/src/linters/share_owned.rs +++ b/crates/sui-move-build/src/linters/share_owned.rs @@ -88,7 +88,7 @@ impl SimpleAbsIntConstructor for ShareOwnedVerifier { _init_state: &mut as SimpleAbsInt>::State, ) -> Option> { let Some(_) = &context.module else { - return None + return None; }; Some(ShareOwnedVerifierAI) } diff --git a/crates/sui-network/src/state_sync/mod.rs b/crates/sui-network/src/state_sync/mod.rs index 830466bc06a22..c88d7a56e34b6 100644 --- a/crates/sui-network/src/state_sync/mod.rs +++ b/crates/sui-network/src/state_sync/mod.rs @@ -826,7 +826,9 @@ async fn get_latest_from_peer( if !info.on_same_chain_as_us { return; } - let Some((highest_checkpoint, low_watermark)) = query_peer_for_latest_info(&mut client, timeout).await else { + let Some((highest_checkpoint, low_watermark)) = + query_peer_for_latest_info(&mut client, timeout).await + else { return; }; peer_heights @@ -1290,9 +1292,13 @@ where PeerCheckpointRequestType::Content, ) .with_checkpoint(*checkpoint.sequence_number()); - let Some(contents) = get_full_checkpoint_contents(peers, &store, &checkpoint, timeout).await else { + let Some(contents) = get_full_checkpoint_contents(peers, &store, &checkpoint, timeout).await + else { // Delay completion in case of error so we don't hammer the network with retries. - let duration = peer_heights.read().unwrap().wait_interval_when_no_peer_to_sync_content(); + let duration = peer_heights + .read() + .unwrap() + .wait_interval_when_no_peer_to_sync_content(); tokio::time::sleep(duration).await; return Err(checkpoint); }; diff --git a/crates/sui-node/src/lib.rs b/crates/sui-node/src/lib.rs index 379ccdf5a265d..d77b26b8edde9 100644 --- a/crates/sui-node/src/lib.rs +++ b/crates/sui-node/src/lib.rs @@ -278,10 +278,12 @@ impl SuiNode { let Ok(iss_provider) = OIDCProvider::from_iss(&id.iss) else { warn!( "JWK iss {:?} (retrieved from {:?}) is not a valid provider", - id.iss, - provider + id.iss, provider ); - metrics.invalid_jwks.with_label_values(&[&provider.to_string()]).inc(); + metrics + .invalid_jwks + .with_label_values(&[&provider.to_string()]) + .inc(); return false; }; diff --git a/crates/sui-proxy/src/admin.rs b/crates/sui-proxy/src/admin.rs index cab96d8457ff5..4090d2624ea00 100644 --- a/crates/sui-proxy/src/admin.rs +++ b/crates/sui-proxy/src/admin.rs @@ -209,8 +209,12 @@ pub fn create_server_cert_default_allow( pub fn create_server_cert_enforce_peer( peer_config: PeerValidationConfig, ) -> Result<(ServerConfig, Option), sui_tls::rustls::Error> { - let (Some(certificate_path), Some(private_key_path)) = (peer_config.certificate_file, peer_config.private_key) else { - return Err(sui_tls::rustls::Error::General("missing certs to initialize server".into())); + let (Some(certificate_path), Some(private_key_path)) = + (peer_config.certificate_file, peer_config.private_key) + else { + return Err(sui_tls::rustls::Error::General( + "missing certs to initialize server".into(), + )); }; let allower = SuiNodeProvider::new(peer_config.url, peer_config.interval); allower.poll_peer_list(); diff --git a/crates/sui-proxy/src/middleware.rs b/crates/sui-proxy/src/middleware.rs index 8553eb5fb8fb6..b6e21b78750d2 100644 --- a/crates/sui-proxy/src/middleware.rs +++ b/crates/sui-proxy/src/middleware.rs @@ -76,8 +76,11 @@ pub async fn expect_valid_public_key( let Some(peer) = allower.get(tls_connect_info.public_key().unwrap()) else { error!("node with unknown pub key tried to connect"); MIDDLEWARE_OPS - .with_label_values(&["expect_valid_public_key", "unknown-validator-connection-attempt"]) - .inc(); + .with_label_values(&[ + "expect_valid_public_key", + "unknown-validator-connection-attempt", + ]) + .inc(); return Err((StatusCode::FORBIDDEN, "unknown clients are not allowed")); }; request.extensions_mut().insert(peer); diff --git a/crates/sui-proxy/src/peers.rs b/crates/sui-proxy/src/peers.rs index e773fd052d5dd..afb1df819539a 100644 --- a/crates/sui-proxy/src/peers.rs +++ b/crates/sui-proxy/src/peers.rs @@ -208,17 +208,31 @@ fn extract(summary: SuiSystemStateSummary) -> impl Iterator { let Ok(p2p_address) = Multiaddr::try_from(vm.p2p_address) else { - error!("refusing to add peer to allow list; unable to decode multiaddr for {}", vm.name); - return None // scoped to filter_map + error!( + "refusing to add peer to allow list; unable to decode multiaddr for {}", + vm.name + ); + return None; // scoped to filter_map }; - debug!("adding public key {:?} for address {:?}", public_key, p2p_address); - Some((public_key.clone(), SuiPeer { name: vm.name, p2p_address, public_key })) // scoped to filter_map - }, + debug!( + "adding public key {:?} for address {:?}", + public_key, p2p_address + ); + Some(( + public_key.clone(), + SuiPeer { + name: vm.name, + p2p_address, + public_key, + }, + )) // scoped to filter_map + } Err(error) => { error!( - "unable to decode public key for name: {:?} sui_address: {:?} error: {error}", - vm.name, vm.sui_address); - None // scoped to filter_map + "unable to decode public key for name: {:?} sui_address: {:?} error: {error}", + vm.name, vm.sui_address + ); + None // scoped to filter_map } } }) diff --git a/crates/sui-replay/src/replay.rs b/crates/sui-replay/src/replay.rs index 241811f42f064..38a826426b056 100644 --- a/crates/sui-replay/src/replay.rs +++ b/crates/sui-replay/src/replay.rs @@ -1019,7 +1019,9 @@ impl LocalExec { return Ok(Some(obj.clone())); } - let Some(o) = self.download_latest_object(obj_id)? else { return Ok(None) }; + let Some(o) = self.download_latest_object(obj_id)? else { + return Ok(None); + }; if o.is_package() { assert!( @@ -1808,7 +1810,10 @@ impl ResourceResolver for LocalExec { ) -> SuiResult>> { // If package not present fetch it from the network or some remote location let Some(object) = self_.get_or_download_object( - &ObjectID::from(*address),false /* we expect a Move obj*/)? else { + &ObjectID::from(*address), + false, /* we expect a Move obj*/ + )? + else { return Ok(None); }; diff --git a/crates/sui-rosetta/src/operations.rs b/crates/sui-rosetta/src/operations.rs index 3395717a6197b..5f7a27381b070 100644 --- a/crates/sui-rosetta/src/operations.rs +++ b/crates/sui-rosetta/src/operations.rs @@ -64,7 +64,7 @@ impl IntoIterator for Operations { impl Operations { pub fn new(mut ops: Vec) -> Self { - for (index, mut op) in ops.iter_mut().enumerate() { + for (index, op) in ops.iter_mut().enumerate() { op.operation_identifier = (index as u64).into() } Self(ops) @@ -169,7 +169,9 @@ impl Operations { }; let OperationMetadata::Stake { validator } = metadata else { - return Err(Error::InvalidInput("Cannot find delegation info from metadata.".into())) + return Err(Error::InvalidInput( + "Cannot find delegation info from metadata.".into(), + )); }; Ok(InternalOperation::Stake { @@ -199,7 +201,9 @@ impl Operations { let stake_ids = if let Some(metadata) = op.metadata { let OperationMetadata::WithdrawStake { stake_ids } = metadata else { - return Err(Error::InvalidInput("Cannot find withdraw stake info from metadata.".into())) + return Err(Error::InvalidInput( + "Cannot find withdraw stake info from metadata.".into(), + )); }; stake_ids } else { diff --git a/crates/sui-rosetta/src/unit_tests/balance_changing_tx_tests.rs b/crates/sui-rosetta/src/unit_tests/balance_changing_tx_tests.rs index bdf3d9ba75f33..96544ea411483 100644 --- a/crates/sui-rosetta/src/unit_tests/balance_changing_tx_tests.rs +++ b/crates/sui-rosetta/src/unit_tests/balance_changing_tx_tests.rs @@ -184,7 +184,7 @@ async fn test_publish_and_move_call() { // TODO: Improve tx response to make it easier to find objects. let treasury = find_module_object(&object_changes, "::TreasuryCap"); let treasury = treasury.clone().reference.to_object_ref(); - let recipient = *addresses.choose(&mut OsRng::default()).unwrap(); + let recipient = *addresses.choose(&mut OsRng).unwrap(); let pt = { let mut builder = ProgrammableTransactionBuilder::new(); builder @@ -808,7 +808,7 @@ async fn get_random_sui( let obj = object.object().unwrap(); obj.is_gas_coin() && !except.contains(&obj.object_id) }) - .choose(&mut OsRng::default()) + .choose(&mut OsRng) .unwrap(); let coin = coin_resp.object().unwrap(); @@ -819,7 +819,7 @@ fn get_random_address(addresses: &[SuiAddress], except: Vec) -> SuiA *addresses .iter() .filter(|addr| !except.contains(*addr)) - .choose(&mut OsRng::default()) + .choose(&mut OsRng) .unwrap() } diff --git a/crates/sui-source-validation-service/src/lib.rs b/crates/sui-source-validation-service/src/lib.rs index 0c94f1f7f4d86..96f56b8766aa4 100644 --- a/crates/sui-source-validation-service/src/lib.rs +++ b/crates/sui-source-validation-service/src/lib.rs @@ -472,12 +472,12 @@ async fn api_route( let symbol = Symbol::from(module); let Ok(address) = AccountAddress::from_hex_literal(&address) else { - let error = format!("Invalid hex address {address}"); - return ( - StatusCode::BAD_REQUEST, - headers, - Json(ErrorResponse { error }).into_response() - ) + let error = format!("Invalid hex address {address}"); + return ( + StatusCode::BAD_REQUEST, + headers, + Json(ErrorResponse { error }).into_response(), + ); }; let app_state = app_state.read().unwrap(); diff --git a/crates/sui-source-validation-service/tests/tests.rs b/crates/sui-source-validation-service/tests/tests.rs index 100ac8fec0347..c369430d71edd 100644 --- a/crates/sui-source-validation-service/tests/tests.rs +++ b/crates/sui-source-validation-service/tests/tests.rs @@ -200,8 +200,8 @@ async fn run_upgrade( .await?; let SuiClientCommandResult::Upgrade(response) = resp else { - unreachable!("Invalid upgrade response"); - }; + unreachable!("Invalid upgrade response"); + }; let SuiTransactionBlockEffects::V1(effects) = response.effects.unwrap(); assert!(effects.status.is_ok()); Ok(()) diff --git a/crates/sui-source-validation/src/lib.rs b/crates/sui-source-validation/src/lib.rs index 9b2b40a6a9cd6..0ec6d92758aaa 100644 --- a/crates/sui-source-validation/src/lib.rs +++ b/crates/sui-source-validation/src/lib.rs @@ -203,10 +203,8 @@ impl<'a> BytecodeSourceVerifier<'a> { let mut errors = Vec::new(); for ((address, module), (package, local_module)) in local_modules { let Some(on_chain_module) = on_chain_modules.remove(&(address, module)) else { - errors.push(SourceVerificationError::OnChainDependencyNotFound { - package, module, - }); - continue; + errors.push(SourceVerificationError::OnChainDependencyNotFound { package, module }); + continue; }; // compare local bytecode to on-chain bytecode to ensure integrity of our @@ -278,10 +276,12 @@ impl<'a> BytecodeSourceVerifier<'a> { let SuiRawMovePackage { module_map, .. } = pkg?; for (name, bytes) in module_map { let Ok(module) = CompiledModule::deserialize_with_defaults(&bytes) else { - err.push(SourceVerificationError::OnChainDependencyDeserializationError { - address: storage_id, - module: name.into(), - }); + err.push( + SourceVerificationError::OnChainDependencyDeserializationError { + address: storage_id, + module: name.into(), + }, + ); continue; }; diff --git a/crates/sui-source-validation/src/tests.rs b/crates/sui-source-validation/src/tests.rs index 94f481cd0609e..bde1209296a8e 100644 --- a/crates/sui-source-validation/src/tests.rs +++ b/crates/sui-source-validation/src/tests.rs @@ -328,11 +328,11 @@ async fn package_not_found() -> anyhow::Result<()> { let package_root = AccountAddress::random(); stable_addrs.insert(SuiAddress::from(package_root), ""); - let Err(err) = verifier.verify_package_root_and_deps( - &a_pkg, - package_root, - ).await else { - panic!("Expected verification to fail"); + let Err(err) = verifier + .verify_package_root_and_deps(&a_pkg, package_root) + .await + else { + panic!("Expected verification to fail"); }; // below may refer to either the package_root or dependent package `b` @@ -343,11 +343,8 @@ async fn package_not_found() -> anyhow::Result<()> { let package_root = AccountAddress::random(); stable_addrs.insert(SuiAddress::from(package_root), ""); - let Err(err) = verifier.verify_package_root( - &a_pkg, - package_root, - ).await else { - panic!("Expected verification to fail"); + let Err(err) = verifier.verify_package_root(&a_pkg, package_root).await else { + panic!("Expected verification to fail"); }; let expected = diff --git a/crates/sui-storage/src/indexes.rs b/crates/sui-storage/src/indexes.rs index bfcb7f018a054..10b98f8359b94 100644 --- a/crates/sui-storage/src/indexes.rs +++ b/crates/sui-storage/src/indexes.rs @@ -356,7 +356,7 @@ impl IndexStore { obj_id, input_coins, digest ) }); - let map = balance_changes.entry(*owner).or_insert(HashMap::new()); + let map = balance_changes.entry(*owner).or_default(); let entry = map.entry(coin_type_tag.clone()).or_insert(TotalBalance { num_coins: 0, balance: 0 @@ -398,7 +398,7 @@ impl IndexStore { obj_id, written_coins, digest ) }); - let map = balance_changes.entry(*owner).or_insert(HashMap::new()); + let map = balance_changes.entry(*owner).or_default(); let entry = map.entry(coin_type_tag.clone()).or_insert(TotalBalance { num_coins: 0, balance: 0 diff --git a/crates/sui-storage/src/sharded_lru.rs b/crates/sui-storage/src/sharded_lru.rs index a6decfcf24c45..cf74eb3dfaa3e 100644 --- a/crates/sui-storage/src/sharded_lru.rs +++ b/crates/sui-storage/src/sharded_lru.rs @@ -125,14 +125,14 @@ where pub async fn get_with(&self, key: K, init: impl Future) -> V { let shard = self.read_shard(&key).await; let value = shard.peek(&key); - if value.is_some() { - return value.unwrap().clone(); + if let Some(value) = value { + return value.clone(); } drop(shard); let mut shard = self.write_shard(&key).await; let value = shard.get(&key); - if value.is_some() { - return value.unwrap().clone(); + if let Some(value) = value { + return value.clone(); } let value = init.await; let cloned_value = value.clone(); diff --git a/crates/sui-storage/tests/key_value_tests.rs b/crates/sui-storage/tests/key_value_tests.rs index 7f845e5ce34df..39aa775590606 100644 --- a/crates/sui-storage/tests/key_value_tests.rs +++ b/crates/sui-storage/tests/key_value_tests.rs @@ -96,9 +96,10 @@ impl MockTxStore { } fn add_random_checkpoint(&mut self) -> (CertifiedCheckpointSummary, CheckpointContents) { - let contents = CheckpointContents::new_with_causally_ordered_transactions( - [ExecutionDigests::random()].into_iter(), - ); + let contents = + CheckpointContents::new_with_causally_ordered_transactions( + [ExecutionDigests::random()], + ); let next_seq = self.next_seq_number; self.next_seq_number += 1; diff --git a/crates/sui-surfer/src/default_surf_strategy.rs b/crates/sui-surfer/src/default_surf_strategy.rs index 302bdd335df6b..5672ab7868b59 100644 --- a/crates/sui-surfer/src/default_surf_strategy.rs +++ b/crates/sui-surfer/src/default_surf_strategy.rs @@ -37,7 +37,10 @@ impl SurfStrategy for DefaultSurfStrategy { entry_functions.shuffle(&mut state.rng); for entry in entry_functions { let Some(args) = Self::choose_function_call_args(state, entry.parameters).await else { - debug!("Failed to choose arguments for Move function {:?}::{:?}", entry.module, entry.function); + debug!( + "Failed to choose arguments for Move function {:?}::{:?}", + entry.module, entry.function + ); continue; }; state diff --git a/crates/sui-swarm-config/src/network_config_builder.rs b/crates/sui-swarm-config/src/network_config_builder.rs index 878805875c693..fadaedffc8fc8 100644 --- a/crates/sui-swarm-config/src/network_config_builder.rs +++ b/crates/sui-swarm-config/src/network_config_builder.rs @@ -228,7 +228,7 @@ impl ConfigBuilder { // See above re fixed protocol keys let (_, protocol_keys) = Committee::new_simple_test_committee_of_size(keys.len()); keys.into_iter() - .zip(protocol_keys.into_iter()) + .zip(protocol_keys) .map(|(account_key, protocol_key)| { let mut builder = ValidatorGenesisConfigBuilder::new() .with_protocol_key_pair(protocol_key) diff --git a/crates/sui-swarm-config/tests/snapshot_tests.rs b/crates/sui-swarm-config/tests/snapshot_tests.rs index a8b2d321d6378..350c5a5c5581c 100644 --- a/crates/sui-swarm-config/tests/snapshot_tests.rs +++ b/crates/sui-swarm-config/tests/snapshot_tests.rs @@ -118,7 +118,7 @@ fn network_config_snapshot_matches() { .rng(rng) .build(); // TODO: Inject static temp path and port numbers, instead of clearing them. - for mut validator_config in &mut network_config.validator_configs { + for validator_config in &mut network_config.validator_configs { validator_config.db_path = PathBuf::from("/tmp/foo/"); validator_config.network_address = Multiaddr::empty(); let fake_socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 1); diff --git a/crates/sui-tool/src/db_tool/mod.rs b/crates/sui-tool/src/db_tool/mod.rs index ca321103006fe..c51d75ef62ede 100644 --- a/crates/sui-tool/src/db_tool/mod.rs +++ b/crates/sui-tool/src/db_tool/mod.rs @@ -325,10 +325,16 @@ pub fn remove_transaction(path: &Path, opt: RemoveTransactionOptions) -> anyhow: }; let epoch_store = AuthorityEpochTables::open(epoch, &path.join("store"), None); let Some(_transaction) = perpetual_db.get_transaction(&opt.digest)? else { - bail!("Transaction {:?} not found and cannot be re-executed!", opt.digest); + bail!( + "Transaction {:?} not found and cannot be re-executed!", + opt.digest + ); }; let Some(effects) = perpetual_db.get_effects(&opt.digest)? else { - bail!("Transaction {:?} not executed or effects have been pruned!", opt.digest); + bail!( + "Transaction {:?} not executed or effects have been pruned!", + opt.digest + ); }; let mut objects_to_remove = vec![]; for mutated_obj in effects.modified_at_versions() { @@ -460,7 +466,9 @@ pub fn rewind_checkpoint_execution( None, None, ); - let Some(checkpoint) = checkpoint_db.get_checkpoint_by_sequence_number(checkpoint_sequence_number)? else { + let Some(checkpoint) = + checkpoint_db.get_checkpoint_by_sequence_number(checkpoint_sequence_number)? + else { bail!("Checkpoint {checkpoint_sequence_number} not found!"); }; if epoch != checkpoint.epoch() { @@ -490,7 +498,7 @@ pub fn print_db_table_summary( table_name: &str, ) -> anyhow::Result<()> { let summary = table_summary(store, epoch, path, table_name)?; - let quantiles = vec![25, 50, 75, 90, 99]; + let quantiles = [25, 50, 75, 90, 99]; println!( "Total num keys = {}, total key bytes = {}, total value bytes = {}", summary.num_keys, summary.key_bytes_total, summary.value_bytes_total diff --git a/crates/sui-transaction-builder/src/lib.rs b/crates/sui-transaction-builder/src/lib.rs index 4f73b88ae20d0..7b0489528590d 100644 --- a/crates/sui-transaction-builder/src/lib.rs +++ b/crates/sui-transaction-builder/src/lib.rs @@ -364,7 +364,10 @@ impl TransactionBuilder { .await? .into_object()?; let Some(SuiRawData::Package(package)) = object.bcs else { - bail!("Bcs field in object [{}] is missing or not a package.", package_id); + bail!( + "Bcs field in object [{}] is missing or not a package.", + package_id + ); }; let package: MovePackage = MovePackage::new( package.id, @@ -672,8 +675,8 @@ impl TransactionBuilder { .ok_or_else(|| anyhow!("Coins input should contain at lease one coin object."))?; let (oref, coin_type) = self.get_object_ref_and_type(coin).await?; - let ObjectType::Struct(type_) = &coin_type else{ - return Err(anyhow!("Provided object [{coin}] is not a move object.")) + let ObjectType::Struct(type_) = &coin_type else { + return Err(anyhow!("Provided object [{coin}] is not a move object.")); }; ensure!( type_.is_coin(), diff --git a/crates/sui-transaction-checks/src/lib.rs b/crates/sui-transaction-checks/src/lib.rs index c0319b46c1485..dcd52448c32dc 100644 --- a/crates/sui-transaction-checks/src/lib.rs +++ b/crates/sui-transaction-checks/src/lib.rs @@ -563,8 +563,8 @@ mod checked { } let TransactionKind::ProgrammableTransaction(pt) = transaction.kind() else { - return Ok(()); - }; + return Ok(()); + }; // We use a custom config with metering enabled let is_metered = true; diff --git a/crates/sui-transactional-test-runner/src/test_adapter.rs b/crates/sui-transactional-test-runner/src/test_adapter.rs index 8e9512a2edd29..84c4ed0c4bc11 100644 --- a/crates/sui-transactional-test-runner/src/test_adapter.rs +++ b/crates/sui-transactional-test-runner/src/test_adapter.rs @@ -763,8 +763,7 @@ impl<'a> MoveTestAdapter<'a> for SuiTestAdapter<'a> { let before_upgrade = { // not binding `m` separately results in some strange async capture error let m = &mut self.compiled_state.named_address_mapping; - let Some(before) = m.insert(package.clone(), zero) - else { + let Some(before) = m.insert(package.clone(), zero) else { panic!("Unbound package '{package}' for upgrade"); }; before @@ -779,8 +778,14 @@ impl<'a> MoveTestAdapter<'a> for SuiTestAdapter<'a> { for dep in dependencies.iter() { let named_address_mapping = &mut self.compiled_state.named_address_mapping; let dep = &Symbol::from(dep.as_str()); - let Some(orig_package) = self.package_upgrade_mapping.get(dep) else { continue }; - let Some(orig_package_address) = named_address_mapping.insert(orig_package.to_string(), zero) else { continue }; + let Some(orig_package) = self.package_upgrade_mapping.get(dep) else { + continue; + }; + let Some(orig_package_address) = + named_address_mapping.insert(orig_package.to_string(), zero) + else { + continue; + }; original_package_addrs.push((*orig_package, orig_package_address)); let dep_address = named_address_mapping .insert(dep.to_string(), orig_package_address) @@ -1492,8 +1497,8 @@ impl<'a> SuiTestAdapter<'a> { .into_iter() .map(|d| { let Some(addr) = self.compiled_state.named_address_mapping.get(&d) else { - bail!("There is no published module address corresponding to name address {d}"); - }; + bail!("There is no published module address corresponding to name address {d}"); + }; let id: ObjectID = addr.into_inner().into(); Ok(id) }) diff --git a/crates/sui-types/src/authenticator_state.rs b/crates/sui-types/src/authenticator_state.rs index edc6b16d6b81c..de7f1d9ae68f7 100644 --- a/crates/sui-types/src/authenticator_state.rs +++ b/crates/sui-types/src/authenticator_state.rs @@ -90,6 +90,7 @@ fn jwk_ord(a: &ActiveJwk, b: &ActiveJwk) -> std::cmp::Ordering { } } +#[allow(clippy::incorrect_partial_ord_impl_on_ord_type)] impl std::cmp::PartialOrd for ActiveJwk { // This must match the sort order defined by jwk_lt in authenticator_state.move fn partial_cmp(&self, other: &Self) -> Option { diff --git a/crates/sui-types/src/coin.rs b/crates/sui-types/src/coin.rs index c02800eeaabe7..04109b46883a9 100644 --- a/crates/sui-types/src/coin.rs +++ b/crates/sui-types/src/coin.rs @@ -111,8 +111,7 @@ impl Coin { /// Add balance to this coin, erroring if the new total balance exceeds the maximum pub fn add(&mut self, balance: Balance) -> Result<(), ExecutionError> { - let Some(new_value) = self.value().checked_add(balance.value()) - else { + let Some(new_value) = self.value().checked_add(balance.value()) else { return Err(ExecutionError::from_kind( ExecutionErrorKind::CoinBalanceOverflow, )); diff --git a/crates/sui-types/src/execution.rs b/crates/sui-types/src/execution.rs index 808226021afe2..00868c0c423bc 100644 --- a/crates/sui-types/src/execution.rs +++ b/crates/sui-types/src/execution.rs @@ -123,7 +123,7 @@ impl ExecutionResultsV2 { lamport_version: SequenceNumber, prev_tx: TransactionDigest, ) { - for (id, mut obj) in self.written_objects.iter_mut() { + for (id, obj) in self.written_objects.iter_mut() { // TODO: We can now get rid of the following logic by passing in lamport version // into the execution layer, and create new objects using the lamport version directly. diff --git a/crates/sui-types/src/messages_checkpoint.rs b/crates/sui-types/src/messages_checkpoint.rs index 0b88298a7eb78..f6b6cabd63a38 100644 --- a/crates/sui-types/src/messages_checkpoint.rs +++ b/crates/sui-types/src/messages_checkpoint.rs @@ -404,7 +404,7 @@ impl CheckpointContents { .. } = self.into_v1(); - transactions.into_iter().zip(user_signatures.into_iter()) + transactions.into_iter().zip(user_signatures) } /// Return an iterator that enumerates the transactions in the contents. @@ -568,7 +568,7 @@ impl FullCheckpointContents { transaction, effects, }; - FullCheckpointContents::new_with_causally_ordered_transactions(vec![exe_data].into_iter()) + FullCheckpointContents::new_with_causally_ordered_transactions(vec![exe_data]) } } @@ -652,9 +652,10 @@ mod tests { let (keys, committee) = make_committee_key(&mut rng); let (_, committee2) = make_committee_key(&mut rng); - let set = CheckpointContents::new_with_causally_ordered_transactions( - [ExecutionDigests::random()].into_iter(), - ); + let set = + CheckpointContents::new_with_causally_ordered_transactions( + [ExecutionDigests::random()], + ); // TODO: duplicated in a test below. @@ -697,9 +698,10 @@ mod tests { let mut rng = StdRng::from_seed(RNG_SEED); let (keys, committee) = make_committee_key(&mut rng); - let set = CheckpointContents::new_with_causally_ordered_transactions( - [ExecutionDigests::random()].into_iter(), - ); + let set = + CheckpointContents::new_with_causally_ordered_transactions( + [ExecutionDigests::random()], + ); let summary = CheckpointSummary::new( committee.epoch, @@ -734,9 +736,9 @@ mod tests { .iter() .map(|k| { let name = k.public().into(); - let set = CheckpointContents::new_with_causally_ordered_transactions( - [ExecutionDigests::random()].into_iter(), - ); + let set = CheckpointContents::new_with_causally_ordered_transactions([ + ExecutionDigests::random(), + ]); SignedCheckpointSummary::new( committee.epoch, diff --git a/crates/sui-types/src/multisig.rs b/crates/sui-types/src/multisig.rs index a5b411343d059..4c3819777c545 100644 --- a/crates/sui-types/src/multisig.rs +++ b/crates/sui-types/src/multisig.rs @@ -366,7 +366,7 @@ impl MultiSigPublicKey { }); } Ok(MultiSigPublicKey { - pk_map: pks.into_iter().zip(weights.into_iter()).collect(), + pk_map: pks.into_iter().zip(weights).collect(), threshold, }) } diff --git a/crates/sui-types/src/multisig_legacy.rs b/crates/sui-types/src/multisig_legacy.rs index 32e2f21bf872c..6cbc14040c4e3 100644 --- a/crates/sui-types/src/multisig_legacy.rs +++ b/crates/sui-types/src/multisig_legacy.rs @@ -311,7 +311,7 @@ impl MultiSigPublicKeyLegacy { }); } Ok(MultiSigPublicKeyLegacy { - pk_map: pks.into_iter().zip(weights.into_iter()).collect(), + pk_map: pks.into_iter().zip(weights).collect(), threshold, }) } diff --git a/crates/sui-types/src/programmable_transaction_builder.rs b/crates/sui-types/src/programmable_transaction_builder.rs index b24b5c03a5566..b5d4d2924912c 100644 --- a/crates/sui-types/src/programmable_transaction_builder.rs +++ b/crates/sui-types/src/programmable_transaction_builder.rs @@ -269,8 +269,7 @@ impl ProgrammableTransactionBuilder { amounts: Vec, ) -> anyhow::Result<()> { let mut coins = coins.into_iter(); - let Some(coin) = coins.next() - else { + let Some(coin) = coins.next() else { anyhow::bail!("coins vector is empty"); }; let coin_arg = self.obj(ObjectArg::ImmOrOwnedObject(coin))?; diff --git a/crates/sui-types/src/unit_tests/utils.rs b/crates/sui-types/src/unit_tests/utils.rs index 26966e210b4db..830d192f96afd 100644 --- a/crates/sui-types/src/unit_tests/utils.rs +++ b/crates/sui-types/src/unit_tests/utils.rs @@ -127,9 +127,8 @@ pub fn mock_certified_checkpoint<'a>( committee: Committee, seq_num: u64, ) -> CertifiedCheckpointSummary { - let contents = CheckpointContents::new_with_causally_ordered_transactions( - [ExecutionDigests::random()].into_iter(), - ); + let contents = + CheckpointContents::new_with_causally_ordered_transactions([ExecutionDigests::random()]); let summary = CheckpointSummary::new( committee.epoch, diff --git a/crates/sui-types/tests/serde_tests.rs b/crates/sui-types/tests/serde_tests.rs index e232f69ead280..cd7056857b06b 100644 --- a/crates/sui-types/tests/serde_tests.rs +++ b/crates/sui-types/tests/serde_tests.rs @@ -18,8 +18,9 @@ fn test_struct_tag_serde() { struct TestStructTag(#[serde_as(as = "SuiStructTag")] StructTag); // serialize to json should not trim the leading 0 - let Value::String(json) = serde_json::to_value(&TestStructTag(tag.clone())) - .unwrap() else { panic!() }; + let Value::String(json) = serde_json::to_value(&TestStructTag(tag.clone())).unwrap() else { + panic!() + }; assert_eq!(json, "0x07f89cdffd8968affa0b47bef91adc5314e19509080470c45bfd434cd83a766b::suifrens::SuiFren<0x07f89cdffd8968affa0b47bef91adc5314e19509080470c45bfd434cd83a766b::capy::Capy>"); let tag2 = parse_sui_struct_tag(&json).unwrap(); diff --git a/crates/sui-upgrade-compatibility-transactional-tests/tests/tests.rs b/crates/sui-upgrade-compatibility-transactional-tests/tests/tests.rs index 5a70adba7e1b6..70028ae00f238 100644 --- a/crates/sui-upgrade-compatibility-transactional-tests/tests/tests.rs +++ b/crates/sui-upgrade-compatibility-transactional-tests/tests/tests.rs @@ -54,8 +54,7 @@ fn check_all_compatibilities( ) -> datatest_stable::Result<()> { assert_eq!(base.len(), upgraded.len()); - let compatibility_types = vec![ - // Full compat + let compatibility_types = [ Compatibility::full_check(), // Full compat but allow private entry functions to change Compatibility { diff --git a/crates/sui/src/unit_tests/validator_tests.rs b/crates/sui/src/unit_tests/validator_tests.rs index 0ca14c3254c55..f054f5a78a926 100644 --- a/crates/sui/src/unit_tests/validator_tests.rs +++ b/crates/sui/src/unit_tests/validator_tests.rs @@ -40,7 +40,11 @@ async fn test_print_raw_rgp_txn() -> Result<(), anyhow::Error> { } .execute(&mut context) .await?; - let SuiValidatorCommandResponse::DisplayGasPriceUpdateRawTxn { data, serialized_data } = response else { + let SuiValidatorCommandResponse::DisplayGasPriceUpdateRawTxn { + data, + serialized_data, + } = response + else { panic!("Expected DisplayGasPriceUpdateRawTxn"); }; diff --git a/crates/sui/src/zklogin_commands_util.rs b/crates/sui/src/zklogin_commands_util.rs index c5ec22f727882..ab34d20fc529e 100644 --- a/crates/sui/src/zklogin_commands_util.rs +++ b/crates/sui/src/zklogin_commands_util.rs @@ -105,9 +105,9 @@ pub async fn perform_zk_login_test_tx( .get_coins(zklogin_address, None, None, None) .await? .next_cursor - else { - panic!("Faucet did not work correctly and the provided Sui address has no coins") - }; + else { + panic!("Faucet did not work correctly and the provided Sui address has no coins") + }; let txb_res = sui .transaction_builder() .transfer_object( diff --git a/crates/typed-store/src/rocks/mod.rs b/crates/typed-store/src/rocks/mod.rs index 2b835456f56ca..a060580026a93 100644 --- a/crates/typed-store/src/rocks/mod.rs +++ b/crates/typed-store/src/rocks/mod.rs @@ -790,8 +790,8 @@ impl DBMap { } pub fn compact_range(&self, start: &J, end: &J) -> Result<(), TypedStoreError> { - let from_buf = be_fix_int_ser(start.borrow())?; - let to_buf = be_fix_int_ser(end.borrow())?; + let from_buf = be_fix_int_ser(start)?; + let to_buf = be_fix_int_ser(end)?; self.rocksdb .compact_range_cf(&self.cf(), Some(from_buf), Some(to_buf)); Ok(()) @@ -816,8 +816,8 @@ impl DBMap { start: &J, end: &J, ) -> Result<(), TypedStoreError> { - let from_buf = be_fix_int_ser(start.borrow())?; - let to_buf = be_fix_int_ser(end.borrow())?; + let from_buf = be_fix_int_ser(start)?; + let to_buf = be_fix_int_ser(end)?; self.rocksdb .compact_range_to_bottom(&self.cf(), Some(from_buf), Some(to_buf)); Ok(()) @@ -872,7 +872,7 @@ impl DBMap { .with_label_values(&[&self.cf]) .start_timer(); let perf_ctx = if self.multiget_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1190,7 +1190,7 @@ impl DBBatch { let batch_size = self.batch.size_in_bytes(); let perf_ctx = if self.write_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1394,7 +1394,7 @@ impl<'a> DBTransaction<'a> { if !Arc::ptr_eq(&db.rocksdb, &self.rocksdb) { return Err(TypedStoreError::CrossDBBatch); } - let k_buf = be_fix_int_ser(key.borrow())?; + let k_buf = be_fix_int_ser(key)?; match self .transaction .get_for_update_cf_opt(&db.cf(), k_buf, true, &db.opts.readopts())? @@ -1618,7 +1618,7 @@ where .with_label_values(&[&self.cf]) .start_timer(); let perf_ctx = if self.get_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1651,7 +1651,7 @@ where .with_label_values(&[&self.cf]) .start_timer(); let perf_ctx = if self.get_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1684,7 +1684,7 @@ where .with_label_values(&[&self.cf]) .start_timer(); let perf_ctx = if self.write_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1714,7 +1714,7 @@ where .with_label_values(&[&self.cf]) .start_timer(); let perf_ctx = if self.write_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1791,7 +1791,7 @@ where .rocksdb_iter_keys .with_label_values(&[&self.cf]); let _perf_ctx = if self.iter_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1817,7 +1817,7 @@ where .with_label_values(&[&self.cf]) .start_timer(); let _perf_ctx = if self.iter_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1871,7 +1871,7 @@ where .rocksdb_iter_keys .with_label_values(&[&self.cf]); let _perf_ctx = if self.iter_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; @@ -1917,7 +1917,7 @@ where .rocksdb_iter_keys .with_label_values(&[&self.cf]); let _perf_ctx = if self.iter_sample_interval.sample() { - Some(RocksDBPerfContext::default()) + Some(RocksDBPerfContext) } else { None }; diff --git a/crates/typed-store/src/test_db.rs b/crates/typed-store/src/test_db.rs index dca8c1401e00f..b6258c365f32e 100644 --- a/crates/typed-store/src/test_db.rs +++ b/crates/typed-store/src/test_db.rs @@ -471,8 +471,8 @@ impl TestDBWriteBatch { from: &K, to: &K, ) -> Result<(), TypedStoreError> { - let raw_from = be_fix_int_ser(from.borrow()).unwrap(); - let raw_to = be_fix_int_ser(to.borrow()).unwrap(); + let raw_from = be_fix_int_ser(from).unwrap(); + let raw_to = be_fix_int_ser(to).unwrap(); self.ops.push_back(WriteBatchOp::DeleteRange(( db.rows.clone(), db.name.clone(), diff --git a/docker/sui-graphql-rpc/Dockerfile b/docker/sui-graphql-rpc/Dockerfile index 366dbdcb322a2..cd03e5fed4051 100644 --- a/docker/sui-graphql-rpc/Dockerfile +++ b/docker/sui-graphql-rpc/Dockerfile @@ -2,13 +2,13 @@ # # Copy in all crates, Cargo.toml and Cargo.lock unmodified, # and build the application. -FROM rust:1.73.0 AS builder +FROM rust:1.73-bullseye AS builder ARG PROFILE=release ENV PROFILE=$PROFILE ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION WORKDIR "$WORKDIR/sui" -RUN apt-get update && apt-get install -y cmake clang +RUN apt-get update && apt-get install -y cmake clang libpq-dev COPY Cargo.toml Cargo.lock ./ COPY crates crates @@ -24,7 +24,7 @@ WORKDIR "$WORKDIR/sui" # Both bench and release profiles copy from release dir RUN mkdir -p /opt/sui/bin COPY --from=builder /sui/target/release/sui-graphql-rpc /opt/sui/bin -RUN apt-get update && apt-get install -y libpq5 ca-certificates +RUN apt-get update && apt-get install -y libpq5 ca-certificates libpq-dev postgresql ARG BUILD_DATE ARG GIT_REVISION diff --git a/docker/sui-indexer/Dockerfile b/docker/sui-indexer/Dockerfile index efb24a02671ff..1fd7f44c603e2 100644 --- a/docker/sui-indexer/Dockerfile +++ b/docker/sui-indexer/Dockerfile @@ -2,11 +2,15 @@ # # Copy in all crates, Cargo.toml and Cargo.lock unmodified, # and build the application. -FROM rust:1.70.0 AS builder +FROM rust:1.73-bullseye AS builder ARG PROFILE=release ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION WORKDIR "$WORKDIR/sui" + +# sui-indexer needs postgres libpq5 and ca-certificates +RUN apt update && apt install -y libpq5 ca-certificates libpq-dev postgresql + RUN apt-get update && apt-get install -y cmake clang COPY Cargo.toml Cargo.lock ./ @@ -21,8 +25,7 @@ RUN cargo build --profile ${PROFILE} --bin sui-indexer FROM debian:bullseye-slim AS runtime WORKDIR "$WORKDIR/sui" COPY --from=builder /sui/target/release/sui-indexer /usr/local/bin -# sui-indexer needs postgres libpq5 and ca-certificates -RUN apt update && apt install -y libpq5 ca-certificates +RUN apt update && apt install -y libpq5 ca-certificates libpq-dev postgresql ARG BUILD_DATE ARG GIT_REVISION diff --git a/docker/sui-node/Dockerfile b/docker/sui-node/Dockerfile index 7c196ae6cbfb0..774a776ba68cb 100644 --- a/docker/sui-node/Dockerfile +++ b/docker/sui-node/Dockerfile @@ -2,7 +2,7 @@ # # Copy in all crates, Cargo.toml and Cargo.lock unmodified, # and build the application. -FROM rust:1.70.0 AS builder +FROM rust:1.73-bullseye AS builder ARG PROFILE=release ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION diff --git a/docker/sui-services/Dockerfile b/docker/sui-services/Dockerfile index 95d5814c1559d..7c54b61e4600c 100644 --- a/docker/sui-services/Dockerfile +++ b/docker/sui-services/Dockerfile @@ -1,4 +1,4 @@ -FROM rust:1.70.0 AS chef +FROM rust:1.73-bullseye AS chef WORKDIR sui ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION diff --git a/docker/sui-source-service/Dockerfile b/docker/sui-source-service/Dockerfile index 1882843ba9ec8..2d0b6edcfa5fa 100644 --- a/docker/sui-source-service/Dockerfile +++ b/docker/sui-source-service/Dockerfile @@ -1,4 +1,4 @@ -FROM rust:1.70.0 AS chef +FROM rust:1.73-bullseye AS chef WORKDIR sui ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION diff --git a/docker/sui-tools/Dockerfile b/docker/sui-tools/Dockerfile index 386f9a441d2ab..d1eb15b4a9bc9 100644 --- a/docker/sui-tools/Dockerfile +++ b/docker/sui-tools/Dockerfile @@ -2,12 +2,12 @@ # # Copy in all crates, Cargo.toml and Cargo.lock unmodified, # and build the application. -FROM rust:1.70.0 AS builder +FROM rust:1.73-bullseye AS builder ARG PROFILE=release ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION WORKDIR "$WORKDIR/sui" -RUN apt-get update && apt-get install -y cmake clang +RUN apt-get update && apt-get install -y cmake clang libpq5 libpq-dev COPY Cargo.toml Cargo.lock ./ COPY crates crates diff --git a/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds.rs b/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds.rs index b4d31c2011668..67f337e4c7e86 100644 --- a/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds.rs +++ b/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds.rs @@ -192,7 +192,7 @@ impl ApplyOutOfBoundsContext { { mutation_map .entry((mutation.src_kind, mutation.dst_kind)) - .or_insert_with(Vec::new) + .or_default() .push(mutation); } diff --git a/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs b/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs index 18085317dc2ba..f086a1ecedd81 100644 --- a/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs +++ b/external-crates/move-execution/v0/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs @@ -156,10 +156,7 @@ impl<'a> ApplyCodeUnitBoundsContext<'a> { .expect("mutations should always be present") { let picked_idx = mutation.function_def.index(function_def_len); - mutation_map - .entry(picked_idx) - .or_insert_with(Vec::new) - .push(mutation); + mutation_map.entry(picked_idx).or_default().push(mutation); } let mut results = vec![]; diff --git a/external-crates/move-execution/v0/move-bytecode-verifier/src/struct_defs.rs b/external-crates/move-execution/v0/move-bytecode-verifier/src/struct_defs.rs index 00c9746863c72..3ec9dedbde6e8 100644 --- a/external-crates/move-execution/v0/move-bytecode-verifier/src/struct_defs.rs +++ b/external-crates/move-execution/v0/move-bytecode-verifier/src/struct_defs.rs @@ -126,7 +126,7 @@ impl<'a> StructDefGraphBuilder<'a> { if let Some(struct_def_idx) = self.handle_to_def.get(sh_idx) { neighbors .entry(cur_idx) - .or_insert_with(BTreeSet::new) + .or_default() .insert(*struct_def_idx); } } @@ -134,7 +134,7 @@ impl<'a> StructDefGraphBuilder<'a> { if let Some(struct_def_idx) = self.handle_to_def.get(sh_idx) { neighbors .entry(cur_idx) - .or_insert_with(BTreeSet::new) + .or_default() .insert(*struct_def_idx); } for t in inners { diff --git a/external-crates/move-execution/v0/move-vm/runtime/src/interpreter.rs b/external-crates/move-execution/v0/move-vm/runtime/src/interpreter.rs index 46676ec0b6aff..48d3f08394886 100644 --- a/external-crates/move-execution/v0/move-vm/runtime/src/interpreter.rs +++ b/external-crates/move-execution/v0/move-vm/runtime/src/interpreter.rs @@ -2431,7 +2431,8 @@ impl Frame { .loader() .vm_config() .runtime_limits_config - .max_value_nest_depth else { + .max_value_nest_depth + else { return Ok(1); }; Self::check_depth_of_type_impl(resolver, ty, 0, max_depth) diff --git a/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds.rs b/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds.rs index b4d31c2011668..67f337e4c7e86 100644 --- a/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds.rs +++ b/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds.rs @@ -192,7 +192,7 @@ impl ApplyOutOfBoundsContext { { mutation_map .entry((mutation.src_kind, mutation.dst_kind)) - .or_insert_with(Vec::new) + .or_default() .push(mutation); } diff --git a/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs b/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs index 18085317dc2ba..f086a1ecedd81 100644 --- a/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs +++ b/external-crates/move-execution/vm-rework/move-bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs @@ -156,10 +156,7 @@ impl<'a> ApplyCodeUnitBoundsContext<'a> { .expect("mutations should always be present") { let picked_idx = mutation.function_def.index(function_def_len); - mutation_map - .entry(picked_idx) - .or_insert_with(Vec::new) - .push(mutation); + mutation_map.entry(picked_idx).or_default().push(mutation); } let mut results = vec![]; diff --git a/external-crates/move-execution/vm-rework/move-bytecode-verifier/src/struct_defs.rs b/external-crates/move-execution/vm-rework/move-bytecode-verifier/src/struct_defs.rs index 258ae693b9ae7..711837245fd26 100644 --- a/external-crates/move-execution/vm-rework/move-bytecode-verifier/src/struct_defs.rs +++ b/external-crates/move-execution/vm-rework/move-bytecode-verifier/src/struct_defs.rs @@ -126,7 +126,7 @@ impl<'a> StructDefGraphBuilder<'a> { if let Some(struct_def_idx) = self.handle_to_def.get(sh_idx) { neighbors .entry(cur_idx) - .or_insert_with(BTreeSet::new) + .or_default() .insert(*struct_def_idx); } } @@ -134,7 +134,7 @@ impl<'a> StructDefGraphBuilder<'a> { if let Some(struct_def_idx) = self.handle_to_def.get(sh_idx) { neighbors .entry(cur_idx) - .or_insert_with(BTreeSet::new) + .or_default() .insert(*struct_def_idx); } for t in inners { diff --git a/external-crates/move-execution/vm-rework/move-vm/runtime/src/interpreter.rs b/external-crates/move-execution/vm-rework/move-vm/runtime/src/interpreter.rs index 063c75557974f..53928a7b7fd54 100644 --- a/external-crates/move-execution/vm-rework/move-vm/runtime/src/interpreter.rs +++ b/external-crates/move-execution/vm-rework/move-vm/runtime/src/interpreter.rs @@ -1876,7 +1876,8 @@ impl Frame { .loader() .vm_config() .runtime_limits_config - .max_value_nest_depth else { + .max_value_nest_depth + else { return Ok(1); }; Self::check_depth_of_type_impl(resolver, ty, 0, max_depth) diff --git a/external-crates/move/move-compiler/src/cfgir/translate.rs b/external-crates/move/move-compiler/src/cfgir/translate.rs index 05924855f718c..80ff4c9898f2c 100644 --- a/external-crates/move/move-compiler/src/cfgir/translate.rs +++ b/external-crates/move/move-compiler/src/cfgir/translate.rs @@ -754,8 +754,14 @@ fn visit_function( acquires, body, } = fdef; - let G::FunctionBody_::Defined { locals, start, blocks, block_info } = &body.value else { - return + let G::FunctionBody_::Defined { + locals, + start, + blocks, + block_info, + } = &body.value + else { + return; }; context.env.add_warning_filter_scope(warning_filter.clone()); let (cfg, infinite_loop_starts) = ImmForwardCFG::new(*start, blocks, block_info.iter()); diff --git a/external-crates/move/move-compiler/src/expansion/primitive_definers.rs b/external-crates/move/move-compiler/src/expansion/primitive_definers.rs index 2378817b390d5..d5eed3097fba4 100644 --- a/external-crates/move/move-compiler/src/expansion/primitive_definers.rs +++ b/external-crates/move/move-compiler/src/expansion/primitive_definers.rs @@ -60,14 +60,16 @@ fn check_prim_definer( .get_(&AttributeName_::Known(KnownAttribute::DefinesPrimitive( DefinesPrimitive, ))); - let Some(sp!(attr_loc, attr_)) = defines_prim_attr else { return }; - let Attribute_::Parameterized(_, params) = attr_ else { + let Some(sp!(attr_loc, attr_)) = defines_prim_attr else { + return; + }; + let Attribute_::Parameterized(_, params) = attr_ else { let msg = format!( "Expected a primitive type parameterization, e.g. '{}()'", DefinesPrimitive::DEFINES_PRIM ); env.add_diag(diag!(Attributes::InvalidUsage, (*attr_loc, msg))); - return + return; }; if params.len() != 1 { let msg = format!( @@ -84,7 +86,7 @@ fn check_prim_definer( DefinesPrimitive::DEFINES_PRIM ); env.add_diag(diag!(Attributes::InvalidUsage, (*param_loc, msg))); - return + return; }; let Some(prim) = BuiltinTypeName_::resolve(name.value.as_str()) else { let msg = format!( @@ -93,7 +95,7 @@ fn check_prim_definer( name, ); env.add_diag(diag!(Attributes::InvalidUsage, (name.loc, msg))); - return + return; }; if let Some(prev) = definers.get(&prim) { diff --git a/external-crates/move/move-compiler/src/expansion/translate.rs b/external-crates/move/move-compiler/src/expansion/translate.rs index 61cafd0fdc7c6..db8e633ab4519 100644 --- a/external-crates/move/move-compiler/src/expansion/translate.rs +++ b/external-crates/move/move-compiler/src/expansion/translate.rs @@ -504,7 +504,6 @@ fn module_( .add_diag(diag!(Declarations::InvalidName, (name.loc(), msg))); } - let name = name; let name_loc = name.0.loc; let current_module = sp(name_loc, ModuleIdent_::new(*context.cur_address(), name)); diff --git a/external-crates/move/move-compiler/src/hlir/translate.rs b/external-crates/move/move-compiler/src/hlir/translate.rs index d0ba7d4384cb5..a77c8fc7e5fff 100644 --- a/external-crates/move/move-compiler/src/hlir/translate.rs +++ b/external-crates/move/move-compiler/src/hlir/translate.rs @@ -1510,7 +1510,7 @@ fn struct_name(sp!(_, t): &H::Type) -> Option { H::SingleType_::Base(bt) => bt, H::SingleType_::Ref(_, bt) => bt, }; - let H::BaseType_::Apply(_, tname ,_ ) = &bt.value else { + let H::BaseType_::Apply(_, tname, _) = &bt.value else { return None; }; if let H::TypeName_::ModuleType(_, struct_name) = tname.value { diff --git a/external-crates/move/move-compiler/src/naming/resolve_use_funs.rs b/external-crates/move/move-compiler/src/naming/resolve_use_funs.rs index 82a0f15387a69..cbf8dbecb9ac8 100644 --- a/external-crates/move/move-compiler/src/naming/resolve_use_funs.rs +++ b/external-crates/move/move-compiler/src/naming/resolve_use_funs.rs @@ -195,13 +195,12 @@ fn use_funs(context: &mut Context, uf: &mut N::UseFuns) { function: (target_m, target_f), kind: ekind, } = implicit; - let Some((target_f,tn)) = is_valid_method(context, &target_m, target_f) else { + let Some((target_f, tn)) = is_valid_method(context, &target_m, target_f) else { if matches!(ekind, E::ImplicitUseFunKind::UseAlias { used: false }) { let msg = format!("Unused 'use' of alias '{}'. Consider removing it", method); - context.env.add_diag(diag!( - UnusedItem::Alias, - (method.loc, msg), - )) + context + .env + .add_diag(diag!(UnusedItem::Alias, (method.loc, msg),)) } continue; }; diff --git a/external-crates/move/move-compiler/src/naming/translate.rs b/external-crates/move/move-compiler/src/naming/translate.rs index 12389e30111dc..035cbbe3304ce 100644 --- a/external-crates/move/move-compiler/src/naming/translate.rs +++ b/external-crates/move/move-compiler/src/naming/translate.rs @@ -274,8 +274,7 @@ impl<'env> Context<'env> { match ma_ { EN::Name(n) => self.resolve_unscoped_type(nloc, n), EN::ModuleAccess(m, n) => { - let Some(module_type) = self.resolve_module_type(nloc, &m, &n) - else { + let Some(module_type) = self.resolve_module_type(nloc, &m, &n) else { assert!(self.env.has_errors()); return ResolvedType::Unbound; }; diff --git a/external-crates/move/move-compiler/src/parser/merge_spec_modules.rs b/external-crates/move/move-compiler/src/parser/merge_spec_modules.rs index abdb0e283b135..7aced3103dbfe 100644 --- a/external-crates/move/move-compiler/src/parser/merge_spec_modules.rs +++ b/external-crates/move/move-compiler/src/parser/merge_spec_modules.rs @@ -154,8 +154,8 @@ fn merge_spec_module( is_spec_module, } = spec_module; assert!(is_spec_module); - m.attributes.extend(attributes.into_iter()); - m.members.extend(members.into_iter()); + m.attributes.extend(attributes); + m.members.extend(members); } } diff --git a/external-crates/move/move-compiler/src/parser/syntax.rs b/external-crates/move/move-compiler/src/parser/syntax.rs index 0c63ec18616a3..47e63e21afa41 100644 --- a/external-crates/move/move-compiler/src/parser/syntax.rs +++ b/external-crates/move/move-compiler/src/parser/syntax.rs @@ -286,6 +286,7 @@ where // Parse an identifier: // Identifier = +#[allow(clippy::needless_if)] fn parse_identifier(context: &mut Context) -> Result> { if matches!( context.tokens.peek(), diff --git a/external-crates/move/move-compiler/src/sui_mode/id_leak.rs b/external-crates/move/move-compiler/src/sui_mode/id_leak.rs index 2b6db266f61a6..fa4947fc736a4 100644 --- a/external-crates/move/move-compiler/src/sui_mode/id_leak.rs +++ b/external-crates/move/move-compiler/src/sui_mode/id_leak.rs @@ -89,7 +89,7 @@ impl SimpleAbsIntConstructor for IDLeakVerifier { _init_state: &mut as SimpleAbsInt>::State, ) -> Option> { let Some(module) = &context.module else { - return None + return None; }; let package_name = program.modules.get(module).unwrap().package_name; let config = env.package_config(package_name); diff --git a/external-crates/move/move-compiler/src/sui_mode/typing.rs b/external-crates/move/move-compiler/src/sui_mode/typing.rs index d9e032a2e3c5a..c5d9b49a479ef 100644 --- a/external-crates/move/move-compiler/src/sui_mode/typing.rs +++ b/external-crates/move/move-compiler/src/sui_mode/typing.rs @@ -208,7 +208,9 @@ fn struct_def(context: &mut Context, name: StructName, sdef: &N::StructDefinitio return; }; - let StructFields::Defined(fields) = fields else { return }; + let StructFields::Defined(fields) = fields else { + return; + }; let invalid_first_field = if fields.is_empty() { // no fields Some(name.loc()) @@ -586,10 +588,10 @@ fn entry_signature( fn tx_context_kind(sp!(_, last_param_ty_): &Type) -> TxContextKind { let Type_::Ref(is_mut, inner_ty) = last_param_ty_ else { - return TxContextKind::None + return TxContextKind::None; }; let Type_::Apply(_, sp!(_, inner_name), _) = &inner_ty.value else { - return TxContextKind::None + return TxContextKind::None; }; if inner_name.is(SUI_ADDR_NAME, TX_CONTEXT_MODULE_NAME, TX_CONTEXT_TYPE_NAME) { if *is_mut { diff --git a/external-crates/move/move-core/types/src/gas_algebra.rs b/external-crates/move/move-core/types/src/gas_algebra.rs index c50a9489c4fa7..bcb62acb86487 100644 --- a/external-crates/move/move-core/types/src/gas_algebra.rs +++ b/external-crates/move/move-core/types/src/gas_algebra.rs @@ -132,6 +132,7 @@ impl From> for u64 { * Clone & Copy * **************************************************************************************************/ +#[allow(clippy::incorrect_clone_impl_on_copy_type)] impl Clone for GasQuantity { fn clone(&self) -> Self { Self::new(self.val) diff --git a/external-crates/move/move-ir-compiler/move-ir-to-bytecode/src/context.rs b/external-crates/move/move-ir-compiler/move-ir-to-bytecode/src/context.rs index 8afc1aebf0a06..8aa51badae665 100644 --- a/external-crates/move/move-ir-compiler/move-ir-to-bytecode/src/context.rs +++ b/external-crates/move/move-ir-compiler/move-ir-to-bytecode/src/context.rs @@ -346,7 +346,7 @@ impl<'a> Context<'a> { } fn materialize_map(m: HashMap) -> Vec { - Self::materialize_pool(m.len(), m.into_iter()) + Self::materialize_pool(m.len(), m) } /// Finish compilation, and materialize the pools for file format. diff --git a/external-crates/move/move-ir-compiler/move-ir-to-bytecode/syntax/src/syntax.rs b/external-crates/move/move-ir-compiler/move-ir-to-bytecode/syntax/src/syntax.rs index 1054ca4048026..42bb47ec1d1da 100644 --- a/external-crates/move/move-ir-compiler/move-ir-to-bytecode/syntax/src/syntax.rs +++ b/external-crates/move/move-ir-compiler/move-ir-to-bytecode/syntax/src/syntax.rs @@ -1481,7 +1481,7 @@ fn parse_acquire_list( Ok(al) } -//// Spec language parsing //// +/// Spec language parsing /// // parses Name '.' Name and returns pair of strings. fn spec_parse_dot_name( diff --git a/external-crates/move/move-model/src/builder/exp_translator.rs b/external-crates/move/move-model/src/builder/exp_translator.rs index 8d7a626401669..86dbb17d4fc9c 100644 --- a/external-crates/move/move-model/src/builder/exp_translator.rs +++ b/external-crates/move/move-model/src/builder/exp_translator.rs @@ -1650,7 +1650,7 @@ impl<'env, 'translator, 'module_translator> ExpTranslator<'env, 'translator, 'mo let expected_user_count = param_count - args.len(); if let Some(types) = user_args { let n = types.len(); - args.extend(types.into_iter()); + args.extend(types); if n != expected_user_count { ( args, diff --git a/external-crates/move/move-prover/boogie-backend/src/lib.rs b/external-crates/move/move-prover/boogie-backend/src/lib.rs index a255739ce4da9..cd10d7b5308aa 100644 --- a/external-crates/move/move-prover/boogie-backend/src/lib.rs +++ b/external-crates/move/move-prover/boogie-backend/src/lib.rs @@ -188,7 +188,7 @@ pub fn add_prelude( .vec_inst .iter() .map(|ty| TypeInfo::new(env, options, ty, false)) - .chain(implicit_vec_inst.into_iter()) + .chain(implicit_vec_inst) .collect::>() .into_iter() .collect_vec(); diff --git a/external-crates/move/move-prover/bytecode/src/dataflow_domains.rs b/external-crates/move/move-prover/bytecode/src/dataflow_domains.rs index f0c48dff4585c..337c272ac011e 100644 --- a/external-crates/move/move-prover/bytecode/src/dataflow_domains.rs +++ b/external-crates/move/move-prover/bytecode/src/dataflow_domains.rs @@ -282,6 +282,6 @@ impl MapDomain { } }) .collect_vec(); - self.extend(new_values.into_iter()); + self.extend(new_values); } } diff --git a/external-crates/move/move-prover/bytecode/src/verification_analysis.rs b/external-crates/move/move-prover/bytecode/src/verification_analysis.rs index c67a486c91d26..57a601334bdf7 100644 --- a/external-crates/move/move-prover/bytecode/src/verification_analysis.rs +++ b/external-crates/move/move-prover/bytecode/src/verification_analysis.rs @@ -371,7 +371,7 @@ impl VerificationAnalysisProcessor { targets: &mut FunctionTargetsHolder, ) { // TODO(mengxu): re-check the treatment of fixedpoint here - let mut info = data + let info = data .annotations .get_or_default_mut::(true); if !info.verified { diff --git a/external-crates/move/move-prover/bytecode/src/verification_analysis_v2.rs b/external-crates/move/move-prover/bytecode/src/verification_analysis_v2.rs index 33fa359afcf96..b30980f736e7a 100644 --- a/external-crates/move/move-prover/bytecode/src/verification_analysis_v2.rs +++ b/external-crates/move/move-prover/bytecode/src/verification_analysis_v2.rs @@ -738,7 +738,7 @@ fn mark_verified( // The user can override with `pragma verify = false`, so respect this. let options = ProverOptions::get(fun_env.module_env.env); if !actual_env.is_explicitly_not_verified(&options.verify_scope) { - let mut info = targets + let info = targets .get_data_mut(&actual_env.get_qualified_id(), &variant) .expect("function data available") .annotations diff --git a/external-crates/move/move-prover/interpreter/src/concrete/evaluator.rs b/external-crates/move/move-prover/interpreter/src/concrete/evaluator.rs index 5af3a63632d0d..bee5a2764389b 100644 --- a/external-crates/move/move-prover/interpreter/src/concrete/evaluator.rs +++ b/external-crates/move/move-prover/interpreter/src/concrete/evaluator.rs @@ -738,7 +738,7 @@ impl<'env> Evaluator<'env> { let choose_val_range_vec = choose_val_range.unwrap(); let mut v_results: Vec<_> = choose_val_range_vec .into_iter() - .zip(loop_results.into_iter()) + .zip(loop_results) .filter_map(|(val, r)| if r.into_bool() { Some(val) } else { None }) .collect(); @@ -754,7 +754,7 @@ impl<'env> Evaluator<'env> { let choose_val_range_vec = choose_val_range.unwrap(); let mut v_results: Vec<_> = choose_val_range_vec .into_iter() - .zip(loop_results.into_iter()) + .zip(loop_results) .filter_map(|(val, r)| if r.into_bool() { Some(val) } else { None }) .collect(); @@ -912,7 +912,7 @@ impl<'env> Evaluator<'env> { let typed_args = decl .params .iter() - .zip(arg_vals.into_iter()) + .zip(arg_vals) .map(|((_, arg_ty), arg_val)| { let converted = convert_model_base_type(env, arg_ty, &ty_args); TypedValue::fuse_base(converted, arg_val) diff --git a/external-crates/move/move-vm/runtime/src/interpreter.rs b/external-crates/move/move-vm/runtime/src/interpreter.rs index dc556173d5ae3..b4d5bc8051c72 100644 --- a/external-crates/move/move-vm/runtime/src/interpreter.rs +++ b/external-crates/move/move-vm/runtime/src/interpreter.rs @@ -2437,7 +2437,8 @@ impl Frame { .loader() .vm_config() .runtime_limits_config - .max_value_nest_depth else { + .max_value_nest_depth + else { return Ok(1); }; Self::check_depth_of_type_impl(resolver, ty, 0, max_depth) diff --git a/external-crates/move/move-vm/types/src/loaded_data/runtime_types.rs b/external-crates/move/move-vm/types/src/loaded_data/runtime_types.rs index 7a694cf2d0278..4cd185c7b45d8 100644 --- a/external-crates/move/move-vm/types/src/loaded_data/runtime_types.rs +++ b/external-crates/move/move-vm/types/src/loaded_data/runtime_types.rs @@ -84,7 +84,10 @@ impl DepthFormula { } for (t_i, c_i) in terms { let Some(mut u_form) = map.remove(t_i) else { - return Err(PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR).with_message(format!("{t_i:?} missing mapping"))) + return Err( + PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR) + .with_message(format!("{t_i:?} missing mapping")), + ); }; u_form.add(*c_i); formulas.push(u_form) diff --git a/external-crates/move/tools/move-bytecode-viewer/src/tui/text_builder.rs b/external-crates/move/tools/move-bytecode-viewer/src/tui/text_builder.rs index d6feeacfa423c..03943066f622d 100644 --- a/external-crates/move/tools/move-bytecode-viewer/src/tui/text_builder.rs +++ b/external-crates/move/tools/move-bytecode-viewer/src/tui/text_builder.rs @@ -56,7 +56,7 @@ impl<'a> TextBuilder<'a> { .push(Span::styled(line_continuation.to_string(), style)); }); iter.next().into_iter().for_each(|remainder| { - self.chunks.extend(chunk(remainder.to_string()).into_iter()); + self.chunks.extend(chunk(remainder.to_string())); }); } else { self.chunks.extend(chunk(text)) diff --git a/external-crates/move/tools/move-cli/src/base/test.rs b/external-crates/move/tools/move-cli/src/base/test.rs index d717de2059358..8130e94bffe46 100644 --- a/external-crates/move/tools/move-cli/src/base/test.rs +++ b/external-crates/move/tools/move-cli/src/base/test.rs @@ -27,7 +27,7 @@ use std::{ #[cfg(target_family = "windows")] use std::os::windows::process::ExitStatusExt; // if unix -#[cfg(any(target_family = "unix"))] +#[cfg(target_family = "unix")] use std::os::unix::prelude::ExitStatusExt; // if not windows nor unix #[cfg(not(any(target_family = "windows", target_family = "unix")))] diff --git a/external-crates/move/tools/move-cli/src/sandbox/utils/mod.rs b/external-crates/move/tools/move-cli/src/sandbox/utils/mod.rs index 7cfd995611f27..40c73d4551bf5 100644 --- a/external-crates/move/tools/move-cli/src/sandbox/utils/mod.rs +++ b/external-crates/move/tools/move-cli/src/sandbox/utils/mod.rs @@ -1,7 +1,7 @@ // Copyright (c) The Diem Core Contributors // Copyright (c) The Move Contributors // SPDX-License-Identifier: Apache-2.0 - +#[allow(hidden_glob_reexports)] use crate::sandbox::utils::on_disk_state_view::OnDiskStateView; use anyhow::{bail, Result}; use colored::Colorize; diff --git a/external-crates/move/tools/move-disassembler/src/disassembler.rs b/external-crates/move/tools/move-disassembler/src/disassembler.rs index 2f96d4fb8806d..8b32ca58a177a 100644 --- a/external-crates/move/tools/move-disassembler/src/disassembler.rs +++ b/external-crates/move/tools/move-disassembler/src/disassembler.rs @@ -454,7 +454,7 @@ impl<'a> Disassembler<'a> { .into_iter() .enumerate() .map(|(local_idx, local)| format!("L{}:\t{}", local_idx, local)) - .chain(bytecode.into_iter()) + .chain(bytecode) .collect(); format!(" {{\n{}\n}}", body_iter.join("\n")) } diff --git a/external-crates/move/tools/move-package/src/compilation/model_builder.rs b/external-crates/move/tools/move-package/src/compilation/model_builder.rs index 6050ad2788fcb..0c9588ccc0067 100644 --- a/external-crates/move/tools/move-package/src/compilation/model_builder.rs +++ b/external-crates/move/tools/move-package/src/compilation/model_builder.rs @@ -74,7 +74,7 @@ impl ModelBuilder { )?; let (all_targets, all_deps) = if self.model_config.all_files_as_targets { let mut targets = vec![target]; - targets.extend(deps.into_iter()); + targets.extend(deps); (targets, vec![]) } else { (vec![target], deps) diff --git a/external-crates/move/tools/move-package/src/resolution/dependency_graph.rs b/external-crates/move/tools/move-package/src/resolution/dependency_graph.rs index db72681caf52d..2a6e2badd8505 100644 --- a/external-crates/move/tools/move-package/src/resolution/dependency_graph.rs +++ b/external-crates/move/tools/move-package/src/resolution/dependency_graph.rs @@ -619,9 +619,8 @@ impl DependencyGraph { continue; }; // graph g has a package with name pkg_name - let Some(( existing_graph, existing_pkg, existing_is_external)) = - existing_pkg_info else - { + let Some((existing_graph, existing_pkg, existing_is_external)) = existing_pkg_info + else { // first time this package was encountered existing_pkg_info = Some((&graph_info.g, pkg, graph_info.is_external)); continue; @@ -1234,7 +1233,7 @@ impl DependencyGraph { .filter(|scc| scc.len() != 1 || self.package_graph.contains_edge(scc[0], scc[0])); let Some(scc) = cyclic_components.next() else { - return Ok(()) + return Ok(()); }; // Duplicate start of the node at end for display @@ -1395,7 +1394,7 @@ impl<'a> fmt::Display for SubstTOML<'a> { let mut substs = self.0.iter(); let Some((addr, subst)) = substs.next() else { - return f.write_str("{}") + return f.write_str("{}"); }; f.write_str("{ ")?; diff --git a/external-crates/move/tools/move-package/tests/test_dependency_graph.rs b/external-crates/move/tools/move-package/tests/test_dependency_graph.rs index 4508e4285d8b1..f17f4ed772a14 100644 --- a/external-crates/move/tools/move-package/tests/test_dependency_graph.rs +++ b/external-crates/move/tools/move-package/tests/test_dependency_graph.rs @@ -129,7 +129,7 @@ fn lock_file_missing_dependency() { pkg, Symbol::from("Root"), &mut File::open(&commit).expect("Opening empty lock file"), - None + None, ) else { panic!("Expected reading dependencies to fail."); }; @@ -330,7 +330,7 @@ fn merge_detached() { dep_graphs, &DependencyKind::default(), &BTreeMap::new(), - &BTreeMap::new() + &BTreeMap::new(), ) else { panic!("Inner's root is not part of outer's graph, so this should fail"); }; @@ -365,7 +365,7 @@ fn merge_after_calculating_always_deps() { dep_graphs, &DependencyKind::default(), &BTreeMap::new(), - &BTreeMap::new() + &BTreeMap::new(), ) else { panic!("Outer's always deps have already been calculated so this should fail"); }; @@ -515,7 +515,7 @@ fn merge_overlapping_different_deps() { dep_graphs, &DependencyKind::default(), dependencies, - &BTreeMap::new() + &BTreeMap::new(), ) else { panic!("Outer and inner mention package A which has different dependencies in both."); }; diff --git a/external-crates/move/tools/move-package/tests/test_runner.rs b/external-crates/move/tools/move-package/tests/test_runner.rs index 3a361dc6da5e4..db3c30f51115c 100644 --- a/external-crates/move/tools/move-package/tests/test_runner.rs +++ b/external-crates/move/tools/move-package/tests/test_runner.rs @@ -110,7 +110,10 @@ impl Test<'_> { fn output(&self) -> anyhow::Result { let Some(ext) = self.expected.extension().and_then(OsStr::to_str) else { - bail!("Unexpected snapshot file extension: {:?}", self.expected.extension()); + bail!( + "Unexpected snapshot file extension: {:?}", + self.expected.extension() + ); }; let out_path = self.output_dir.path().to_path_buf(); diff --git a/external-crates/move/tools/move-resource-viewer/src/lib.rs b/external-crates/move/tools/move-resource-viewer/src/lib.rs index 75039344c6905..dd312469eaaa6 100644 --- a/external-crates/move/tools/move-resource-viewer/src/lib.rs +++ b/external-crates/move/tools/move-resource-viewer/src/lib.rs @@ -171,7 +171,7 @@ impl<'a, T: MoveResolver + ?Sized> MoveValueAnnotator<'a, T> { .cache .get_field_names(&ty)? .into_iter() - .zip(runtime.into_iter()) + .zip(runtime) .collect(), MoveStruct::WithFields(fields) | MoveStruct::WithTypes { fields, .. } => fields, }) @@ -204,10 +204,7 @@ impl<'a, T: MoveResolver + ?Sized> MoveValueAnnotator<'a, T> { Ok(AnnotatedMoveStruct { abilities: ty.abilities.0, type_: struct_tag, - value: field_names - .into_iter() - .zip(annotated_fields.into_iter()) - .collect(), + value: field_names.into_iter().zip(annotated_fields).collect(), }) } diff --git a/external-crates/move/tools/move-unit-test/src/lib.rs b/external-crates/move/tools/move-unit-test/src/lib.rs index a3081040819b7..2b3bfbb622ef7 100644 --- a/external-crates/move/tools/move-unit-test/src/lib.rs +++ b/external-crates/move/tools/move-unit-test/src/lib.rs @@ -198,8 +198,8 @@ impl UnitTestingConfig { } = self.compile_to_test_plan(deps.clone(), vec![])?; let mut test_plan = self.compile_to_test_plan(self.source_files.clone(), deps)?; - test_plan.module_info.extend(module_info.into_iter()); - test_plan.files.extend(files.into_iter()); + test_plan.module_info.extend(module_info); + test_plan.files.extend(files); Some(test_plan) } diff --git a/narwhal/Docker/Dockerfile b/narwhal/Docker/Dockerfile index a3c3d33346bf1..251a1506d86ad 100644 --- a/narwhal/Docker/Dockerfile +++ b/narwhal/Docker/Dockerfile @@ -2,7 +2,7 @@ # # Copy in all crates, Cargo.toml and Cargo.lock unmodified, # and build the application. -FROM rust:1.70.0 AS builder +FROM rust:1.73-bullseye AS builder ARG PROFILE=release ARG GIT_REVISION ENV GIT_REVISION=$GIT_REVISION diff --git a/narwhal/config/src/committee.rs b/narwhal/config/src/committee.rs index 2fff58d8008f5..56827b27faf6b 100644 --- a/narwhal/config/src/committee.rs +++ b/narwhal/config/src/committee.rs @@ -390,6 +390,7 @@ impl Committee { /// Update the networking information of some of the primaries. The arguments are a full vector of /// authorities which Public key and Stake must match the one stored in the current Committee. Any discrepancy /// will generate no update and return a vector of errors. + #[allow(clippy::manual_try_fold)] pub fn update_primary_network_info( &mut self, mut new_info: BTreeMap, diff --git a/narwhal/consensus/src/tests/randomized_tests.rs b/narwhal/consensus/src/tests/randomized_tests.rs index c1f235afb471d..c98a17bdca227 100644 --- a/narwhal/consensus/src/tests/randomized_tests.rs +++ b/narwhal/consensus/src/tests/randomized_tests.rs @@ -650,9 +650,7 @@ fn create_execution_plan( // shuffle the children here again to create a different execution plan children.shuffle(&mut rand); - while !children.is_empty() { - let c = children.pop().unwrap(); - + while let Some(c) = children.pop() { // has this children any other dependencies (certificate parents that have not been // already sorted)? If not, then add it to the candidate of nodes without incoming edges. let has_more_dependencies = adjacency_parent_to_children diff --git a/narwhal/node/src/main.rs b/narwhal/node/src/main.rs index 6c4d2c5d0e056..d9f38c29cfa65 100644 --- a/narwhal/node/src/main.rs +++ b/narwhal/node/src/main.rs @@ -337,7 +337,7 @@ async fn run( worker_cache, client, &store, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, None, ) .await?; diff --git a/narwhal/node/tests/node_test.rs b/narwhal/node/tests/node_test.rs index 535997d05129b..f1786cc9e05ac 100644 --- a/narwhal/node/tests/node_test.rs +++ b/narwhal/node/tests/node_test.rs @@ -69,7 +69,7 @@ async fn simple_primary_worker_node_start_stop() { worker_cache, client, &store, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, ) .await .unwrap(); diff --git a/narwhal/primary/src/certificate_fetcher.rs b/narwhal/primary/src/certificate_fetcher.rs index 5666d25c408b4..c0d71141dd689 100644 --- a/narwhal/primary/src/certificate_fetcher.rs +++ b/narwhal/primary/src/certificate_fetcher.rs @@ -323,9 +323,10 @@ async fn run_fetch_task( .set_bounds(gc_round, written_rounds) .set_max_items(MAX_CERTIFICATES_TO_FETCH); let Some(response) = - fetch_certificates_helper(state.authority_id, &state.network, &committee, request).await else { - return Err(DagError::NoCertificateFetched); - }; + fetch_certificates_helper(state.authority_id, &state.network, &committee, request).await + else { + return Err(DagError::NoCertificateFetched); + }; // Process and store fetched certificates. let num_certs_fetched = response.certificates.len(); diff --git a/narwhal/primary/src/primary.rs b/narwhal/primary/src/primary.rs index 93d0310868604..79a8722422fe7 100644 --- a/narwhal/primary/src/primary.rs +++ b/narwhal/primary/src/primary.rs @@ -66,7 +66,7 @@ use types::{ WorkerOwnBatchMessage, WorkerToPrimary, WorkerToPrimaryServer, }; -#[cfg(any(test))] +#[cfg(test)] #[path = "tests/primary_tests.rs"] pub mod primary_tests; diff --git a/narwhal/primary/src/synchronizer.rs b/narwhal/primary/src/synchronizer.rs index be3092a97fb68..64e67241d1525 100644 --- a/narwhal/primary/src/synchronizer.rs +++ b/narwhal/primary/src/synchronizer.rs @@ -113,9 +113,10 @@ impl Inner { .lock() .entry(certificate.round()) .or_insert_with(|| Box::new(CertificatesAggregator::new())) - .append(certificate.clone(), &self.committee) else { - return Ok(()); - }; + .append(certificate.clone(), &self.committee) + else { + return Ok(()); + }; // Send it to the `Proposer`. self.tx_parents .send((parents, certificate.round(), certificate.epoch())) @@ -395,7 +396,9 @@ impl Synchronizer { const FETCH_TRIGGER_TIMEOUT: Duration = Duration::from_secs(30); let mut rx_consensus_round_updates = rx_consensus_round_updates.clone(); loop { - let Ok(result) = timeout(FETCH_TRIGGER_TIMEOUT, rx_consensus_round_updates.changed()).await else { + let Ok(result) = + timeout(FETCH_TRIGGER_TIMEOUT, rx_consensus_round_updates.changed()).await + else { // When consensus commit has not happened for 30s, it is possible that no new // certificate is received by this primary or created in the network, so // fetching should definitely be started. @@ -404,7 +407,12 @@ impl Synchronizer { debug!("Synchronizer is shutting down."); return; }; - if inner.tx_certificate_fetcher.send(CertificateFetcherCommand::Kick).await.is_err() { + if inner + .tx_certificate_fetcher + .send(CertificateFetcherCommand::Kick) + .await + .is_err() + { debug!("Synchronizer is shutting down."); return; } @@ -460,7 +468,9 @@ impl Synchronizer { spawn_logged_monitored_task!( async move { loop { - let Some((certificate, result_sender, early_suspend)) = rx_certificate_acceptor.recv().await else { + let Some((certificate, result_sender, early_suspend)) = + rx_certificate_acceptor.recv().await + else { debug!("Synchronizer is shutting down."); return; }; diff --git a/narwhal/primary/src/tests/primary_tests.rs b/narwhal/primary/src/tests/primary_tests.rs index 60106767b4a3c..ccd7363f62d60 100644 --- a/narwhal/primary/src/tests/primary_tests.rs +++ b/narwhal/primary/src/tests/primary_tests.rs @@ -120,7 +120,7 @@ async fn test_get_network_peers_from_admin_server() { worker_cache.clone(), test_utils::latest_protocol_version(), worker_1_parameters.clone(), - TrivialTransactionValidator::default(), + TrivialTransactionValidator, client_1, store.batch_store, metrics_1, @@ -236,7 +236,7 @@ async fn test_get_network_peers_from_admin_server() { assert_eq!(2, resp.len()); // Assert peer ids are correct - let expected_peer_ids = vec![&primary_2_peer_id, &worker_1_peer_id]; + let expected_peer_ids = [&primary_2_peer_id, &worker_1_peer_id]; assert!(expected_peer_ids.iter().all(|e| resp.contains(e))); // Test getting all connected peers for primary 2 @@ -256,7 +256,7 @@ async fn test_get_network_peers_from_admin_server() { assert_eq!(2, resp.len()); // Assert peer ids are correct - let expected_peer_ids = vec![&primary_1_peer_id, &worker_1_peer_id]; + let expected_peer_ids = [&primary_1_peer_id, &worker_1_peer_id]; assert!(expected_peer_ids.iter().all(|e| resp.contains(e))); } diff --git a/narwhal/primary/src/tests/synchronizer_tests.rs b/narwhal/primary/src/tests/synchronizer_tests.rs index 8319c25689cd6..628cf0fe6b53d 100644 --- a/narwhal/primary/src/tests/synchronizer_tests.rs +++ b/narwhal/primary/src/tests/synchronizer_tests.rs @@ -722,7 +722,9 @@ async fn deliver_certificate_not_found_parents() { // and we should fail assert!(!parents_available); - let CertificateFetcherCommand::Ancestors(certificate) = rx_certificate_fetcher.recv().await.unwrap() else { + let CertificateFetcherCommand::Ancestors(certificate) = + rx_certificate_fetcher.recv().await.unwrap() + else { panic!("Expected CertificateFetcherCommand::Ancestors"); }; diff --git a/narwhal/test-utils/src/cluster.rs b/narwhal/test-utils/src/cluster.rs index b1f4fab933995..84fbf658a12b2 100644 --- a/narwhal/test-utils/src/cluster.rs +++ b/narwhal/test-utils/src/cluster.rs @@ -465,7 +465,7 @@ impl WorkerNodeDetails { self.worker_cache.clone(), client, &worker_store, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, None, ) .await @@ -512,6 +512,7 @@ struct AuthorityDetailsInternal { workers: HashMap, } +#[allow(clippy::arc_with_non_send_sync)] impl AuthorityDetails { pub fn new( id: usize, diff --git a/narwhal/worker/src/tests/worker_tests.rs b/narwhal/worker/src/tests/worker_tests.rs index 378d16b2763ee..3e3fa0460afd9 100644 --- a/narwhal/worker/src/tests/worker_tests.rs +++ b/narwhal/worker/src/tests/worker_tests.rs @@ -185,7 +185,7 @@ async fn handle_remote_clients_transactions() { worker_cache.clone(), latest_protocol_version(), parameters, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, client.clone(), batch_store, metrics, @@ -304,7 +304,7 @@ async fn handle_local_clients_transactions() { worker_cache.clone(), latest_protocol_version(), parameters, - TrivialTransactionValidator::default(), + TrivialTransactionValidator, client.clone(), batch_store, metrics, @@ -445,7 +445,7 @@ async fn get_network_peers_from_admin_server() { worker_cache.clone(), latest_protocol_version(), worker_1_parameters.clone(), - TrivialTransactionValidator::default(), + TrivialTransactionValidator, client_1.clone(), store.batch_store.clone(), metrics_1.clone(), @@ -493,7 +493,7 @@ async fn get_network_peers_from_admin_server() { assert_eq!(1, resp.len()); // Assert peer ids are correct - let expected_peer_ids = vec![&primary_1_peer_id]; + let expected_peer_ids = [&primary_1_peer_id]; assert!(expected_peer_ids.iter().all(|e| resp.contains(e))); let authority_2 = fixture.authorities().nth(1).unwrap(); @@ -560,7 +560,7 @@ async fn get_network_peers_from_admin_server() { worker_cache.clone(), latest_protocol_version(), worker_2_parameters.clone(), - TrivialTransactionValidator::default(), + TrivialTransactionValidator, client_2, store.batch_store, metrics_2.clone(), @@ -609,7 +609,7 @@ async fn get_network_peers_from_admin_server() { assert_eq!(3, resp.len()); // Assert peer ids are correct - let expected_peer_ids = vec![&primary_1_peer_id, &primary_2_peer_id, &worker_2_peer_id]; + let expected_peer_ids = [&primary_1_peer_id, &primary_2_peer_id, &worker_2_peer_id]; assert!(expected_peer_ids.iter().all(|e| resp.contains(e))); // Test getting all connected peers for worker 2 (worker at index 0 for primary 2) @@ -630,7 +630,7 @@ async fn get_network_peers_from_admin_server() { assert_eq!(3, resp.len()); // Assert peer ids are correct - let expected_peer_ids = vec![&primary_1_peer_id, &primary_2_peer_id, &worker_1_peer_id]; + let expected_peer_ids = [&primary_1_peer_id, &primary_2_peer_id, &worker_1_peer_id]; assert!(expected_peer_ids.iter().all(|e| resp.contains(e))); // Assert network connectivity metrics are also set as expected diff --git a/rust-toolchain.toml b/rust-toolchain.toml index f400973ca7fe6..50fa4928b96fe 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.70" +channel = "1.73" diff --git a/sui-execution/cut/src/plan.rs b/sui-execution/cut/src/plan.rs index a41e084807a39..f3e66416bb5a6 100644 --- a/sui-execution/cut/src/plan.rs +++ b/sui-execution/cut/src/plan.rs @@ -155,7 +155,7 @@ impl CutPlan { let toml = src.join("Cargo.toml"); let Some(pkg_name) = package_name(toml)? else { - return Ok(()) + return Ok(()); }; if !self.pending_packages.remove(&pkg_name) { @@ -343,7 +343,7 @@ impl CutPlan { ) -> Result<()> { for field in ["dependencies", "dev-dependencies", "build-dependencies"] { let Some(deps) = table.get_mut(field).and_then(Item::as_table_like_mut) else { - continue + continue; }; for (dep_name, dep) in deps.iter_mut() { @@ -370,7 +370,7 @@ impl CutPlan { dep: &mut Item, ) -> Result<()> { let Some(dep) = dep.as_table_like_mut() else { - return Ok(()) + return Ok(()); }; // If the dep has an explicit package name, use that as the key for finding package @@ -383,7 +383,7 @@ impl CutPlan { // Only path-based dependencies need to be updated. let Some(path) = dep.get_mut("path") else { - return Ok(()) + return Ok(()); }; if let Some(dep_pkg) = dep_pkg { @@ -590,7 +590,9 @@ fn toml_path_array_to_set>( ) -> Result> { let mut set = HashSet::new(); - let Some(array) = table.get(field) else { return Ok(set) }; + let Some(array) = table.get(field) else { + return Ok(set); + }; let Some(array) = array.as_array() else { bail!(Error::NotAStringArray(field)) }; @@ -1145,7 +1147,7 @@ mod tests { fs::write( root.join("Cargo.toml"), - vec![ + [ r#"[workspace]"#, r#"members = ["crates/foo"]"#, r#"exclude = ["#, @@ -1165,7 +1167,7 @@ mod tests { fs::write( root.join("crates/bar/Cargo.toml"), - vec![ + [ r#"[package]"#, r#"name = "bar""#, r#""#, @@ -1182,7 +1184,7 @@ mod tests { fs::write( root.join("crates/baz/Cargo.toml"), - vec![ + [ r#"[package]"#, r#"name = "baz""#, r#""#, @@ -1198,7 +1200,7 @@ mod tests { fs::write( root.join("crates/qux/Cargo.toml"), - vec![ + [ r#"[package]"#, r#"name = "qux""#, r#""#, @@ -1214,7 +1216,7 @@ mod tests { fs::write( root.join("crates/quy/Cargo.toml"), - vec![r#"[package]"#, r#"name = "quy""#].join("\n"), + [r#"[package]"#, r#"name = "quy""#].join("\n"), ) .unwrap(); diff --git a/sui-execution/latest/sui-adapter/src/adapter.rs b/sui-execution/latest/sui-adapter/src/adapter.rs index 520d3311765ec..b25c5f5c166d5 100644 --- a/sui-execution/latest/sui-adapter/src/adapter.rs +++ b/sui-execution/latest/sui-adapter/src/adapter.rs @@ -146,12 +146,12 @@ mod checked { let addrs = &mut module.address_identifiers; let Some(address_mut) = addrs.get_mut(self_address_idx.0 as usize) else { - let name = module.identifier_at(self_handle.name); - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::PublishErrorNonZeroAddress, - format!("Publishing module {name} with invalid address index"), - )); - }; + let name = module.identifier_at(self_handle.name); + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::PublishErrorNonZeroAddress, + format!("Publishing module {name} with invalid address index"), + )); + }; if *address_mut != AccountAddress::ZERO { let name = module.identifier_at(self_handle.name); diff --git a/sui-execution/latest/sui-adapter/src/gas_charger.rs b/sui-execution/latest/sui-adapter/src/gas_charger.rs index 329fdfae6ad53..6f1abd8c167a4 100644 --- a/sui-execution/latest/sui-adapter/src/gas_charger.rs +++ b/sui-execution/latest/sui-adapter/src/gas_charger.rs @@ -139,10 +139,10 @@ pub mod checked { .map(|obj_ref| { let obj = temporary_store.objects().get(&obj_ref.0).unwrap(); let Data::Move(move_obj) = &obj.data else { - return Err(ExecutionError::invariant_violation( - "Provided non-gas coin object as input for gas!" - )); - }; + return Err(ExecutionError::invariant_violation( + "Provided non-gas coin object as input for gas!", + )); + }; if !move_obj.type_().is_gas_coin() { return Err(ExecutionError::invariant_violation( "Provided non-gas coin object as input for gas!", diff --git a/sui-execution/latest/sui-adapter/src/programmable_transactions/context.rs b/sui-execution/latest/sui-adapter/src/programmable_transactions/context.rs index 7b4138f9cb839..44a23414ec3c3 100644 --- a/sui-execution/latest/sui-adapter/src/programmable_transactions/context.rs +++ b/sui-execution/latest/sui-adapter/src/programmable_transactions/context.rs @@ -48,7 +48,7 @@ mod checked { use sui_types::execution::ExecutionResults; use sui_types::{ balance::Balance, - base_types::{MoveObjectType, ObjectID, SequenceNumber, SuiAddress, TxContext}, + base_types::{MoveObjectType, ObjectID, SuiAddress, TxContext}, coin::Coin, error::{ExecutionError, ExecutionErrorKind}, event::Event, @@ -163,7 +163,8 @@ mod checked { let Some(Value::Object(ObjectValue { contents: ObjectContents::Coin(coin), .. - })) = &mut gas.inner.value else { + })) = &mut gas.inner.value + else { invariant_violation!("Gas object should be a populated coin") }; @@ -586,13 +587,17 @@ mod checked { let mut additional_writes = BTreeMap::new(); for input in inputs.into_iter().chain(std::iter::once(gas)) { let InputValue { - object_metadata: Some(InputObjectMetadata::InputObject { - // We are only interested in mutable inputs. - is_mutable_input: true, - id, version, owner, - }), + object_metadata: + Some(InputObjectMetadata::InputObject { + // We are only interested in mutable inputs. + is_mutable_input: true, + id, + version, + owner, + }), inner: ResultValue { value, .. }, - } = input else { + } = input + else { continue; }; loaded_runtime_objects.insert( @@ -1094,7 +1099,11 @@ mod checked { new_packages: &[MovePackage], object: &Object, ) -> Result { - let Object { data: Data::Move(object), .. } = object else { + let Object { + data: Data::Move(object), + .. + } = object + else { invariant_violation!("Expected a Move object"); }; @@ -1264,21 +1273,18 @@ mod checked { gas_charger: &mut GasCharger, gas_id: ObjectID, ) -> Result<(), ExecutionError> { - let Some(AdditionalWrite { bytes,.. }) = additional_writes.get_mut(&gas_id) else { + let Some(AdditionalWrite { bytes, .. }) = additional_writes.get_mut(&gas_id) else { invariant_violation!("Gas object cannot be wrapped or destroyed") }; let Ok(mut coin) = Coin::from_bcs_bytes(bytes) else { invariant_violation!("Gas object must be a coin") }; - let Some(new_balance) = coin - .balance - .value() - .checked_add(gas_charger.gas_budget()) else { - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::CoinBalanceOverflow, - "Gas coin too large after returning the max gas budget", - )); - }; + let Some(new_balance) = coin.balance.value().checked_add(gas_charger.gas_budget()) else { + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::CoinBalanceOverflow, + "Gas coin too large after returning the max gas budget", + )); + }; coin.balance = Balance::new(new_balance); *bytes = coin.to_bcs_bytes(); Ok(()) @@ -1319,7 +1325,7 @@ mod checked { MoveObject::new_from_execution( struct_tag.into(), has_public_transfer, - old_obj_ver.unwrap_or_else(SequenceNumber::new), + old_obj_ver.unwrap_or_default(), contents, protocol_config, ) diff --git a/sui-execution/latest/sui-adapter/src/programmable_transactions/execution.rs b/sui-execution/latest/sui-adapter/src/programmable_transactions/execution.rs index 0247ec74492aa..1fbd850c7d526 100644 --- a/sui-execution/latest/sui-adapter/src/programmable_transactions/execution.rs +++ b/sui-execution/latest/sui-adapter/src/programmable_transactions/execution.rs @@ -625,12 +625,10 @@ mod checked { )); }; - let Ok(current_normalized) = existing_package - .normalize( - context.protocol_config.move_binary_format_version(), - context.protocol_config.no_extraneous_module_bytes(), - ) - else { + let Ok(current_normalized) = existing_package.normalize( + context.protocol_config.move_binary_format_version(), + context.protocol_config.no_extraneous_module_bytes(), + ) else { invariant_violation!("Tried to normalize modules in existing package but failed") }; @@ -926,9 +924,14 @@ mod checked { .get_runtime() .load_module(module_id, &data_store) .map_err(|e| context.convert_vm_error(e))?; - let Some((index, fdef)) = module.function_defs.iter().enumerate().find(|(_index, fdef)| { - module.identifier_at(module.function_handle_at(fdef.function).name) == function - }) else { + let Some((index, fdef)) = module + .function_defs + .iter() + .enumerate() + .find(|(_index, fdef)| { + module.identifier_at(module.function_handle_at(fdef.function).name) == function + }) + else { return Err(ExecutionError::new_with_source( ExecutionErrorKind::FunctionNotFound, format!( @@ -1315,14 +1318,11 @@ mod checked { return Err(command_argument_error( CommandArgumentError::TypeMismatch, idx, - )) + )); + }; + let Some(s) = context.vm.get_runtime().get_struct_type(*sidx) else { + invariant_violation!("sui::transfer::Receiving struct not found in session") }; - let Some(s) = context - .vm - .get_runtime() - .get_struct_type(*sidx) else { - invariant_violation!("sui::transfer::Receiving struct not found in session") - }; let resolved_struct = get_struct_ident(&s); if resolved_struct != RESOLVED_RECEIVING_STRUCT || targs.len() != 1 { @@ -1358,7 +1358,9 @@ mod checked { Type::Reference(inner) => (false, inner), _ => return Ok(TxContextKind::None), }; - let Type::Struct(idx) = &**inner else { return Ok(TxContextKind::None) }; + let Type::Struct(idx) = &**inner else { + return Ok(TxContextKind::None); + }; let Some(s) = context.vm.get_runtime().get_struct_type(*idx) else { invariant_violation!("Loaded struct not found") }; diff --git a/sui-execution/latest/sui-adapter/src/programmable_transactions/linkage_view.rs b/sui-execution/latest/sui-adapter/src/programmable_transactions/linkage_view.rs index fb4dc39d8d01f..748951a33e89f 100644 --- a/sui-execution/latest/sui-adapter/src/programmable_transactions/linkage_view.rs +++ b/sui-execution/latest/sui-adapter/src/programmable_transactions/linkage_view.rs @@ -128,15 +128,11 @@ impl<'state> LinkageView<'state> { } in context.type_origin_table() { let Ok(module_name) = Identifier::from_str(module_name) else { - invariant_violation!( - "Module name isn't an identifier: {module_name}" - ); + invariant_violation!("Module name isn't an identifier: {module_name}"); }; let Ok(struct_name) = Identifier::from_str(struct_name) else { - invariant_violation!( - "Struct name isn't an identifier: {struct_name}" - ); + invariant_violation!("Struct name isn't an identifier: {struct_name}"); }; let runtime_id = ModuleId::new(runtime_id, module_name); @@ -216,7 +212,8 @@ impl<'state> LinkageView<'state> { let Some(upgrade) = linkage.link_table.get(&runtime_id) else { invariant_violation!( "Missing linkage for {runtime_id} in context {}, runtime_id is {}", - linkage.storage_id, linkage.runtime_id + linkage.storage_id, + linkage.runtime_id ); }; @@ -243,9 +240,7 @@ impl<'state> LinkageView<'state> { let storage_id = ObjectID::from(*self.relocate(runtime_id)?.address()); let Some(package) = self.resolver.get_package(&storage_id)? else { - invariant_violation!( - "Missing dependent package in store: {storage_id}", - ) + invariant_violation!("Missing dependent package in store: {storage_id}",) }; for TypeOrigin { diff --git a/sui-execution/latest/sui-adapter/src/temporary_store.rs b/sui-execution/latest/sui-adapter/src/temporary_store.rs index f986fc4de8ac6..46138e5826dc6 100644 --- a/sui-execution/latest/sui-adapter/src/temporary_store.rs +++ b/sui-execution/latest/sui-adapter/src/temporary_store.rs @@ -835,7 +835,7 @@ impl<'backing> TemporaryStore<'backing> { }) } else { // not in input objects, must be a dynamic field - let Ok(Some(obj))= self.store.get_object_by_key(id, expected_version) else { + let Ok(Some(obj)) = self.store.get_object_by_key(id, expected_version) else { invariant_violation!( "Failed looking up dynamic field {id} in SUI conservation checking" ); diff --git a/sui-execution/latest/sui-adapter/src/type_layout_resolver.rs b/sui-execution/latest/sui-adapter/src/type_layout_resolver.rs index 2fe0d83943a63..0941e095dd00d 100644 --- a/sui-execution/latest/sui-adapter/src/type_layout_resolver.rs +++ b/sui-execution/latest/sui-adapter/src/type_layout_resolver.rs @@ -45,7 +45,8 @@ impl<'state, 'vm> LayoutResolver for TypeLayoutResolver<'state, 'vm> { format: ObjectFormatOptions, ) -> Result { let struct_tag: StructTag = object.type_().clone().into(); - let Ok(ty) = load_type_from_struct(self.vm, &mut self.linkage_view, &[], &struct_tag) else { + let Ok(ty) = load_type_from_struct(self.vm, &mut self.linkage_view, &[], &struct_tag) + else { return Err(SuiError::FailObjectLayout { st: format!("{}", struct_tag), }); @@ -58,7 +59,7 @@ impl<'state, 'vm> LayoutResolver for TypeLayoutResolver<'state, 'vm> { let Ok(MoveTypeLayout::Struct(layout)) = layout else { return Err(SuiError::FailObjectLayout { st: format!("{}", struct_tag), - }) + }); }; Ok(layout) } diff --git a/sui-execution/latest/sui-move-natives/src/crypto/bls12381.rs b/sui-execution/latest/sui-move-natives/src/crypto/bls12381.rs index b6cb1810d7da8..28c1ef5b21864 100644 --- a/sui-execution/latest/sui-move-natives/src/crypto/bls12381.rs +++ b/sui-execution/latest/sui-move-natives/src/crypto/bls12381.rs @@ -80,9 +80,10 @@ pub fn bls12381_min_sig_verify( let cost = context.gas_used(); let Ok(signature) = - ::from_bytes(&signature_bytes_ref) else { - return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); - }; + ::from_bytes(&signature_bytes_ref) + else { + return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); + }; let public_key = match ::from_bytes(&public_key_bytes_ref) { diff --git a/sui-execution/latest/sui-move-natives/src/crypto/ecvrf.rs b/sui-execution/latest/sui-move-natives/src/crypto/ecvrf.rs index ef3b013f55d43..7605d7235391a 100644 --- a/sui-execution/latest/sui-move-natives/src/crypto/ecvrf.rs +++ b/sui-execution/latest/sui-move-natives/src/crypto/ecvrf.rs @@ -82,11 +82,13 @@ pub fn ecvrf_verify( return Ok(NativeResult::err(cost, INVALID_ECVRF_HASH_LENGTH)); }; - let Ok(public_key) = bcs::from_bytes::(public_key_bytes.as_bytes_ref().as_slice()) else { + let Ok(public_key) = + bcs::from_bytes::(public_key_bytes.as_bytes_ref().as_slice()) + else { return Ok(NativeResult::err(cost, INVALID_ECVRF_PUBLIC_KEY)); }; - let Ok(proof) = bcs::from_bytes::(proof_bytes.as_bytes_ref().as_slice()) else { + let Ok(proof) = bcs::from_bytes::(proof_bytes.as_bytes_ref().as_slice()) else { return Ok(NativeResult::err(cost, INVALID_ECVRF_PROOF)); }; diff --git a/sui-execution/latest/sui-move-natives/src/crypto/ed25519.rs b/sui-execution/latest/sui-move-natives/src/crypto/ed25519.rs index 6f3f2bb6556dc..b082deca9adae 100644 --- a/sui-execution/latest/sui-move-natives/src/crypto/ed25519.rs +++ b/sui-execution/latest/sui-move-natives/src/crypto/ed25519.rs @@ -78,7 +78,8 @@ pub fn ed25519_verify( return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; - let Ok(public_key) = ::from_bytes(&public_key_bytes_ref) else { + let Ok(public_key) = ::from_bytes(&public_key_bytes_ref) + else { return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; diff --git a/sui-execution/latest/sui-move-natives/src/dynamic_field.rs b/sui-execution/latest/sui-move-natives/src/dynamic_field.rs index 2304c14792f5f..dab4c1d9ec76a 100644 --- a/sui-execution/latest/sui-move-natives/src/dynamic_field.rs +++ b/sui-execution/latest/sui-move-natives/src/dynamic_field.rs @@ -131,16 +131,10 @@ pub fn hash_type_and_key( _ => return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)), }; let Some(k_bytes) = k.simple_serialize(&k_layout) else { - return Ok(NativeResult::err( - cost, - E_BCS_SERIALIZATION_FAILURE, - )) + return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)); }; let Ok(id) = derive_dynamic_field_id(parent, &k_tag, &k_bytes) else { - return Ok(NativeResult::err( - cost, - E_BCS_SERIALIZATION_FAILURE, - )); + return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)); }; Ok(NativeResult::ok(cost, smallvec![Value::address(id.into())])) diff --git a/sui-execution/latest/sui-move-natives/src/lib.rs b/sui-execution/latest/sui-move-natives/src/lib.rs index 9d6a9c7ede039..47e8d797e63f0 100644 --- a/sui-execution/latest/sui-move-natives/src/lib.rs +++ b/sui-execution/latest/sui-move-natives/src/lib.rs @@ -790,10 +790,10 @@ pub(crate) fn get_tag_and_layouts( } }; let Some(layout) = context.type_to_type_layout(ty)? else { - return Ok(None) + return Ok(None); }; let Some(annotated_layout) = context.type_to_fully_annotated_layout(ty)? else { - return Ok(None) + return Ok(None); }; Ok(Some((*tag, layout, annotated_layout))) } diff --git a/sui-execution/latest/sui-move-natives/src/object_runtime/mod.rs b/sui-execution/latest/sui-move-natives/src/object_runtime/mod.rs index d333ac2b4f072..0754124c7a1b8 100644 --- a/sui-execution/latest/sui-move-natives/src/object_runtime/mod.rs +++ b/sui-execution/latest/sui-move-natives/src/object_runtime/mod.rs @@ -380,7 +380,8 @@ impl<'a> ObjectRuntime<'a> { child_layout, child_fully_annotated_layout, child_move_type, - )? else { + )? + else { return Ok(None); }; // NB: It is important that the object only be added to the received set after it has been diff --git a/sui-execution/latest/sui-move-natives/src/object_runtime/object_store.rs b/sui-execution/latest/sui-move-natives/src/object_runtime/object_store.rs index 05375d053487f..0b695a5b5ea32 100644 --- a/sui-execution/latest/sui-move-natives/src/object_runtime/object_store.rs +++ b/sui-execution/latest/sui-move-natives/src/object_runtime/object_store.rs @@ -360,11 +360,12 @@ impl<'a> ChildObjectStore<'a> { child_fully_annotated_layout: &MoveTypeLayout, child_move_type: MoveObjectType, ) -> PartialVMResult, DynamicallyLoadedObjectMetadata)>> { - let Some((obj, obj_meta)) = self - .inner - .receive_object_from_store(parent, child, child_version)? else { - return Ok(None) - }; + let Some((obj, obj_meta)) = + self.inner + .receive_object_from_store(parent, child, child_version)? + else { + return Ok(None); + }; Ok(Some( match deserialize_move_object(&obj, child_ty, child_layout, child_move_type)? { diff --git a/sui-execution/latest/sui-move-natives/src/test_scenario.rs b/sui-execution/latest/sui-move-natives/src/test_scenario.rs index 6340d8ff810a7..9aaaa8d245d29 100644 --- a/sui-execution/latest/sui-move-natives/src/test_scenario.rs +++ b/sui-execution/latest/sui-move-natives/src/test_scenario.rs @@ -133,9 +133,9 @@ pub fn end_transaction( inventories .address_inventories .entry(a) - .or_insert_with(BTreeMap::new) + .or_default() .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } Owner::ObjectOwner(_) => (), @@ -143,14 +143,14 @@ pub fn end_transaction( inventories .shared_inventory .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } Owner::Immutable => { inventories .immutable_inventory .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } } diff --git a/sui-execution/latest/sui-move-natives/src/test_utils.rs b/sui-execution/latest/sui-move-natives/src/test_utils.rs index 01e9944004997..50ddbe9c3fc9b 100644 --- a/sui-execution/latest/sui-move-natives/src/test_utils.rs +++ b/sui-execution/latest/sui-move-natives/src/test_utils.rs @@ -33,7 +33,7 @@ pub fn create_one_time_witness( let type_layout = context.type_to_type_layout(&ty)?; let Some(MoveTypeLayout::Struct(struct_layout)) = type_layout else { - return Ok(NativeResult::err(InternalGas::new(1), 0)) + return Ok(NativeResult::err(InternalGas::new(1), 0)); }; if is_otw_struct(&struct_layout, &type_tag) { diff --git a/sui-execution/latest/sui-move-natives/src/transfer.rs b/sui-execution/latest/sui-move-natives/src/transfer.rs index c1a53b757ea00..3fd7b593b43b7 100644 --- a/sui-execution/latest/sui-move-natives/src/transfer.rs +++ b/sui-execution/latest/sui-move-natives/src/transfer.rs @@ -67,11 +67,11 @@ pub fn receive_object_internal( .into(); assert!(ty_args.is_empty()); - let Some((tag, layout, annotated_layout)) = get_tag_and_layouts(context, &child_ty)? else { + let Some((tag, layout, annotated_layout)) = get_tag_and_layouts(context, &child_ty)? else { return Ok(NativeResult::err( - context.gas_used(), - E_BCS_SERIALIZATION_FAILURE, - )) + context.gas_used(), + E_BCS_SERIALIZATION_FAILURE, + )); }; let object_runtime: &mut ObjectRuntime = context.extensions_mut().get_mut(); diff --git a/sui-execution/latest/sui-move-natives/src/types.rs b/sui-execution/latest/sui-move-natives/src/types.rs index 9387004c6ae1e..8f37590d9b96a 100644 --- a/sui-execution/latest/sui-move-natives/src/types.rs +++ b/sui-execution/latest/sui-move-natives/src/types.rs @@ -97,7 +97,7 @@ pub fn is_one_time_witness( let cost = context.gas_used(); let Some(MoveTypeLayout::Struct(struct_layout)) = type_layout else { - return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])) + return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; let is_otw = is_otw_struct(&struct_layout, &type_tag); diff --git a/sui-execution/latest/sui-verifier/src/id_leak_verifier.rs b/sui-execution/latest/sui-verifier/src/id_leak_verifier.rs index 5498a5b632112..100e56a1ede4c 100644 --- a/sui-execution/latest/sui-verifier/src/id_leak_verifier.rs +++ b/sui-execution/latest/sui-verifier/src/id_leak_verifier.rs @@ -212,7 +212,7 @@ impl<'a> IDLeakAnalysis<'a> { fn stack_popn(&mut self, n: u64) -> Result<(), PartialVMError> { let Some(n) = NonZeroU64::new(n) else { - return Ok(()) + return Ok(()); }; self.stack.pop_any_n(n).map_err(|e| { PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION) diff --git a/sui-execution/v0/sui-adapter/src/adapter.rs b/sui-execution/v0/sui-adapter/src/adapter.rs index aeeec97d51d5b..cc283904f3a1a 100644 --- a/sui-execution/v0/sui-adapter/src/adapter.rs +++ b/sui-execution/v0/sui-adapter/src/adapter.rs @@ -145,12 +145,12 @@ mod checked { let addrs = &mut module.address_identifiers; let Some(address_mut) = addrs.get_mut(self_address_idx.0 as usize) else { - let name = module.identifier_at(self_handle.name); - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::PublishErrorNonZeroAddress, - format!("Publishing module {name} with invalid address index"), - )); - }; + let name = module.identifier_at(self_handle.name); + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::PublishErrorNonZeroAddress, + format!("Publishing module {name} with invalid address index"), + )); + }; if *address_mut != AccountAddress::ZERO { let name = module.identifier_at(self_handle.name); diff --git a/sui-execution/v0/sui-adapter/src/gas_charger.rs b/sui-execution/v0/sui-adapter/src/gas_charger.rs index 148afe97d1a7f..7c61137ff9928 100644 --- a/sui-execution/v0/sui-adapter/src/gas_charger.rs +++ b/sui-execution/v0/sui-adapter/src/gas_charger.rs @@ -138,10 +138,10 @@ pub mod checked { .map(|obj_ref| { let obj = temporary_store.objects().get(&obj_ref.0).unwrap(); let Data::Move(move_obj) = &obj.data else { - return Err(ExecutionError::invariant_violation( - "Provided non-gas coin object as input for gas!" - )); - }; + return Err(ExecutionError::invariant_violation( + "Provided non-gas coin object as input for gas!", + )); + }; if !move_obj.type_().is_gas_coin() { return Err(ExecutionError::invariant_violation( "Provided non-gas coin object as input for gas!", diff --git a/sui-execution/v0/sui-adapter/src/programmable_transactions/context.rs b/sui-execution/v0/sui-adapter/src/programmable_transactions/context.rs index ed0b98c980953..5b470ac1d932a 100644 --- a/sui-execution/v0/sui-adapter/src/programmable_transactions/context.rs +++ b/sui-execution/v0/sui-adapter/src/programmable_transactions/context.rs @@ -160,17 +160,18 @@ mod checked { // so to mimic this "off limits" behavior, we act as if the coin has less balance than // it really does let Some(Value::Object(ObjectValue { - contents: ObjectContents::Coin(coin), - .. - })) = &mut gas.inner.value else { - invariant_violation!("Gas object should be a populated coin") - }; + contents: ObjectContents::Coin(coin), + .. + })) = &mut gas.inner.value + else { + invariant_violation!("Gas object should be a populated coin") + }; let max_gas_in_balance = gas_charger.gas_budget(); let Some(new_balance) = coin.balance.value().checked_sub(max_gas_in_balance) else { - invariant_violation!( - "Transaction input checker should check that there is enough gas" - ); - }; + invariant_violation!( + "Transaction input checker should check that there is enough gas" + ); + }; coin.balance = Balance::new(new_balance); gas } else { @@ -329,8 +330,8 @@ mod checked { .type_to_type_layout(&ty) .map_err(|e| self.convert_vm_error(e))?; let Some(bytes) = value.simple_serialize(&layout) else { - invariant_violation!("Failed to deserialize already serialized Move value"); - }; + invariant_violation!("Failed to deserialize already serialized Move value"); + }; Ok((module_id.clone(), tag, bytes)) }) .collect::, ExecutionError>>()?; @@ -486,8 +487,8 @@ mod checked { ); // restore is exclusively used for mut let Ok((_, value_opt)) = self.borrow_mut_impl(arg, None) else { - invariant_violation!("Should be able to borrow argument to restore it") - }; + invariant_violation!("Should be able to borrow argument to restore it") + }; let old_value = value_opt.replace(value); assert_invariant!( old_value.is_none() || old_value.unwrap().is_copyable(), @@ -589,20 +590,23 @@ mod checked { object_metadata: object_metadata_opt, inner: ResultValue { value, .. }, } = input; - let Some(object_metadata) = object_metadata_opt else { return Ok(()) }; - let InputObjectMetadata::InputObject { + let Some(object_metadata) = object_metadata_opt else { + return Ok(()); + }; + let InputObjectMetadata::InputObject { is_mutable_input, owner, id, .. - } = &object_metadata else { + } = &object_metadata + else { unreachable!("Found non-input object metadata for input object when adding writes to input objects -- impossible in v0"); }; input_object_metadata.insert(object_metadata.id(), object_metadata.clone()); let Some(Value::Object(object_value)) = value else { - by_value_inputs.insert(*id); - return Ok(()) - }; + by_value_inputs.insert(*id); + return Ok(()); + }; if *is_mutable_input { add_additional_write(&mut additional_writes, *owner, object_value)?; } @@ -765,8 +769,8 @@ mod checked { .type_to_type_layout(&ty) .map_err(|e| convert_vm_error(e, vm, tmp_session.get_resolver()))?; let Some(bytes) = value.simple_serialize(&layout) else { - invariant_violation!("Failed to deserialize already serialized Move value"); - }; + invariant_violation!("Failed to deserialize already serialized Move value"); + }; // safe because has_public_transfer has been determined by the abilities let move_object = unsafe { create_written_object( @@ -919,14 +923,14 @@ mod checked { Argument::GasCoin => (self.gas.object_metadata.as_ref(), &mut self.gas.inner), Argument::Input(i) => { let Some(input_value) = self.inputs.get_mut(i as usize) else { - return Err(CommandArgumentError::IndexOutOfBounds { idx: i }); - }; + return Err(CommandArgumentError::IndexOutOfBounds { idx: i }); + }; (input_value.object_metadata.as_ref(), &mut input_value.inner) } Argument::Result(i) => { let Some(command_result) = self.results.get_mut(i as usize) else { - return Err(CommandArgumentError::IndexOutOfBounds { idx: i }); - }; + return Err(CommandArgumentError::IndexOutOfBounds { idx: i }); + }; if command_result.len() != 1 { return Err(CommandArgumentError::InvalidResultArity { result_idx: i }); } @@ -934,14 +938,14 @@ mod checked { } Argument::NestedResult(i, j) => { let Some(command_result) = self.results.get_mut(i as usize) else { - return Err(CommandArgumentError::IndexOutOfBounds { idx: i }); - }; + return Err(CommandArgumentError::IndexOutOfBounds { idx: i }); + }; let Some(result_value) = command_result.get_mut(j as usize) else { - return Err(CommandArgumentError::SecondaryIndexOutOfBounds { - result_idx: i, - secondary_idx: j, - }); - }; + return Err(CommandArgumentError::SecondaryIndexOutOfBounds { + result_idx: i, + secondary_idx: j, + }); + }; (None, result_value) } }; @@ -1121,8 +1125,8 @@ mod checked { ) -> Result { let contents = if type_.is_coin() { let Ok(coin) = Coin::from_bcs_bytes(contents) else { - invariant_violation!("Could not deserialize a coin") - }; + invariant_violation!("Could not deserialize a coin") + }; ObjectContents::Coin(coin) } else { ObjectContents::Raw(contents.to_vec()) @@ -1144,9 +1148,13 @@ mod checked { session: &mut Session<'state, 'vm, LinkageView<'state>>, object: &Object, ) -> Result { - let Object { data: Data::Move(object), .. } = object else { - invariant_violation!("Expected a Move object"); - }; + let Object { + data: Data::Move(object), + .. + } = object + else { + invariant_violation!("Expected a Move object"); + }; let used_in_non_entry_move_call = false; make_object_value( @@ -1169,9 +1177,9 @@ mod checked { id: ObjectID, ) -> Result { let Some(obj) = state_view.read_object(&id) else { - // protected by transaction input checker - invariant_violation!("Object {} does not exist yet", id); - }; + // protected by transaction input checker + invariant_violation!("Object {} does not exist yet", id); + }; // override_as_immutable ==> Owner::Shared assert_invariant!( !override_as_immutable || matches!(obj.owner, Owner::Shared { .. }), @@ -1301,16 +1309,13 @@ mod checked { gas_charger: &mut GasCharger, gas_id: ObjectID, ) -> Result<(), ExecutionError> { - let Some(AdditionalWrite { bytes,.. }) = additional_writes.get_mut(&gas_id) else { - invariant_violation!("Gas object cannot be wrapped or destroyed") - }; + let Some(AdditionalWrite { bytes, .. }) = additional_writes.get_mut(&gas_id) else { + invariant_violation!("Gas object cannot be wrapped or destroyed") + }; let Ok(mut coin) = Coin::from_bcs_bytes(bytes) else { - invariant_violation!("Gas object must be a coin") - }; - let Some(new_balance) = coin - .balance - .value() - .checked_add(gas_charger.gas_budget()) else { + invariant_violation!("Gas object must be a coin") + }; + let Some(new_balance) = coin.balance.value().checked_add(gas_charger.gas_budget()) else { return Err(ExecutionError::new_with_source( ExecutionErrorKind::CoinBalanceOverflow, "Gas coin too large after returning the max gas budget", @@ -1369,7 +1374,7 @@ mod checked { MoveObject::new_from_execution( struct_tag.into(), has_public_transfer, - old_obj_ver.unwrap_or_else(SequenceNumber::new), + old_obj_ver.unwrap_or_default(), contents, protocol_config, ) diff --git a/sui-execution/v0/sui-adapter/src/programmable_transactions/execution.rs b/sui-execution/v0/sui-adapter/src/programmable_transactions/execution.rs index b0969865fc938..607f3ae2dd7e1 100644 --- a/sui-execution/v0/sui-adapter/src/programmable_transactions/execution.rs +++ b/sui-execution/v0/sui-adapter/src/programmable_transactions/execution.rs @@ -121,10 +121,10 @@ mod checked { let results = match command { Command::MakeMoveVec(tag_opt, args) if args.is_empty() => { let Some(tag) = tag_opt else { - invariant_violation!( - "input checker ensures if args are empty, there is a type specified" - ); - }; + invariant_violation!( + "input checker ensures if args are empty, there is a type specified" + ); + }; let elem_ty = context .load_type(&tag) .map_err(|e| context.convert_vm_error(e))?; @@ -203,13 +203,13 @@ mod checked { Command::SplitCoins(coin_arg, amount_args) => { let mut obj: ObjectValue = context.borrow_arg_mut(0, coin_arg)?; let ObjectContents::Coin(coin) = &mut obj.contents else { - let e = ExecutionErrorKind::command_argument_error( - CommandArgumentError::TypeMismatch, - 0, - ); - let msg = "Expected a coin but got an non coin object".to_owned(); - return Err(ExecutionError::new_with_source(e, msg)); - }; + let e = ExecutionErrorKind::command_argument_error( + CommandArgumentError::TypeMismatch, + 0, + ); + let msg = "Expected a coin but got an non coin object".to_owned(); + return Err(ExecutionError::new_with_source(e, msg)); + }; let split_coins = amount_args .into_iter() .map(|amount_arg| { @@ -230,13 +230,13 @@ mod checked { Command::MergeCoins(target_arg, coin_args) => { let mut target: ObjectValue = context.borrow_arg_mut(0, target_arg)?; let ObjectContents::Coin(target_coin) = &mut target.contents else { - let e = ExecutionErrorKind::command_argument_error( - CommandArgumentError::TypeMismatch, - 0, - ); - let msg = "Expected a coin but got an non coin object".to_owned(); - return Err(ExecutionError::new_with_source(e, msg)); - }; + let e = ExecutionErrorKind::command_argument_error( + CommandArgumentError::TypeMismatch, + 0, + ); + let msg = "Expected a coin but got an non coin object".to_owned(); + return Err(ExecutionError::new_with_source(e, msg)); + }; let coins: Vec = coin_args .into_iter() .enumerate() @@ -252,11 +252,11 @@ mod checked { return Err(ExecutionError::new_with_source(e, msg)); } let ObjectContents::Coin(Coin { id, balance }) = coin.contents else { - invariant_violation!( - "Target coin was a coin, and we already checked for the same type. \ + invariant_violation!( + "Target coin was a coin, and we already checked for the same type. \ This should be a coin" - ); - }; + ); + }; context.delete_id(*id.object_id())?; target_coin.add(balance)?; } @@ -486,8 +486,8 @@ mod checked { let package_obj = context.new_package(&modules, &dependencies)?; let Some(package) = package_obj.data.try_as_package() else { - invariant_violation!("Newly created package object is not a package"); - }; + invariant_violation!("Newly created package object is not a package"); + }; context.set_linkage(package)?; let res = publish_and_verify_modules(context, runtime_id, &modules) @@ -608,8 +608,8 @@ mod checked { context.upgrade_package(storage_id, ¤t_package, &modules, &dependencies)?; let Some(package) = package_obj.data.try_as_package() else { - invariant_violation!("Newly created package object is not a package"); - }; + invariant_violation!("Newly created package object is not a package"); + }; // Populate loader with all previous types. if !context @@ -627,12 +627,12 @@ mod checked { } let Ok(module) = Identifier::new(module_name.as_str()) else { - continue; - }; + continue; + }; let Ok(name) = Identifier::new(struct_name.as_str()) else { - continue; - }; + continue; + }; let _ = context.load_type(&TypeTag::Struct(Box::new(StructTag { address: (*origin).into(), @@ -669,32 +669,30 @@ mod checked { ) -> Result<(), ExecutionError> { // Make sure this is a known upgrade policy. let Ok(policy) = UpgradePolicy::try_from(policy) else { - return Err(ExecutionError::from_kind( - ExecutionErrorKind::PackageUpgradeError { - upgrade_error: PackageUpgradeError::UnknownUpgradePolicy { policy }, - }, - )); - }; + return Err(ExecutionError::from_kind( + ExecutionErrorKind::PackageUpgradeError { + upgrade_error: PackageUpgradeError::UnknownUpgradePolicy { policy }, + }, + )); + }; - let Ok(current_normalized) = existing_package - .normalize( + let Ok(current_normalized) = existing_package.normalize( context.protocol_config.move_binary_format_version(), context.protocol_config.no_extraneous_module_bytes(), - ) - else { - invariant_violation!("Tried to normalize modules in existing package but failed") - }; + ) else { + invariant_violation!("Tried to normalize modules in existing package but failed") + }; let mut new_normalized = normalize_deserialized_modules(upgrading_modules.into_iter()); for (name, cur_module) in current_normalized { let Some(new_module) = new_normalized.remove(&name) else { - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::PackageUpgradeError { - upgrade_error: PackageUpgradeError::IncompatibleUpgrade, - }, - format!("Existing module {name} not found in next version of package"), - )); - }; + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::PackageUpgradeError { + upgrade_error: PackageUpgradeError::IncompatibleUpgrade, + }, + format!("Existing module {name} not found in next version of package"), + )); + }; check_module_compatibility(&policy, context.protocol_config, &cur_module, &new_module)?; } @@ -826,8 +824,8 @@ mod checked { // objects). if tx_context_kind == TxContextKind::Mutable { let Some((_, ctx_bytes, _)) = result.mutable_reference_outputs.pop() else { - invariant_violation!("Missing TxContext in reference outputs"); - }; + invariant_violation!("Missing TxContext in reference outputs"); + }; let updated_ctx: TxContext = bcs::from_bytes(&ctx_bytes).map_err(|e| { ExecutionError::invariant_violation(format!( "Unable to deserialize TxContext bytes. {e}" @@ -1001,17 +999,22 @@ mod checked { .vm .load_module(module_id, context.session.get_resolver()) .map_err(|e| context.convert_vm_error(e))?; - let Some((index, fdef)) = module.function_defs.iter().enumerate().find(|(_index, fdef)| { - module.identifier_at(module.function_handle_at(fdef.function).name) == function - }) else { - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::FunctionNotFound, - format!( - "Could not resolve function '{}' in module {}", - function, &module_id, - ), - )); - }; + let Some((index, fdef)) = module + .function_defs + .iter() + .enumerate() + .find(|(_index, fdef)| { + module.identifier_at(module.function_handle_at(fdef.function).name) == function + }) + else { + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::FunctionNotFound, + format!( + "Could not resolve function '{}' in module {}", + function, &module_id, + ), + )); + }; // entry on init is now banned, so ban invoking it if !from_init && function == INIT_FN_NAME && context.protocol_config.ban_entry_init() { @@ -1144,8 +1147,8 @@ mod checked { .get_type_tag(return_type) .map_err(|e| context.convert_vm_error(e))?; let TypeTag::Struct(struct_tag) = type_tag else { - invariant_violation!("Struct type make a non struct type tag") - }; + invariant_violation!("Struct type make a non struct type tag") + }; ValueKind::Object { type_: MoveObjectType::from(*struct_tag), has_public_transfer: abilities.has_store(), @@ -1274,8 +1277,8 @@ mod checked { .get_type_tag(type_) .map_err(|e| context.convert_vm_error(e))?; let TypeTag::Struct(struct_tag) = type_tag else { - invariant_violation!("Struct type make a non struct type tag") - }; + invariant_violation!("Struct type make a non struct type tag") + }; let type_ = (*struct_tag).into(); ValueKind::Object { type_, @@ -1334,19 +1337,19 @@ mod checked { // and might need to run validation in addition to the BCS layout Value::Raw(RawValueType::Any, bytes) => { let Some(layout) = primitive_serialization_layout(context, param_ty)? else { - let msg = format!( - "Non-primitive argument at index {}. If it is an object, it must be \ + let msg = format!( + "Non-primitive argument at index {}. If it is an object, it must be \ populated by an object", - idx, - ); - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::command_argument_error( - CommandArgumentError::InvalidUsageOfPureArg, - idx as u16, - ), - msg, - )); - }; + idx, + ); + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::command_argument_error( + CommandArgumentError::InvalidUsageOfPureArg, + idx as u16, + ), + msg, + )); + }; bcs_argument_validate(bytes, idx as u16, layout)?; return Ok(()); } @@ -1394,10 +1397,12 @@ mod checked { Type::Reference(inner) => (false, inner), _ => return Ok(TxContextKind::None), }; - let Type::Struct(idx) = &**inner else { return Ok(TxContextKind::None) }; + let Type::Struct(idx) = &**inner else { + return Ok(TxContextKind::None); + }; let Some(s) = context.session.get_struct_type(*idx) else { - invariant_violation!("Loaded struct not found") - }; + invariant_violation!("Loaded struct not found") + }; let (module_addr, module_name, struct_name) = get_struct_ident(&s); let is_tx_context_type = module_addr == &SUI_FRAMEWORK_ADDRESS && module_name == TX_CONTEXT_MODULE_NAME @@ -1438,8 +1443,8 @@ mod checked { } Type::StructInstantiation(idx, targs) => { let Some(s) = context.session.get_struct_type(*idx) else { - invariant_violation!("Loaded struct not found") - }; + invariant_violation!("Loaded struct not found") + }; let resolved_struct = get_struct_ident(&s); // is option of a string if resolved_struct == RESOLVED_STD_OPTION && targs.len() == 1 { @@ -1451,8 +1456,8 @@ mod checked { } Type::Struct(idx) => { let Some(s) = context.session.get_struct_type(*idx) else { - invariant_violation!("Loaded struct not found") - }; + invariant_violation!("Loaded struct not found") + }; let resolved_struct = get_struct_ident(&s); if resolved_struct == RESOLVED_SUI_ID { Some(PrimitiveArgumentLayout::Address) diff --git a/sui-execution/v0/sui-adapter/src/programmable_transactions/linkage_view.rs b/sui-execution/v0/sui-adapter/src/programmable_transactions/linkage_view.rs index d7055f6e93b49..156d7571942c3 100644 --- a/sui-execution/v0/sui-adapter/src/programmable_transactions/linkage_view.rs +++ b/sui-execution/v0/sui-adapter/src/programmable_transactions/linkage_view.rs @@ -161,15 +161,11 @@ impl<'state> LinkageView<'state> { } in context.type_origin_table() { let Ok(module_name) = Identifier::from_str(module_name) else { - invariant_violation!( - "Module name isn't an identifier: {module_name}" - ); + invariant_violation!("Module name isn't an identifier: {module_name}"); }; let Ok(struct_name) = Identifier::from_str(struct_name) else { - invariant_violation!( - "Struct name isn't an identifier: {struct_name}" - ); + invariant_violation!("Struct name isn't an identifier: {struct_name}"); }; let runtime_id = ModuleId::new(runtime_id, module_name); @@ -274,7 +270,8 @@ impl<'state> LinkageResolver for LinkageView<'state> { let Some(upgrade) = linkage.link_table.get(&runtime_id) else { invariant_violation!( "Missing linkage for {runtime_id} in context {}, runtime_id is {}", - linkage.storage_id, linkage.runtime_id + linkage.storage_id, + linkage.runtime_id ); }; @@ -306,9 +303,7 @@ impl<'state> LinkageResolver for LinkageView<'state> { let storage_id = ObjectID::from(*self.relocate(runtime_id)?.address()); let Some(package) = self.resolver.get_package(&storage_id)? else { - invariant_violation!( - "Missing dependent package in store: {storage_id}", - ) + invariant_violation!("Missing dependent package in store: {storage_id}",) }; for TypeOrigin { diff --git a/sui-execution/v0/sui-adapter/src/temporary_store.rs b/sui-execution/v0/sui-adapter/src/temporary_store.rs index 2a3be224b02f8..beb92dd823f41 100644 --- a/sui-execution/v0/sui-adapter/src/temporary_store.rs +++ b/sui-execution/v0/sui-adapter/src/temporary_store.rs @@ -774,7 +774,7 @@ impl<'backing> TemporaryStore<'backing> { }) } else { // not in input objects, must be a dynamic field - let Ok(Some(obj))= self.store.get_object_by_key(id, expected_version) else { + let Ok(Some(obj)) = self.store.get_object_by_key(id, expected_version) else { invariant_violation!( "Failed looking up dynamic field {id} in SUI conservation checking" ); diff --git a/sui-execution/v0/sui-adapter/src/type_layout_resolver.rs b/sui-execution/v0/sui-adapter/src/type_layout_resolver.rs index 58fcee617348b..cac7249c83539 100644 --- a/sui-execution/v0/sui-adapter/src/type_layout_resolver.rs +++ b/sui-execution/v0/sui-adapter/src/type_layout_resolver.rs @@ -64,7 +64,7 @@ impl<'state, 'vm> LayoutResolver for TypeLayoutResolver<'state, 'vm> { let Ok(MoveTypeLayout::Struct(layout)) = layout else { return Err(SuiError::FailObjectLayout { st: format!("{}", struct_tag), - }) + }); }; Ok(layout) } diff --git a/sui-execution/v0/sui-move-natives/src/crypto/bls12381.rs b/sui-execution/v0/sui-move-natives/src/crypto/bls12381.rs index b6cb1810d7da8..28c1ef5b21864 100644 --- a/sui-execution/v0/sui-move-natives/src/crypto/bls12381.rs +++ b/sui-execution/v0/sui-move-natives/src/crypto/bls12381.rs @@ -80,9 +80,10 @@ pub fn bls12381_min_sig_verify( let cost = context.gas_used(); let Ok(signature) = - ::from_bytes(&signature_bytes_ref) else { - return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); - }; + ::from_bytes(&signature_bytes_ref) + else { + return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); + }; let public_key = match ::from_bytes(&public_key_bytes_ref) { diff --git a/sui-execution/v0/sui-move-natives/src/crypto/ecvrf.rs b/sui-execution/v0/sui-move-natives/src/crypto/ecvrf.rs index ef3b013f55d43..7605d7235391a 100644 --- a/sui-execution/v0/sui-move-natives/src/crypto/ecvrf.rs +++ b/sui-execution/v0/sui-move-natives/src/crypto/ecvrf.rs @@ -82,11 +82,13 @@ pub fn ecvrf_verify( return Ok(NativeResult::err(cost, INVALID_ECVRF_HASH_LENGTH)); }; - let Ok(public_key) = bcs::from_bytes::(public_key_bytes.as_bytes_ref().as_slice()) else { + let Ok(public_key) = + bcs::from_bytes::(public_key_bytes.as_bytes_ref().as_slice()) + else { return Ok(NativeResult::err(cost, INVALID_ECVRF_PUBLIC_KEY)); }; - let Ok(proof) = bcs::from_bytes::(proof_bytes.as_bytes_ref().as_slice()) else { + let Ok(proof) = bcs::from_bytes::(proof_bytes.as_bytes_ref().as_slice()) else { return Ok(NativeResult::err(cost, INVALID_ECVRF_PROOF)); }; diff --git a/sui-execution/v0/sui-move-natives/src/crypto/ed25519.rs b/sui-execution/v0/sui-move-natives/src/crypto/ed25519.rs index 6f3f2bb6556dc..b082deca9adae 100644 --- a/sui-execution/v0/sui-move-natives/src/crypto/ed25519.rs +++ b/sui-execution/v0/sui-move-natives/src/crypto/ed25519.rs @@ -78,7 +78,8 @@ pub fn ed25519_verify( return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; - let Ok(public_key) = ::from_bytes(&public_key_bytes_ref) else { + let Ok(public_key) = ::from_bytes(&public_key_bytes_ref) + else { return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; diff --git a/sui-execution/v0/sui-move-natives/src/dynamic_field.rs b/sui-execution/v0/sui-move-natives/src/dynamic_field.rs index 726c957d5f98f..27cce451302a7 100644 --- a/sui-execution/v0/sui-move-natives/src/dynamic_field.rs +++ b/sui-execution/v0/sui-move-natives/src/dynamic_field.rs @@ -131,16 +131,10 @@ pub fn hash_type_and_key( _ => return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)), }; let Some(k_bytes) = k.simple_serialize(&k_layout) else { - return Ok(NativeResult::err( - cost, - E_BCS_SERIALIZATION_FAILURE, - )) + return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)); }; let Ok(id) = derive_dynamic_field_id(parent, &k_tag, &k_bytes) else { - return Ok(NativeResult::err( - cost, - E_BCS_SERIALIZATION_FAILURE, - )); + return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)); }; Ok(NativeResult::ok(cost, smallvec![Value::address(id.into())])) @@ -512,10 +506,10 @@ fn get_tag_and_layouts( } }; let Some(layout) = context.type_to_type_layout(ty)? else { - return Ok(None) + return Ok(None); }; let Some(annotated_layout) = context.type_to_fully_annotated_layout(ty)? else { - return Ok(None) + return Ok(None); }; Ok(Some((*tag, layout, annotated_layout))) } diff --git a/sui-execution/v0/sui-move-natives/src/test_scenario.rs b/sui-execution/v0/sui-move-natives/src/test_scenario.rs index 2e37d3bb74779..a2d03c9c5e19d 100644 --- a/sui-execution/v0/sui-move-natives/src/test_scenario.rs +++ b/sui-execution/v0/sui-move-natives/src/test_scenario.rs @@ -138,9 +138,9 @@ pub fn end_transaction( inventories .address_inventories .entry(a) - .or_insert_with(BTreeMap::new) + .or_default() .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } Owner::ObjectOwner(_) => (), @@ -148,14 +148,14 @@ pub fn end_transaction( inventories .shared_inventory .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } Owner::Immutable => { inventories .immutable_inventory .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } } diff --git a/sui-execution/v0/sui-move-natives/src/test_utils.rs b/sui-execution/v0/sui-move-natives/src/test_utils.rs index 01e9944004997..50ddbe9c3fc9b 100644 --- a/sui-execution/v0/sui-move-natives/src/test_utils.rs +++ b/sui-execution/v0/sui-move-natives/src/test_utils.rs @@ -33,7 +33,7 @@ pub fn create_one_time_witness( let type_layout = context.type_to_type_layout(&ty)?; let Some(MoveTypeLayout::Struct(struct_layout)) = type_layout else { - return Ok(NativeResult::err(InternalGas::new(1), 0)) + return Ok(NativeResult::err(InternalGas::new(1), 0)); }; if is_otw_struct(&struct_layout, &type_tag) { diff --git a/sui-execution/v0/sui-move-natives/src/types.rs b/sui-execution/v0/sui-move-natives/src/types.rs index 9387004c6ae1e..8f37590d9b96a 100644 --- a/sui-execution/v0/sui-move-natives/src/types.rs +++ b/sui-execution/v0/sui-move-natives/src/types.rs @@ -97,7 +97,7 @@ pub fn is_one_time_witness( let cost = context.gas_used(); let Some(MoveTypeLayout::Struct(struct_layout)) = type_layout else { - return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])) + return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; let is_otw = is_otw_struct(&struct_layout, &type_tag); diff --git a/sui-execution/v0/sui-verifier/src/id_leak_verifier.rs b/sui-execution/v0/sui-verifier/src/id_leak_verifier.rs index 1e3c17402e14c..33da7d536f5fa 100644 --- a/sui-execution/v0/sui-verifier/src/id_leak_verifier.rs +++ b/sui-execution/v0/sui-verifier/src/id_leak_verifier.rs @@ -225,7 +225,7 @@ impl<'a> IDLeakAnalysis<'a> { fn stack_popn(&mut self, n: u64) -> Result<(), PartialVMError> { let Some(n) = NonZeroU64::new(n) else { - return Ok(()) + return Ok(()); }; self.stack.pop_any_n(n).map_err(|e| { PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION) diff --git a/sui-execution/vm-rework/sui-adapter/src/adapter.rs b/sui-execution/vm-rework/sui-adapter/src/adapter.rs index 520d3311765ec..b25c5f5c166d5 100644 --- a/sui-execution/vm-rework/sui-adapter/src/adapter.rs +++ b/sui-execution/vm-rework/sui-adapter/src/adapter.rs @@ -146,12 +146,12 @@ mod checked { let addrs = &mut module.address_identifiers; let Some(address_mut) = addrs.get_mut(self_address_idx.0 as usize) else { - let name = module.identifier_at(self_handle.name); - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::PublishErrorNonZeroAddress, - format!("Publishing module {name} with invalid address index"), - )); - }; + let name = module.identifier_at(self_handle.name); + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::PublishErrorNonZeroAddress, + format!("Publishing module {name} with invalid address index"), + )); + }; if *address_mut != AccountAddress::ZERO { let name = module.identifier_at(self_handle.name); diff --git a/sui-execution/vm-rework/sui-adapter/src/gas_charger.rs b/sui-execution/vm-rework/sui-adapter/src/gas_charger.rs index 329fdfae6ad53..6f1abd8c167a4 100644 --- a/sui-execution/vm-rework/sui-adapter/src/gas_charger.rs +++ b/sui-execution/vm-rework/sui-adapter/src/gas_charger.rs @@ -139,10 +139,10 @@ pub mod checked { .map(|obj_ref| { let obj = temporary_store.objects().get(&obj_ref.0).unwrap(); let Data::Move(move_obj) = &obj.data else { - return Err(ExecutionError::invariant_violation( - "Provided non-gas coin object as input for gas!" - )); - }; + return Err(ExecutionError::invariant_violation( + "Provided non-gas coin object as input for gas!", + )); + }; if !move_obj.type_().is_gas_coin() { return Err(ExecutionError::invariant_violation( "Provided non-gas coin object as input for gas!", diff --git a/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/context.rs b/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/context.rs index 6ad227fbee178..7fb6e349d2e41 100644 --- a/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/context.rs +++ b/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/context.rs @@ -48,7 +48,7 @@ mod checked { use sui_types::execution::ExecutionResults; use sui_types::{ balance::Balance, - base_types::{MoveObjectType, ObjectID, SequenceNumber, SuiAddress, TxContext}, + base_types::{MoveObjectType, ObjectID, SuiAddress, TxContext}, coin::Coin, error::{ExecutionError, ExecutionErrorKind}, event::Event, @@ -161,7 +161,8 @@ mod checked { let Some(Value::Object(ObjectValue { contents: ObjectContents::Coin(coin), .. - })) = &mut gas.inner.value else { + })) = &mut gas.inner.value + else { invariant_violation!("Gas object should be a populated coin") }; @@ -584,13 +585,17 @@ mod checked { let mut additional_writes = BTreeMap::new(); for input in inputs.into_iter().chain(std::iter::once(gas)) { let InputValue { - object_metadata: Some(InputObjectMetadata::InputObject { - // We are only interested in mutable inputs. - is_mutable_input: true, - id, version, owner, - }), + object_metadata: + Some(InputObjectMetadata::InputObject { + // We are only interested in mutable inputs. + is_mutable_input: true, + id, + version, + owner, + }), inner: ResultValue { value, .. }, - } = input else { + } = input + else { continue; }; loaded_runtime_objects.insert( @@ -1092,7 +1097,11 @@ mod checked { new_packages: &[MovePackage], object: &Object, ) -> Result { - let Object { data: Data::Move(object), .. } = object else { + let Object { + data: Data::Move(object), + .. + } = object + else { invariant_violation!("Expected a Move object"); }; @@ -1262,21 +1271,18 @@ mod checked { gas_charger: &mut GasCharger, gas_id: ObjectID, ) -> Result<(), ExecutionError> { - let Some(AdditionalWrite { bytes,.. }) = additional_writes.get_mut(&gas_id) else { + let Some(AdditionalWrite { bytes, .. }) = additional_writes.get_mut(&gas_id) else { invariant_violation!("Gas object cannot be wrapped or destroyed") }; let Ok(mut coin) = Coin::from_bcs_bytes(bytes) else { invariant_violation!("Gas object must be a coin") }; - let Some(new_balance) = coin - .balance - .value() - .checked_add(gas_charger.gas_budget()) else { - return Err(ExecutionError::new_with_source( - ExecutionErrorKind::CoinBalanceOverflow, - "Gas coin too large after returning the max gas budget", - )); - }; + let Some(new_balance) = coin.balance.value().checked_add(gas_charger.gas_budget()) else { + return Err(ExecutionError::new_with_source( + ExecutionErrorKind::CoinBalanceOverflow, + "Gas coin too large after returning the max gas budget", + )); + }; coin.balance = Balance::new(new_balance); *bytes = coin.to_bcs_bytes(); Ok(()) @@ -1317,7 +1323,7 @@ mod checked { MoveObject::new_from_execution( struct_tag.into(), has_public_transfer, - old_obj_ver.unwrap_or_else(SequenceNumber::new), + old_obj_ver.unwrap_or_default(), contents, protocol_config, ) diff --git a/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/execution.rs b/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/execution.rs index b2bb71011af52..197c2bb291bca 100644 --- a/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/execution.rs +++ b/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/execution.rs @@ -623,12 +623,10 @@ mod checked { )); }; - let Ok(current_normalized) = existing_package - .normalize( - context.protocol_config.move_binary_format_version(), - context.protocol_config.no_extraneous_module_bytes(), - ) - else { + let Ok(current_normalized) = existing_package.normalize( + context.protocol_config.move_binary_format_version(), + context.protocol_config.no_extraneous_module_bytes(), + ) else { invariant_violation!("Tried to normalize modules in existing package but failed") }; @@ -924,9 +922,14 @@ mod checked { .get_runtime() .load_module(module_id, &data_store) .map_err(|e| context.convert_vm_error(e))?; - let Some((index, fdef)) = module.function_defs.iter().enumerate().find(|(_index, fdef)| { - module.identifier_at(module.function_handle_at(fdef.function).name) == function - }) else { + let Some((index, fdef)) = module + .function_defs + .iter() + .enumerate() + .find(|(_index, fdef)| { + module.identifier_at(module.function_handle_at(fdef.function).name) == function + }) + else { return Err(ExecutionError::new_with_source( ExecutionErrorKind::FunctionNotFound, format!( @@ -1313,14 +1316,11 @@ mod checked { return Err(command_argument_error( CommandArgumentError::TypeMismatch, idx, - )) + )); + }; + let Some(s) = context.vm.get_runtime().get_struct_type(*sidx) else { + invariant_violation!("sui::transfer::Receiving struct not found in session") }; - let Some(s) = context - .vm - .get_runtime() - .get_struct_type(*sidx) else { - invariant_violation!("sui::transfer::Receiving struct not found in session") - }; let resolved_struct = get_struct_ident(&s); if resolved_struct != RESOLVED_RECEIVING_STRUCT || targs.len() != 1 { @@ -1356,7 +1356,9 @@ mod checked { Type::Reference(inner) => (false, inner), _ => return Ok(TxContextKind::None), }; - let Type::Struct(idx) = &**inner else { return Ok(TxContextKind::None) }; + let Type::Struct(idx) = &**inner else { + return Ok(TxContextKind::None); + }; let Some(s) = context.vm.get_runtime().get_struct_type(*idx) else { invariant_violation!("Loaded struct not found") }; diff --git a/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/linkage_view.rs b/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/linkage_view.rs index fb4dc39d8d01f..748951a33e89f 100644 --- a/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/linkage_view.rs +++ b/sui-execution/vm-rework/sui-adapter/src/programmable_transactions/linkage_view.rs @@ -128,15 +128,11 @@ impl<'state> LinkageView<'state> { } in context.type_origin_table() { let Ok(module_name) = Identifier::from_str(module_name) else { - invariant_violation!( - "Module name isn't an identifier: {module_name}" - ); + invariant_violation!("Module name isn't an identifier: {module_name}"); }; let Ok(struct_name) = Identifier::from_str(struct_name) else { - invariant_violation!( - "Struct name isn't an identifier: {struct_name}" - ); + invariant_violation!("Struct name isn't an identifier: {struct_name}"); }; let runtime_id = ModuleId::new(runtime_id, module_name); @@ -216,7 +212,8 @@ impl<'state> LinkageView<'state> { let Some(upgrade) = linkage.link_table.get(&runtime_id) else { invariant_violation!( "Missing linkage for {runtime_id} in context {}, runtime_id is {}", - linkage.storage_id, linkage.runtime_id + linkage.storage_id, + linkage.runtime_id ); }; @@ -243,9 +240,7 @@ impl<'state> LinkageView<'state> { let storage_id = ObjectID::from(*self.relocate(runtime_id)?.address()); let Some(package) = self.resolver.get_package(&storage_id)? else { - invariant_violation!( - "Missing dependent package in store: {storage_id}", - ) + invariant_violation!("Missing dependent package in store: {storage_id}",) }; for TypeOrigin { diff --git a/sui-execution/vm-rework/sui-adapter/src/temporary_store.rs b/sui-execution/vm-rework/sui-adapter/src/temporary_store.rs index abc3befea642e..4320db711f546 100644 --- a/sui-execution/vm-rework/sui-adapter/src/temporary_store.rs +++ b/sui-execution/vm-rework/sui-adapter/src/temporary_store.rs @@ -699,7 +699,7 @@ impl<'backing> TemporaryStore<'backing> { }) } else { // not in input objects, must be a dynamic field - let Ok(Some(obj))= self.store.get_object_by_key(id, expected_version) else { + let Ok(Some(obj)) = self.store.get_object_by_key(id, expected_version) else { invariant_violation!( "Failed looking up dynamic field {id} in SUI conservation checking" ); diff --git a/sui-execution/vm-rework/sui-adapter/src/type_layout_resolver.rs b/sui-execution/vm-rework/sui-adapter/src/type_layout_resolver.rs index 2fe0d83943a63..0941e095dd00d 100644 --- a/sui-execution/vm-rework/sui-adapter/src/type_layout_resolver.rs +++ b/sui-execution/vm-rework/sui-adapter/src/type_layout_resolver.rs @@ -45,7 +45,8 @@ impl<'state, 'vm> LayoutResolver for TypeLayoutResolver<'state, 'vm> { format: ObjectFormatOptions, ) -> Result { let struct_tag: StructTag = object.type_().clone().into(); - let Ok(ty) = load_type_from_struct(self.vm, &mut self.linkage_view, &[], &struct_tag) else { + let Ok(ty) = load_type_from_struct(self.vm, &mut self.linkage_view, &[], &struct_tag) + else { return Err(SuiError::FailObjectLayout { st: format!("{}", struct_tag), }); @@ -58,7 +59,7 @@ impl<'state, 'vm> LayoutResolver for TypeLayoutResolver<'state, 'vm> { let Ok(MoveTypeLayout::Struct(layout)) = layout else { return Err(SuiError::FailObjectLayout { st: format!("{}", struct_tag), - }) + }); }; Ok(layout) } diff --git a/sui-execution/vm-rework/sui-move-natives/src/crypto/bls12381.rs b/sui-execution/vm-rework/sui-move-natives/src/crypto/bls12381.rs index b6cb1810d7da8..28c1ef5b21864 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/crypto/bls12381.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/crypto/bls12381.rs @@ -80,9 +80,10 @@ pub fn bls12381_min_sig_verify( let cost = context.gas_used(); let Ok(signature) = - ::from_bytes(&signature_bytes_ref) else { - return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); - }; + ::from_bytes(&signature_bytes_ref) + else { + return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); + }; let public_key = match ::from_bytes(&public_key_bytes_ref) { diff --git a/sui-execution/vm-rework/sui-move-natives/src/crypto/ecvrf.rs b/sui-execution/vm-rework/sui-move-natives/src/crypto/ecvrf.rs index ef3b013f55d43..7605d7235391a 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/crypto/ecvrf.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/crypto/ecvrf.rs @@ -82,11 +82,13 @@ pub fn ecvrf_verify( return Ok(NativeResult::err(cost, INVALID_ECVRF_HASH_LENGTH)); }; - let Ok(public_key) = bcs::from_bytes::(public_key_bytes.as_bytes_ref().as_slice()) else { + let Ok(public_key) = + bcs::from_bytes::(public_key_bytes.as_bytes_ref().as_slice()) + else { return Ok(NativeResult::err(cost, INVALID_ECVRF_PUBLIC_KEY)); }; - let Ok(proof) = bcs::from_bytes::(proof_bytes.as_bytes_ref().as_slice()) else { + let Ok(proof) = bcs::from_bytes::(proof_bytes.as_bytes_ref().as_slice()) else { return Ok(NativeResult::err(cost, INVALID_ECVRF_PROOF)); }; diff --git a/sui-execution/vm-rework/sui-move-natives/src/crypto/ed25519.rs b/sui-execution/vm-rework/sui-move-natives/src/crypto/ed25519.rs index 6f3f2bb6556dc..b082deca9adae 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/crypto/ed25519.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/crypto/ed25519.rs @@ -78,7 +78,8 @@ pub fn ed25519_verify( return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; - let Ok(public_key) = ::from_bytes(&public_key_bytes_ref) else { + let Ok(public_key) = ::from_bytes(&public_key_bytes_ref) + else { return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; diff --git a/sui-execution/vm-rework/sui-move-natives/src/dynamic_field.rs b/sui-execution/vm-rework/sui-move-natives/src/dynamic_field.rs index 2304c14792f5f..dab4c1d9ec76a 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/dynamic_field.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/dynamic_field.rs @@ -131,16 +131,10 @@ pub fn hash_type_and_key( _ => return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)), }; let Some(k_bytes) = k.simple_serialize(&k_layout) else { - return Ok(NativeResult::err( - cost, - E_BCS_SERIALIZATION_FAILURE, - )) + return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)); }; let Ok(id) = derive_dynamic_field_id(parent, &k_tag, &k_bytes) else { - return Ok(NativeResult::err( - cost, - E_BCS_SERIALIZATION_FAILURE, - )); + return Ok(NativeResult::err(cost, E_BCS_SERIALIZATION_FAILURE)); }; Ok(NativeResult::ok(cost, smallvec![Value::address(id.into())])) diff --git a/sui-execution/vm-rework/sui-move-natives/src/lib.rs b/sui-execution/vm-rework/sui-move-natives/src/lib.rs index 29d82e0dcc192..93ffc88331b51 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/lib.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/lib.rs @@ -764,10 +764,10 @@ pub(crate) fn get_tag_and_layouts( } }; let Some(layout) = context.type_to_type_layout(ty)? else { - return Ok(None) + return Ok(None); }; let Some(annotated_layout) = context.type_to_fully_annotated_layout(ty)? else { - return Ok(None) + return Ok(None); }; Ok(Some((*tag, layout, annotated_layout))) } diff --git a/sui-execution/vm-rework/sui-move-natives/src/object_runtime/mod.rs b/sui-execution/vm-rework/sui-move-natives/src/object_runtime/mod.rs index d333ac2b4f072..0754124c7a1b8 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/object_runtime/mod.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/object_runtime/mod.rs @@ -380,7 +380,8 @@ impl<'a> ObjectRuntime<'a> { child_layout, child_fully_annotated_layout, child_move_type, - )? else { + )? + else { return Ok(None); }; // NB: It is important that the object only be added to the received set after it has been diff --git a/sui-execution/vm-rework/sui-move-natives/src/object_runtime/object_store.rs b/sui-execution/vm-rework/sui-move-natives/src/object_runtime/object_store.rs index 05375d053487f..0b695a5b5ea32 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/object_runtime/object_store.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/object_runtime/object_store.rs @@ -360,11 +360,12 @@ impl<'a> ChildObjectStore<'a> { child_fully_annotated_layout: &MoveTypeLayout, child_move_type: MoveObjectType, ) -> PartialVMResult, DynamicallyLoadedObjectMetadata)>> { - let Some((obj, obj_meta)) = self - .inner - .receive_object_from_store(parent, child, child_version)? else { - return Ok(None) - }; + let Some((obj, obj_meta)) = + self.inner + .receive_object_from_store(parent, child, child_version)? + else { + return Ok(None); + }; Ok(Some( match deserialize_move_object(&obj, child_ty, child_layout, child_move_type)? { diff --git a/sui-execution/vm-rework/sui-move-natives/src/test_scenario.rs b/sui-execution/vm-rework/sui-move-natives/src/test_scenario.rs index 6340d8ff810a7..9aaaa8d245d29 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/test_scenario.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/test_scenario.rs @@ -133,9 +133,9 @@ pub fn end_transaction( inventories .address_inventories .entry(a) - .or_insert_with(BTreeMap::new) + .or_default() .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } Owner::ObjectOwner(_) => (), @@ -143,14 +143,14 @@ pub fn end_transaction( inventories .shared_inventory .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } Owner::Immutable => { inventories .immutable_inventory .entry(ty) - .or_insert_with(Set::new) + .or_default() .insert(id, ()); } } diff --git a/sui-execution/vm-rework/sui-move-natives/src/test_utils.rs b/sui-execution/vm-rework/sui-move-natives/src/test_utils.rs index 01e9944004997..50ddbe9c3fc9b 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/test_utils.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/test_utils.rs @@ -33,7 +33,7 @@ pub fn create_one_time_witness( let type_layout = context.type_to_type_layout(&ty)?; let Some(MoveTypeLayout::Struct(struct_layout)) = type_layout else { - return Ok(NativeResult::err(InternalGas::new(1), 0)) + return Ok(NativeResult::err(InternalGas::new(1), 0)); }; if is_otw_struct(&struct_layout, &type_tag) { diff --git a/sui-execution/vm-rework/sui-move-natives/src/transfer.rs b/sui-execution/vm-rework/sui-move-natives/src/transfer.rs index c1a53b757ea00..3fd7b593b43b7 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/transfer.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/transfer.rs @@ -67,11 +67,11 @@ pub fn receive_object_internal( .into(); assert!(ty_args.is_empty()); - let Some((tag, layout, annotated_layout)) = get_tag_and_layouts(context, &child_ty)? else { + let Some((tag, layout, annotated_layout)) = get_tag_and_layouts(context, &child_ty)? else { return Ok(NativeResult::err( - context.gas_used(), - E_BCS_SERIALIZATION_FAILURE, - )) + context.gas_used(), + E_BCS_SERIALIZATION_FAILURE, + )); }; let object_runtime: &mut ObjectRuntime = context.extensions_mut().get_mut(); diff --git a/sui-execution/vm-rework/sui-move-natives/src/types.rs b/sui-execution/vm-rework/sui-move-natives/src/types.rs index 9387004c6ae1e..8f37590d9b96a 100644 --- a/sui-execution/vm-rework/sui-move-natives/src/types.rs +++ b/sui-execution/vm-rework/sui-move-natives/src/types.rs @@ -97,7 +97,7 @@ pub fn is_one_time_witness( let cost = context.gas_used(); let Some(MoveTypeLayout::Struct(struct_layout)) = type_layout else { - return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])) + return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])); }; let is_otw = is_otw_struct(&struct_layout, &type_tag); diff --git a/sui-execution/vm-rework/sui-verifier/src/id_leak_verifier.rs b/sui-execution/vm-rework/sui-verifier/src/id_leak_verifier.rs index 5498a5b632112..100e56a1ede4c 100644 --- a/sui-execution/vm-rework/sui-verifier/src/id_leak_verifier.rs +++ b/sui-execution/vm-rework/sui-verifier/src/id_leak_verifier.rs @@ -212,7 +212,7 @@ impl<'a> IDLeakAnalysis<'a> { fn stack_popn(&mut self, n: u64) -> Result<(), PartialVMError> { let Some(n) = NonZeroU64::new(n) else { - return Ok(()) + return Ok(()); }; self.stack.pop_any_n(n).map_err(|e| { PartialVMError::new(StatusCode::VERIFIER_INVARIANT_VIOLATION)