Skip to content

Commit 247c266

Browse files
authored
Merge pull request #3541 from autonomys/xdm_benchmarks
Benchmarks for XDM extension
2 parents 6aaee34 + 0af6e2b commit 247c266

File tree

26 files changed

+1336
-27
lines changed

26 files changed

+1336
-27
lines changed

crates/subspace-runtime/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,5 +155,6 @@ runtime-benchmarks = [
155155
"pallet-transporter/runtime-benchmarks",
156156
"pallet-utility/runtime-benchmarks",
157157
"sp-consensus-subspace/runtime-benchmarks",
158+
"sp-messenger/runtime-benchmarks",
158159
"sp-runtime/runtime-benchmarks",
159160
]

crates/subspace-runtime/src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,9 @@ impl pallet_messenger::Config for Runtime {
754754
type OnXDMRewards = OnXDMRewards;
755755
type MmrHash = mmr::Hash;
756756
type MmrProofVerifier = MmrProofVerifier;
757+
#[cfg(feature = "runtime-benchmarks")]
758+
type StorageKeys = sp_messenger::BenchmarkStorageKeys;
759+
#[cfg(not(feature = "runtime-benchmarks"))]
757760
type StorageKeys = StorageKeys;
758761
type DomainOwner = Domains;
759762
type HoldIdentifier = HoldIdentifierWrapper;
@@ -763,6 +766,7 @@ impl pallet_messenger::Config for Runtime {
763766
type MaxOutgoingMessages = MaxOutgoingMessages;
764767
type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
765768
type NoteChainTransfer = Transporter;
769+
type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<Runtime>;
766770
}
767771

768772
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
@@ -1259,6 +1263,7 @@ mod benches {
12591263
[pallet_messenger, Messenger]
12601264
[pallet_transporter, Transporter]
12611265
[pallet_subspace_extension, SubspaceExtensionBench::<Runtime>]
1266+
[pallet_messenger_from_domains_extension, MessengerFromDomainsExtensionBench::<Runtime>]
12621267
);
12631268
}
12641269

@@ -1781,6 +1786,7 @@ impl_runtime_apis! {
17811786
use frame_system_benchmarking::Pallet as SystemBench;
17821787
use baseline::Pallet as BaselineBench;
17831788
use pallet_subspace::extensions::benchmarking::Pallet as SubspaceExtensionBench;
1789+
use pallet_messenger::extensions::benchmarking_from_domains::Pallet as MessengerFromDomainsExtensionBench;
17841790

17851791
let mut list = Vec::<BenchmarkList>::new();
17861792
list_benchmarks!(list, extra);
@@ -1799,6 +1805,7 @@ impl_runtime_apis! {
17991805
use frame_system_benchmarking::Pallet as SystemBench;
18001806
use baseline::Pallet as BaselineBench;
18011807
use pallet_subspace::extensions::benchmarking::Pallet as SubspaceExtensionBench;
1808+
use pallet_messenger::extensions::benchmarking_from_domains::Pallet as MessengerFromDomainsExtensionBench;
18021809

18031810
use frame_support::traits::WhitelistedStorageKeys;
18041811
let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();

domains/client/block-preprocessor/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,11 @@ where
501501
let bundle_estimated_weight = bundle.estimated_weight();
502502
let mut maybe_invalid_bundle_type = None;
503503

504+
// Note: It is okay to use stateless here since all the bundle checks currently do not
505+
// require state. But of any checks in the future requires a state read that was part of the
506+
// genesis ex: `SelfChainId`, stateless runtime will panic.
507+
// So ideal to set the genesis storage as fraud proof already have access to that and would be
508+
// no different in terms of verification on both the sides
504509
let stateless_runtime_api = self.stateless_runtime_api(parent_domain_hash)?;
505510
let consensus_runtime_api = self.consensus_client.runtime_api();
506511

domains/pallets/messenger/src/extensions.rs

Lines changed: 141 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,36 @@
11
//! Extensions for unsigned general extrinsics
22
3+
#[cfg(feature = "runtime-benchmarks")]
4+
pub mod benchmarking_from_consensus;
5+
#[cfg(feature = "runtime-benchmarks")]
6+
pub mod benchmarking_from_domains;
7+
pub mod weights;
8+
mod weights_from_consensus;
9+
mod weights_from_domains;
10+
11+
use crate::extensions::weights::{FromConsensusWeightInfo, FromDomainWeightInfo};
312
use crate::pallet::Call as MessengerCall;
413
use crate::{
5-
Call, Config, Origin, Pallet as Messenger, ValidatedRelayMessage, XDM_TRANSACTION_LONGEVITY,
14+
Call, Config, ExtensionWeightInfo, Origin, Pallet as Messenger, ValidatedRelayMessage,
15+
XDM_TRANSACTION_LONGEVITY,
616
};
717
use core::cmp::Ordering;
8-
use frame_support::pallet_prelude::{PhantomData, TypeInfo};
18+
use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight};
919
use frame_support::RuntimeDebugNoBound;
1020
use frame_system::pallet_prelude::RuntimeCallFor;
1121
use parity_scale_codec::{Decode, Encode};
1222
use scale_info::prelude::fmt;
13-
use sp_messenger::messages::{Message, Nonce};
23+
use sp_messenger::messages::{Message, Nonce, Proof};
1424
use sp_messenger::MAX_FUTURE_ALLOWED_NONCES;
15-
use sp_runtime::impl_tx_ext_default;
1625
use sp_runtime::traits::{
1726
AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Implication,
18-
TransactionExtension, ValidateResult,
27+
PostDispatchInfoOf, TransactionExtension, ValidateResult,
1928
};
2029
use sp_runtime::transaction_validity::{
2130
InvalidTransaction, TransactionSource, TransactionValidityError, ValidTransaction,
2231
ValidTransactionBuilder,
2332
};
33+
use sp_runtime::DispatchResult;
2434
use sp_subspace_mmr::MmrProofVerifier;
2535

2636
/// Trait to convert Runtime call to possible Messenger call.
@@ -40,6 +50,12 @@ pub enum Val<T: Config + fmt::Debug> {
4050
ValidatedRelayMessage(ValidatedRelayMessage<T>),
4151
}
4252

53+
/// Data passed from prepare to post_dispatch.
54+
#[derive(RuntimeDebugNoBound)]
55+
pub enum Pre {
56+
Refund(Weight),
57+
}
58+
4359
/// Extensions for pallet-messenger unsigned extrinsics.
4460
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
4561
pub struct MessengerExtension<Runtime>(PhantomData<Runtime>);
@@ -182,7 +198,7 @@ where
182198
fn do_prepare(
183199
call: &MessengerCall<Runtime>,
184200
val: ValidatedRelayMessage<Runtime>,
185-
) -> Result<(), TransactionValidityError> {
201+
) -> Result<Pre, TransactionValidityError> {
186202
let ValidatedRelayMessage {
187203
message,
188204
should_init_channel,
@@ -194,15 +210,94 @@ where
194210
return Err(InvalidTransaction::Future.into());
195211
}
196212

197-
match call {
198-
Call::relay_message { .. } => {
199-
Messenger::<Runtime>::pre_dispatch_relay_message(message, should_init_channel)
213+
let pre = match call {
214+
Call::relay_message { msg } => {
215+
Messenger::<Runtime>::pre_dispatch_relay_message(message, should_init_channel)?;
216+
if should_init_channel {
217+
// if this is a channel init,
218+
// there is no further refund of weight
219+
Pre::Refund(Weight::zero())
220+
} else {
221+
match msg.proof {
222+
Proof::Consensus { .. } => Pre::Refund(Self::refund_weight_for_consensus()),
223+
Proof::Domain { .. } => Pre::Refund(Self::refund_weight_for_domains()),
224+
}
225+
}
200226
}
201227
Call::relay_message_response { .. } => {
202-
Messenger::<Runtime>::pre_dispatch_relay_message_response(message)
228+
Messenger::<Runtime>::pre_dispatch_relay_message_response(message)?;
229+
// no refund for relay response message.
230+
Pre::Refund(Weight::zero())
203231
}
204-
_ => Err(InvalidTransaction::Call.into()),
205-
}
232+
_ => return Err(InvalidTransaction::Call.into()),
233+
};
234+
235+
Ok(pre)
236+
}
237+
238+
fn do_calculate_weight(call: &RuntimeCallFor<Runtime>) -> Weight
239+
where
240+
RuntimeCallFor<Runtime>: MaybeMessengerCall<Runtime>,
241+
Runtime: Config,
242+
{
243+
let messenger_call = match call.maybe_messenger_call() {
244+
Some(messenger_call) => messenger_call,
245+
None => return Weight::zero(),
246+
};
247+
248+
let (dst_chain_id, verification_weight) = match messenger_call {
249+
Call::relay_message { msg } => (
250+
msg.dst_chain_id,
251+
match msg.proof {
252+
Proof::Consensus { .. } => {
253+
Runtime::ExtensionWeightInfo::from_consensus_relay_message().max(
254+
Runtime::ExtensionWeightInfo::from_consensus_relay_message_channel_open(
255+
),
256+
)
257+
}
258+
Proof::Domain { .. } => {
259+
Runtime::ExtensionWeightInfo::from_domains_relay_message_channel_open()
260+
.max(Runtime::ExtensionWeightInfo::from_domains_relay_message())
261+
}
262+
},
263+
),
264+
Call::relay_message_response { msg } => (
265+
msg.dst_chain_id,
266+
match msg.proof {
267+
Proof::Consensus { .. } => {
268+
Runtime::ExtensionWeightInfo::from_consensus_relay_message_response()
269+
}
270+
Proof::Domain { .. } => {
271+
Runtime::ExtensionWeightInfo::from_domains_relay_message_response()
272+
}
273+
},
274+
),
275+
_ => return Weight::zero(),
276+
};
277+
278+
let mmr_proof_weight = if dst_chain_id.is_consensus_chain() {
279+
Runtime::ExtensionWeightInfo::mmr_proof_verification_on_consensus()
280+
} else {
281+
Runtime::ExtensionWeightInfo::mmr_proof_verification_on_domain()
282+
};
283+
284+
mmr_proof_weight.saturating_add(verification_weight)
285+
}
286+
287+
fn refund_weight_for_consensus() -> Weight {
288+
let min = Runtime::ExtensionWeightInfo::from_consensus_relay_message_channel_open()
289+
.min(Runtime::ExtensionWeightInfo::from_consensus_relay_message());
290+
let max = Runtime::ExtensionWeightInfo::from_consensus_relay_message_channel_open()
291+
.max(Runtime::ExtensionWeightInfo::from_consensus_relay_message());
292+
max.saturating_sub(min)
293+
}
294+
295+
fn refund_weight_for_domains() -> Weight {
296+
let min = Runtime::ExtensionWeightInfo::from_domains_relay_message_channel_open()
297+
.min(Runtime::ExtensionWeightInfo::from_domains_relay_message());
298+
let max = Runtime::ExtensionWeightInfo::from_domains_relay_message_channel_open()
299+
.max(Runtime::ExtensionWeightInfo::from_domains_relay_message());
300+
max.saturating_sub(min)
206301
}
207302
}
208303

@@ -216,7 +311,11 @@ where
216311
const IDENTIFIER: &'static str = "MessengerExtension";
217312
type Implicit = ();
218313
type Val = Val<Runtime>;
219-
type Pre = ();
314+
type Pre = Pre;
315+
316+
fn weight(&self, call: &RuntimeCallFor<Runtime>) -> Weight {
317+
Self::do_calculate_weight(call)
318+
}
220319

221320
fn validate(
222321
&self,
@@ -259,13 +358,22 @@ where
259358
(Some(messenger_call), Val::ValidatedRelayMessage(validated_relay_message)) => {
260359
Self::do_prepare(messenger_call, validated_relay_message)
261360
}
262-
// return Ok for the rest of the call types
263-
(_, _) => Ok(()),
361+
// return Ok for the rest of the call types and nothing to refund here as
362+
// non XDM calls will have zero weight from this extension.
363+
(_, _) => Ok(Pre::Refund(Weight::zero())),
264364
}
265365
}
266366

267-
// TODO: need benchmarking for this extension.
268-
impl_tx_ext_default!(RuntimeCallFor<Runtime>; weight);
367+
fn post_dispatch_details(
368+
pre: Self::Pre,
369+
_info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
370+
_post_info: &PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
371+
_len: usize,
372+
_result: &DispatchResult,
373+
) -> Result<Weight, TransactionValidityError> {
374+
let Pre::Refund(weight) = pre;
375+
Ok(weight)
376+
}
269377
}
270378

271379
/// Extensions for pallet-messenger unsigned extrinsics with trusted MMR verification.
@@ -349,10 +457,11 @@ where
349457
const IDENTIFIER: &'static str = "MessengerTrustedMmrExtension";
350458
type Implicit = ();
351459
type Val = Val<Runtime>;
352-
type Pre = ();
460+
type Pre = Pre;
353461

354-
// TODO: need benchmarking for this extension.
355-
impl_tx_ext_default!(RuntimeCallFor<Runtime>; weight);
462+
fn weight(&self, call: &RuntimeCallFor<Runtime>) -> Weight {
463+
MessengerExtension::<Runtime>::do_calculate_weight(call)
464+
}
356465

357466
fn validate(
358467
&self,
@@ -396,7 +505,18 @@ where
396505
MessengerExtension::<Runtime>::do_prepare(messenger_call, validated_relay_message)
397506
}
398507
// return Ok for the rest of the call types
399-
(_, _) => Ok(()),
508+
(_, _) => Ok(Pre::Refund(Weight::zero())),
400509
}
401510
}
511+
512+
fn post_dispatch_details(
513+
pre: Self::Pre,
514+
_info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
515+
_post_info: &PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
516+
_len: usize,
517+
_result: &DispatchResult,
518+
) -> Result<Weight, TransactionValidityError> {
519+
let Pre::Refund(weight) = pre;
520+
Ok(weight)
521+
}
402522
}

0 commit comments

Comments
 (0)