difftreelog
fix(preimage-execution) introduce weight expectation + adjust benchmarks + new tests
in: master
6 files changed
pallets/maintenance/src/benchmarking.rsdiffbeforeafterboth191920use frame_benchmarking::benchmarks;20use frame_benchmarking::benchmarks;21use frame_system::{Call as RuntimeCall, RawOrigin};21use frame_system::{Call as RuntimeCall, RawOrigin};22use frame_support::{ensure, traits::StorePreimage};22use frame_support::{ensure, pallet_prelude::Weight, traits::StorePreimage};23use codec::Encode;23use codec::Encode;24use sp_std::vec;24use sp_std::vec;252540 execute_preimage {40 execute_preimage {41 let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();41 let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();42 let hash = T::Preimages::note(call_hash.into())?;42 let hash = T::Preimages::note(call_hash.into())?;43 }: _(RawOrigin::Root, hash)43 }: _(RawOrigin::Root, hash, None, Weight::from_parts(100000000000, 100000000000))44 verify {44 verify {45 }45 }46}46}pallets/maintenance/src/lib.rsdiffbeforeafterboth104104105 #[pallet::call_index(2)]105 #[pallet::call_index(2)]106 #[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]106 #[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]107 pub fn execute_preimage(_origin: OriginFor<T>, _hash: H256) -> DispatchResult {107 pub fn execute_preimage(108 #[cfg(feature = "preimage")]108 origin: OriginFor<T>,109 {109 hash: H256,110 let origin = _origin;110 preimage_length: Option<u32>,111 weight_bound: Weight,112 ) -> DispatchResultWithPostInfo {111 let hash = _hash;113 use codec::Decode;112114113 ensure_root(origin)?;115 ensure_root(origin)?;114116115 let len = T::Preimages::len(&hash).ok_or(DispatchError::Unavailable)?;117 let data = T::Preimages::fetch(&hash, preimage_length)?;118 weight_bound.set_proof_size(119 weight_bound120 .proof_size()121 .checked_sub(122 data.len()123 .try_into()116 let bounded = T::Preimages::pick::<<T as Config>::RuntimeCall>(hash, len);124 .map_err(|_| DispatchError::Corruption)?,125 )126 .ok_or(DispatchError::Exhausted)?,127 );128117 let (call, _) =129 let call = <T as Config>::RuntimeCall::decode(&mut &data[..])118 T::Preimages::realize(&bounded).map_err(|_| DispatchError::Unavailable)?;130 .map_err(|_| DispatchError::Corruption)?;131132 ensure!(133 call.get_dispatch_info().weight.all_lte(weight_bound),134 DispatchError::Exhausted135 );119136120 let result = match call.dispatch(frame_system::RawOrigin::Root.into()) {137 match call.dispatch(frame_system::RawOrigin::Root.into()) {121 Ok(_) => Ok(()),138 Ok(post_info) => Ok(PostDispatchInfo {139 actual_weight: post_info.actual_weight,140 pays_fee: Pays::No,141 }),122 Err(error_and_info) => Err(error_and_info.error),142 Err(error_and_info) => Err(DispatchErrorWithPostInfo {143 post_info: PostDispatchInfo {144 actual_weight: error_and_info.post_info.actual_weight,145 pays_fee: Pays::No,146 },147 error: error_and_info.error,148 }),123 };149 }124125 result126 }127128 #[cfg(not(feature = "preimage"))]129 {130 Err(DispatchError::Unavailable)131 }132 }150 }133 }151 }134}152}runtime/common/config/pallets/preimage.rsdiffbeforeafterboth20use up_common::constants::*;20use up_common::constants::*;212122parameter_types! {22parameter_types! {23 pub PreimageBaseDeposit: Balance = 1000 * UNIQUE; // deposit(2, 64);23 pub PreimageBaseDeposit: Balance = 1000 * UNIQUE;24 // pub PreimageByteDeposit: Balance = 1 * CENTIUNIQUE; // deposit(0, 1);25}24}262527impl pallet_preimage::Config for Runtime {26impl pallet_preimage::Config for Runtime {runtime/common/runtime_apis.rsdiffbeforeafterboth565 #[cfg(feature = "collator-selection")]565 #[cfg(feature = "collator-selection")]566 list_benchmark!(list, extra, pallet_identity, Identity);566 list_benchmark!(list, extra, pallet_identity, Identity);567568 #[cfg(feature = "preimage")]569 list_benchmark!(list, extra, pallet_preimage, Preimage);570567571 #[cfg(feature = "foreign-assets")]568 #[cfg(feature = "foreign-assets")]572 list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);569 list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);632 #[cfg(feature = "collator-selection")]629 #[cfg(feature = "collator-selection")]633 add_benchmark!(params, batches, pallet_identity, Identity);630 add_benchmark!(params, batches, pallet_identity, Identity);634635 #[cfg(feature = "preimage")]636 add_benchmark!(params, batches, pallet_preimage, Preimage);637631638 #[cfg(feature = "foreign-assets")]632 #[cfg(feature = "foreign-assets")]639 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);633 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);tests/src/maintenance.seqtest.tsdiffbeforeafterboth18import {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';212222async 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;283284 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 }282290283 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 });306312307 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;310317311 // preimage is executed, and an appropriate event is present318 // preimage is executed, and an appropriate event is present316 expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');323 expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');317 });324 });325326 itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {327 const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);328329 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);333334 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [335 preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},336 ])).to.be.rejectedWith(/balances\.InsufficientBalance/);337 });318338319 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 });323344324 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 });350351 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 });329356330 after(async function() {357 after(async function() {331 await usingPlaygrounds(async (helper) => {358 await usingPlaygrounds(async (helper) => {tests/src/util/identitySetter.tsdiffbeforeafterboth172 // identitiesToRemove.push((key as any).toHuman()[0]);172 // identitiesToRemove.push((key as any).toHuman()[0]);173 }173 }174175 console.log(identitiesToAdd[0][1]);176174177 if (identitiesToRemove.length != 0)175 if (identitiesToRemove.length != 0)178 await uploadPreimage(176 await uploadPreimage(