Skip to content

Commit

Permalink
feat: benchmarks (#585)
Browse files Browse the repository at this point in the history
## fixes
[KILTprotocol/ticket#2551](KILTprotocol/ticket#2551)

This pull request introduces benchmark logic for the DIP templates. To
calculate default weights, a dummy implementation of the pallets in the
Peregrine runtime is defined. After the PR is approved, I will remove
the dummy implementation.


## Leftover tasks

- [x] Make the provider and consumer binaries compiles for benchmarking.
Currently the `VersionedSiblingParachainDipStateProof` type does not
implement the `WorstCase` trait, which is a blocker to use it in
benchmarks
- [x] Adjust the `DipProofVerifier` logic to allow any calls to be
dispatched when being benchmarked
- [x] Make sure everything compiles
- [x] Make sure benchmarks can actually be run for both provider and
consumer runtimes

---------

Co-authored-by: Antonio Antonino <antonio@kilt.io>
  • Loading branch information
Ad96el and ntn-x2 authored Dec 6, 2023
1 parent 55e45f8 commit 5afb750
Show file tree
Hide file tree
Showing 71 changed files with 5,478 additions and 566 deletions.
920 changes: 486 additions & 434 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions crates/kilt-dip-support/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ log.workspace = true

# Internal dependencies
did.workspace = true
kilt-support = {workspace = true, optional = true}
pallet-did-lookup.workspace = true
pallet-dip-consumer.workspace = true
pallet-dip-provider.workspace = true
Expand Down Expand Up @@ -57,6 +58,7 @@ std = [
"hash-db/std",
"log/std",
"did/std",
"kilt-support?/std",
"pallet-did-lookup/std",
"pallet-dip-consumer/std",
"pallet-dip-provider/std",
Expand All @@ -80,6 +82,8 @@ std = [
"parachain-info/std",
]
runtime-benchmarks = [
"kilt-support/runtime-benchmarks",
"pallet-dip-consumer/runtime-benchmarks",
"pallet-dip-provider/runtime-benchmarks",
"rococo-runtime/runtime-benchmarks"
]
94 changes: 93 additions & 1 deletion crates/kilt-dip-support/src/did.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use did::{
did_details::{DidPublicKey, DidPublicKeyDetails, DidVerificationKey},
DidSignature, DidVerificationKeyRelationship,
};
use frame_support::ensure;
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_core::RuntimeDebug;
Expand All @@ -44,6 +43,20 @@ pub struct TimeBoundDidSignature<BlockNumber> {
pub block_number: BlockNumber,
}

#[cfg(feature = "runtime-benchmarks")]
impl<BlockNumber, Context> kilt_support::traits::GetWorstCase<Context> for TimeBoundDidSignature<BlockNumber>
where
DidSignature: kilt_support::traits::GetWorstCase<Context>,
BlockNumber: Default,
{
fn worst_case(context: Context) -> Self {
Self {
signature: DidSignature::worst_case(context),
block_number: BlockNumber::default(),
}
}
}

pub enum RevealedDidKeysSignatureAndCallVerifierError {
SignatureNotFresh,
SignatureUnverifiable,
Expand Down Expand Up @@ -121,6 +134,7 @@ impl<
CallVerifier:
DipCallOriginFilter<Call, OriginInfo = (DidVerificationKey<RemoteAccountId>, DidVerificationKeyRelationship)>,
{
#[cfg(not(feature = "runtime-benchmarks"))]
#[allow(clippy::result_unit_err)]
pub(crate) fn verify_did_signature_for_call(
call: &Call,
Expand All @@ -131,6 +145,8 @@ impl<
(DidVerificationKey<RemoteAccountId>, DidVerificationKeyRelationship),
RevealedDidKeysSignatureAndCallVerifierError,
> {
use frame_support::ensure;

let block_number = ContextProvider::block_number();
let is_signature_fresh = if let Some(blocks_ago_from_now) =
block_number.checked_sub(&merkle_revealed_did_signature.did_signature.block_number)
Expand Down Expand Up @@ -183,4 +199,80 @@ impl<
.map_err(|_| RevealedDidKeysSignatureAndCallVerifierError::OriginCheckFailed)?;
Ok((key.clone(), *relationship))
}

#[cfg(feature = "runtime-benchmarks")]
#[allow(clippy::result_unit_err)]
pub(crate) fn verify_did_signature_for_call(
call: &Call,
submitter: &Submitter,
local_details: &mut Option<DidLocalDetails>,
merkle_revealed_did_signature: RevealedDidKeysAndSignature<MerkleProofEntries, ContextProvider::BlockNumber>,
) -> Result<
(DidVerificationKey<RemoteAccountId>, DidVerificationKeyRelationship),
RevealedDidKeysSignatureAndCallVerifierError,
> {
use sp_core::ed25519;

let block_number = ContextProvider::block_number();
// Computed but ignored
if let Some(blocks_ago_from_now) =
block_number.checked_sub(&merkle_revealed_did_signature.did_signature.block_number)
{
// False if the signature is too old.
blocks_ago_from_now <= ContextProvider::SIGNATURE_VALIDITY.into()
} else {
// Signature generated at a future time, not possible to verify.
false
};
let encoded_payload = (
call,
&local_details,
submitter,
&merkle_revealed_did_signature.did_signature.block_number,
ContextProvider::genesis_hash(),
ContextProvider::signed_extra(),
)
.encode();
// Only consider verification keys from the set of revealed keys.
let proof_verification_keys: Vec<(DidVerificationKey<RemoteAccountId>, DidVerificationKeyRelationship)> =
merkle_revealed_did_signature
.merkle_leaves
.borrow()
.iter()
.filter_map(
|RevealedDidKey {
relationship,
details: DidPublicKeyDetails { key, .. },
..
}| {
let DidPublicKey::PublicVerificationKey(key) = key else {
return None;
};
if let Ok(vr) = DidVerificationKeyRelationship::try_from(*relationship) {
Some(Ok((key.clone(), vr)))
} else {
None
}
},
)
.collect::<Result<_, _>>()?;
let valid_signing_key = proof_verification_keys.iter().find(|(verification_key, _)| {
verification_key
.verify_signature(&encoded_payload, &merkle_revealed_did_signature.did_signature.signature)
.is_ok()
});
let default = (
DidVerificationKey::Ed25519(ed25519::Public::from_raw([0u8; 32])),
DidVerificationKeyRelationship::Authentication,
);
let (key, relationship) = valid_signing_key.unwrap_or(&default);
if let Some(details) = local_details {
details.bump();
} else {
*local_details = Some(DidLocalDetails::default());
};
// Ignore the result of this call
let _ = CallVerifier::check_call_origin_info(call, &(key.clone(), *relationship));
Ok((key.clone(), *relationship))
}
}
11 changes: 5 additions & 6 deletions crates/kilt-dip-support/src/export/child.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use parity_scale_codec::{Codec, Decode, Encode, HasCompact};
use scale_info::TypeInfo;
use sp_core::{RuntimeDebug, U256};
use sp_runtime::traits::{AtLeast32BitUnsigned, Get, Hash, MaybeDisplay, Member, SimpleBitOps};
use sp_std::{marker::PhantomData, vec::Vec};
use sp_std::marker::PhantomData;

use crate::{
did::RevealedDidKeysSignatureAndCallVerifierError,
Expand All @@ -38,7 +38,7 @@ use crate::{
RelayChainStorageInfo,
},
utils::OutputOf,
FrameSystemDidSignatureContext, ProviderParachainStateInfoViaProviderPallet,
BoundedBlindedValue, FrameSystemDidSignatureContext, ProviderParachainStateInfoViaProviderPallet,
};

#[derive(Encode, Decode, PartialEq, Eq, RuntimeDebug, TypeInfo, Clone)]
Expand Down Expand Up @@ -209,7 +209,7 @@ impl<
type Proof = VersionedChildParachainDipStateProof<
<RelayChainInfo as RelayChainStorageInfo>::BlockNumber,
<RelayChainInfo as RelayChainStorageInfo>::Hasher,
Vec<Vec<u8>>,
BoundedBlindedValue<u8>,
RevealedDidMerkleProofLeaf<
KeyIdOf<KiltRuntime>,
KiltRuntime::AccountId,
Expand Down Expand Up @@ -376,7 +376,7 @@ impl<
type Proof = VersionedChildParachainDipStateProof<
<RelayChainInfo as RelayChainStorageInfo>::BlockNumber,
<RelayChainInfo as RelayChainStorageInfo>::Hasher,
Vec<Vec<u8>>,
BoundedBlindedValue<u8>,
RevealedDidMerkleProofLeaf<
ProviderDidKeyId,
ProviderAccountId,
Expand Down Expand Up @@ -592,7 +592,7 @@ mod v0 {
type Proof = ChildParachainDipStateProof<
<RelayChainInfo as RelayChainStorageInfo>::BlockNumber,
<RelayChainInfo as RelayChainStorageInfo>::Hasher,
Vec<Vec<u8>>,
BoundedBlindedValue<u8>,
RevealedDidMerkleProofLeaf<
ProviderDidKeyId,
ProviderAccountId,
Expand Down Expand Up @@ -629,7 +629,6 @@ mod v0 {
// 1.2 If so, extract the state root from the header
let state_root_at_height = proof.relay_header.state_root;

// FIXME: Compilation error
// 2. Verify relay chain proof
let provider_parachain_header =
ParachainHeadProofVerifier::<RelayChainInfo>::verify_proof_for_parachain_with_root(
Expand Down
36 changes: 33 additions & 3 deletions crates/kilt-dip-support/src/export/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,49 @@ pub mod v0 {
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_core::RuntimeDebug;
use sp_std::vec::Vec;

use crate::{did::TimeBoundDidSignature, merkle::DidMerkleProof};
use crate::{did::TimeBoundDidSignature, merkle::DidMerkleProof, BoundedBlindedValue};

#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, RuntimeDebug, TypeInfo, Clone)]
pub struct ParachainRootStateProof<RelayBlockHeight> {
pub(crate) relay_block_height: RelayBlockHeight,
pub(crate) proof: Vec<Vec<u8>>,
pub(crate) proof: BoundedBlindedValue<u8>,
}

#[cfg(feature = "runtime-benchmarks")]
impl<RelayBlockHeight, Context> kilt_support::traits::GetWorstCase<Context>
for ParachainRootStateProof<RelayBlockHeight>
where
RelayBlockHeight: Default,
{
fn worst_case(context: Context) -> Self {
Self {
relay_block_height: RelayBlockHeight::default(),
proof: BoundedBlindedValue::worst_case(context),
}
}
}

#[derive(Encode, Decode, PartialEq, Eq, RuntimeDebug, TypeInfo, Clone)]
pub struct DipMerkleProofAndDidSignature<BlindedValues, Leaf, BlockNumber> {
pub(crate) leaves: DidMerkleProof<BlindedValues, Leaf>,
pub(crate) signature: TimeBoundDidSignature<BlockNumber>,
}

#[cfg(feature = "runtime-benchmarks")]
impl<BlindedValues, Leaf, BlockNumber, Context> kilt_support::traits::GetWorstCase<Context>
for DipMerkleProofAndDidSignature<BlindedValues, Leaf, BlockNumber>
where
BlindedValues: kilt_support::traits::GetWorstCase<Context>,
Leaf: Default + Clone,
BlockNumber: Default,
Context: Clone,
{
fn worst_case(context: Context) -> Self {
Self {
leaves: DidMerkleProof::worst_case(context.clone()),
signature: TimeBoundDidSignature::worst_case(context),
}
}
}
}
61 changes: 53 additions & 8 deletions crates/kilt-dip-support/src/export/sibling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ use parity_scale_codec::{Decode, Encode, HasCompact};
use scale_info::TypeInfo;
use sp_core::{RuntimeDebug, U256};
use sp_runtime::traits::Get;
use sp_std::{marker::PhantomData, vec::Vec};
use sp_std::marker::PhantomData;

use crate::{
did::RevealedDidKeysSignatureAndCallVerifierError,
merkle::{DidMerkleProofVerifierError, RevealedDidMerkleProofLeaf, RevealedDidMerkleProofLeaves},
state_proofs::{parachain::DipIdentityCommitmentProofVerifierError, relay_chain::ParachainHeadProofVerifierError},
traits::{self, Bump, DidSignatureVerifierContext, DipCallOriginFilter},
utils::OutputOf,
FrameSystemDidSignatureContext, ProviderParachainStateInfoViaProviderPallet,
BoundedBlindedValue, FrameSystemDidSignatureContext, ProviderParachainStateInfoViaProviderPallet,
};

#[derive(Encode, Decode, PartialEq, Eq, RuntimeDebug, TypeInfo, Clone)]
Expand All @@ -56,6 +56,26 @@ pub enum VersionedSiblingParachainDipStateProof<
),
}

#[cfg(feature = "runtime-benchmarks")]
impl<RelayBlockHeight, DipMerkleProofBlindedValues, DipMerkleProofRevealedLeaf, LocalBlockNumber, Context>
kilt_support::traits::GetWorstCase<Context>
for VersionedSiblingParachainDipStateProof<
RelayBlockHeight,
DipMerkleProofBlindedValues,
DipMerkleProofRevealedLeaf,
LocalBlockNumber,
> where
RelayBlockHeight: Default,
DipMerkleProofBlindedValues: kilt_support::traits::GetWorstCase<Context>,
DipMerkleProofRevealedLeaf: Default + Clone,
LocalBlockNumber: Default,
Context: Clone,
{
fn worst_case(context: Context) -> Self {
Self::V0(v0::SiblingParachainDipStateProof::worst_case(context))
}
}

pub enum DipSiblingProviderStateProofVerifierError<
ParachainHeadMerkleProofVerificationError,
IdentityCommitmentMerkleProofVerificationError,
Expand Down Expand Up @@ -183,7 +203,7 @@ impl<
>;
type Proof = VersionedSiblingParachainDipStateProof<
RelayChainStateInfo::BlockNumber,
Vec<Vec<u8>>,
BoundedBlindedValue<u8>,
RevealedDidMerkleProofLeaf<
KeyIdOf<KiltRuntime>,
KiltRuntime::AccountId,
Expand Down Expand Up @@ -336,7 +356,7 @@ impl<
>;
type Proof = VersionedSiblingParachainDipStateProof<
RelayChainStateInfo::BlockNumber,
Vec<Vec<u8>>,
BoundedBlindedValue<u8>,
RevealedDidMerkleProofLeaf<
ProviderDidKeyId,
ProviderAccountId,
Expand Down Expand Up @@ -413,9 +433,34 @@ mod v0 {
DipMerkleProofRevealedLeaf,
LocalBlockNumber,
> {
para_state_root: ParachainRootStateProof<RelayBlockHeight>,
dip_identity_commitment: Vec<Vec<u8>>,
did: DipMerkleProofAndDidSignature<DipMerkleProofBlindedValues, DipMerkleProofRevealedLeaf, LocalBlockNumber>,
pub(crate) para_state_root: ParachainRootStateProof<RelayBlockHeight>,
pub(crate) dip_identity_commitment: BoundedBlindedValue<u8>,
pub(crate) did:
DipMerkleProofAndDidSignature<DipMerkleProofBlindedValues, DipMerkleProofRevealedLeaf, LocalBlockNumber>,
}

#[cfg(feature = "runtime-benchmarks")]
impl<RelayBlockHeight, DipMerkleProofBlindedValues, DipMerkleProofRevealedLeaf, LocalBlockNumber, Context>
kilt_support::traits::GetWorstCase<Context>
for SiblingParachainDipStateProof<
RelayBlockHeight,
DipMerkleProofBlindedValues,
DipMerkleProofRevealedLeaf,
LocalBlockNumber,
> where
DipMerkleProofBlindedValues: kilt_support::traits::GetWorstCase<Context>,
DipMerkleProofRevealedLeaf: Default + Clone,
RelayBlockHeight: Default,
LocalBlockNumber: Default,
Context: Clone,
{
fn worst_case(context: Context) -> Self {
Self {
para_state_root: ParachainRootStateProof::worst_case(context.clone()),
dip_identity_commitment: BoundedBlindedValue::worst_case(context.clone()),
did: DipMerkleProofAndDidSignature::worst_case(context),
}
}
}

#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
Expand Down Expand Up @@ -518,7 +563,7 @@ mod v0 {
>;
type Proof = SiblingParachainDipStateProof<
RelayChainStateInfo::BlockNumber,
Vec<Vec<u8>>,
BoundedBlindedValue<u8>,
RevealedDidMerkleProofLeaf<
ProviderDidKeyId,
ProviderAccountId,
Expand Down
1 change: 1 addition & 0 deletions crates/kilt-dip-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ pub use state_proofs::{
relay_chain::{ParachainHeadProofVerifier, ParachainHeadProofVerifierError, RelayStateRootsViaRelayStorePallet},
};
pub use traits::{FrameSystemDidSignatureContext, ProviderParachainStateInfoViaProviderPallet};
pub use utils::BoundedBlindedValue;
Loading

0 comments on commit 5afb750

Please sign in to comment.