git.delta.rocks / unique-network / refs/commits / 1ae086c66ec9

difftreelog

fix(preimage-execution) introduce weight expectation + adjust benchmarks + new tests

Fahrrader2023-02-22parent: #23641e0.patch.diff
in: master

6 files changed

modifiedpallets/maintenance/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/benchmarking.rs
+++ b/pallets/maintenance/src/benchmarking.rs
@@ -19,7 +19,7 @@
 
 use frame_benchmarking::benchmarks;
 use frame_system::{Call as RuntimeCall, RawOrigin};
-use frame_support::{ensure, traits::StorePreimage};
+use frame_support::{ensure, pallet_prelude::Weight, traits::StorePreimage};
 use codec::Encode;
 use sp_std::vec;
 
@@ -40,7 +40,7 @@
 	execute_preimage {
 		let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();
 		let hash = T::Preimages::note(call_hash.into())?;
-	}: _(RawOrigin::Root, hash)
+	}: _(RawOrigin::Root, hash, None, Weight::from_parts(100000000000, 100000000000))
 	verify {
 	}
 }
modifiedpallets/maintenance/src/lib.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/lib.rs
+++ b/pallets/maintenance/src/lib.rs
@@ -104,30 +104,48 @@
 
 		#[pallet::call_index(2)]
 		#[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]
-		pub fn execute_preimage(_origin: OriginFor<T>, _hash: H256) -> DispatchResult {
-			#[cfg(feature = "preimage")]
-			{
-				let origin = _origin;
-				let hash = _hash;
+		pub fn execute_preimage(
+			origin: OriginFor<T>,
+			hash: H256,
+			preimage_length: Option<u32>,
+			weight_bound: Weight,
+		) -> DispatchResultWithPostInfo {
+			use codec::Decode;
 
-				ensure_root(origin)?;
+			ensure_root(origin)?;
 
-				let len = T::Preimages::len(&hash).ok_or(DispatchError::Unavailable)?;
-				let bounded = T::Preimages::pick::<<T as Config>::RuntimeCall>(hash, len);
-				let (call, _) =
-					T::Preimages::realize(&bounded).map_err(|_| DispatchError::Unavailable)?;
+			let data = T::Preimages::fetch(&hash, preimage_length)?;
+			weight_bound.set_proof_size(
+				weight_bound
+					.proof_size()
+					.checked_sub(
+						data.len()
+							.try_into()
+							.map_err(|_| DispatchError::Corruption)?,
+					)
+					.ok_or(DispatchError::Exhausted)?,
+			);
 
-				let result = match call.dispatch(frame_system::RawOrigin::Root.into()) {
-					Ok(_) => Ok(()),
-					Err(error_and_info) => Err(error_and_info.error),
-				};
+			let call = <T as Config>::RuntimeCall::decode(&mut &data[..])
+				.map_err(|_| DispatchError::Corruption)?;
 
-				result
-			}
+			ensure!(
+				call.get_dispatch_info().weight.all_lte(weight_bound),
+				DispatchError::Exhausted
+			);
 
-			#[cfg(not(feature = "preimage"))]
-			{
-				Err(DispatchError::Unavailable)
+			match call.dispatch(frame_system::RawOrigin::Root.into()) {
+				Ok(post_info) => Ok(PostDispatchInfo {
+					actual_weight: post_info.actual_weight,
+					pays_fee: Pays::No,
+				}),
+				Err(error_and_info) => Err(DispatchErrorWithPostInfo {
+					post_info: PostDispatchInfo {
+						actual_weight: error_and_info.post_info.actual_weight,
+						pays_fee: Pays::No,
+					},
+					error: error_and_info.error,
+				}),
 			}
 		}
 	}
modifiedruntime/common/config/pallets/preimage.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/preimage.rs
+++ b/runtime/common/config/pallets/preimage.rs
@@ -20,8 +20,7 @@
 use up_common::constants::*;
 
 parameter_types! {
-	pub PreimageBaseDeposit: Balance = 1000 * UNIQUE; // deposit(2, 64);
-	// pub PreimageByteDeposit: Balance = 1 * CENTIUNIQUE; // deposit(0, 1);
+	pub PreimageBaseDeposit: Balance = 1000 * UNIQUE;
 }
 
 impl pallet_preimage::Config for Runtime {
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -565,9 +565,6 @@
                     #[cfg(feature = "collator-selection")]
                     list_benchmark!(list, extra, pallet_identity, Identity);
 
-                    #[cfg(feature = "preimage")]
-                    list_benchmark!(list, extra, pallet_preimage, Preimage);
-
                     #[cfg(feature = "foreign-assets")]
                     list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);
 
@@ -631,9 +628,6 @@
 
                     #[cfg(feature = "collator-selection")]
                     add_benchmark!(params, batches, pallet_identity, Identity);
-
-                    #[cfg(feature = "preimage")]
-                    add_benchmark!(params, batches, pallet_preimage, Preimage);
 
                     #[cfg(feature = "foreign-assets")]
                     add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);
modifiedtests/src/maintenance.seqtest.tsdiffbeforeafterboth
18import {ApiPromise} from '@polkadot/api';18import {ApiPromise} from '@polkadot/api';
19import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';19import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
20import {itEth} from './eth/util';20import {itEth} from './eth/util';
21import {UniqueHelper} from './util/playgrounds/unique';
2122
22async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {23async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
23 return (await api.query.maintenance.enabled()).toJSON() as boolean;24 return (await api.query.maintenance.enabled()).toJSON() as boolean;
280 describe('Preimage Execution', () => {281 describe('Preimage Execution', () => {
281 let preimageHash: string;282 let preimageHash: string;
283
284 async function notePreimage(helper: UniqueHelper, preimage: any): Promise<string> {
285 const result = await helper.preimage.notePreimage(bob, preimage);
286 const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');
287 const preimageHash = events[0].event.data[0].toHuman();
288 return preimageHash;
289 }
282290
283 before(async function() {291 before(async function() {
284 await usingPlaygrounds(async (helper) => {292 await usingPlaygrounds(async (helper) => {
298 },306 },
299 ]);307 ]);
300 const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();308 const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();
301 const result = await helper.preimage.notePreimage(bob, preimage);309 preimageHash = await notePreimage(helper, preimage);
302 const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');
303 preimageHash = events[0].event.data[0].toHuman();
304 });310 });
305 });311 });
306312
307 itSub('Successfully executes call in a preimage', async ({helper}) => {313 itSub('Successfully executes call in a preimage', async ({helper}) => {
308 const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [preimageHash]))314 const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
315 preimageHash, null, {refTime: 10000000000, proofSize: 10000000000},
309 .to.be.fulfilled;316 ])).to.be.fulfilled;
310317
311 // preimage is executed, and an appropriate event is present318 // preimage is executed, and an appropriate event is present
316 expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');323 expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');
317 });324 });
325
326 itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {
327 const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);
328
329 const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [
330 {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,
331 ]).method.toHex();
332 const preimageHash = await notePreimage(helper, preimage);
333
334 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
335 preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},
336 ])).to.be.rejectedWith(/balances\.InsufficientBalance/);
337 });
318338
319 itSub('Does not allow preimage execution with non-root', async ({helper}) => {339 itSub('Does not allow preimage execution with non-root', async ({helper}) => {
320 await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [preimageHash]))340 await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [
341 preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},
321 .to.be.rejectedWith(/BadOrigin/);342 ])).to.be.rejectedWith(/BadOrigin/);
322 });343 });
323344
324 itSub('Does not allow execution of non-existent preimages', async ({helper}) => {345 itSub('Does not allow execution of non-existent preimages', async ({helper}) => {
325 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [346 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
326 '0x1010101010101010101010101010101010101010101010101010101010101010',347 '0x1010101010101010101010101010101010101010101010101010101010101010', null, {refTime: 100000000000, proofSize: 100000000000},
327 ])).to.be.rejectedWith(/Unavailable/);348 ])).to.be.rejectedWith(/Unavailable/);
328 });349 });
350
351 itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {
352 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
353 preimageHash, null, {refTime: 1000, proofSize: 1000},
354 ])).to.be.rejectedWith(/Exhausted/);
355 });
329356
330 after(async function() {357 after(async function() {
331 await usingPlaygrounds(async (helper) => {358 await usingPlaygrounds(async (helper) => {
modifiedtests/src/util/identitySetter.tsdiffbeforeafterboth
--- a/tests/src/util/identitySetter.ts
+++ b/tests/src/util/identitySetter.ts
@@ -172,8 +172,6 @@
         // identitiesToRemove.push((key as any).toHuman()[0]);
       }
 
-      console.log(identitiesToAdd[0][1]);
-
       if (identitiesToRemove.length != 0)
         await uploadPreimage(
           helper,