Skip to content

Commit

Permalink
Schema grants#224 (#381)
Browse files Browse the repository at this point in the history
# Goal
The goal of this PR is to allow providers to publish messages on
specific schema_ids for a given delegator
Provider should provider list of schema_ids while adding a user as
delegator

Closes #224 
Closes #314 
Closes #140 

# Checklist
- [x] Updated the js/api-augment code if a custom RPC added/changed
- [x] Update msa and messages pallets to support schema grants between
delegator and provider
- [x] Runtime updated
- [x] Tests added
- [x] Benchmarks added
- [x] Weights updated
  • Loading branch information
saraswatpuneet authored Sep 12, 2022
1 parent 47462e3 commit e20b67e
Show file tree
Hide file tree
Showing 34 changed files with 846 additions and 406 deletions.
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions common/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ smallvec = "1.9.0"
sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" }
sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" }

#ORML
orml-utilities = {git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, branch = "polkadot-v0.9.27"}

[features]
default = ['std']
std = [
Expand Down
38 changes: 38 additions & 0 deletions common/primitives/src/ds.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{traits::Get, BoundedVec};
use orml_utilities::OrderedSet;
use scale_info::TypeInfo;

/// Extending OrderSet and implement struct OrderedSetExt
#[derive(TypeInfo, Clone, Decode, Encode, PartialEq, Eq, MaxEncodedLen, Default)]
#[scale_info(skip_type_params(T, S))]
pub struct OrderedSetExt<
T: Ord + Encode + Decode + MaxEncodedLen + Clone + Eq + PartialEq,
S: Get<u32>,
>(pub OrderedSet<T, S>);

impl<T, S> OrderedSetExt<T, S>
where
T: Ord + Encode + Decode + MaxEncodedLen + Clone + Eq + PartialEq + core::fmt::Debug,
S: Get<u32>,
{
/// Create a new empty set
pub fn new() -> Self {
Self(OrderedSet::<T, S>::new())
}
/// Create a set from a `Vec`.
/// `v` will be sorted and dedup first.
pub fn from(bv: BoundedVec<T, S>) -> Self {
Self(OrderedSet::<T, S>::from(bv))
}
}

impl<T, S> core::fmt::Debug for OrderedSetExt<T, S>
where
T: Ord + Encode + Decode + MaxEncodedLen + Clone + Eq + PartialEq + core::fmt::Debug,
S: Get<u32>,
{
fn fmt(&self, _f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
Ok(())
}
}
2 changes: 2 additions & 0 deletions common/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
missing_docs
)]

/// Data structures for the generic use.
pub mod ds;
/// Structs and traits for the Messages pallet.
pub mod messages;
/// Structs and traits for the MSA pallet.
Expand Down
27 changes: 25 additions & 2 deletions common/primitives/src/msa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use serde::{Deserialize, Serialize};
use sp_runtime::DispatchError;
use sp_std::prelude::Vec;

pub use crate::{ds::OrderedSetExt, schema::SchemaId};

/// Message Source Id or msaId is the unique identifier for Message Source Accounts
pub type MessageSourceId = u64;

Expand Down Expand Up @@ -65,11 +67,17 @@ impl KeyInfo {

/// Struct for the information of the relationship between an MSA and a Provider
#[derive(TypeInfo, Debug, Clone, Decode, Encode, PartialEq, Default, MaxEncodedLen)]
pub struct ProviderInfo<BlockNumber> {
#[scale_info(skip_type_params(MaxSchemaGrants))]
pub struct ProviderInfo<BlockNumber, MaxSchemaGrants>
where
MaxSchemaGrants: Get<u32>,
{
/// Specifies a permission granted by the delegator to the provider.
pub permission: u8,
/// Block number the grant will be revoked.
pub expired: BlockNumber,
/// Schemas that the provider is allowed to use for a delegated message.
pub schemas: OrderedSetExt<SchemaId, MaxSchemaGrants>,
}

/// Provider is the recipient of a delegation.
Expand Down Expand Up @@ -124,6 +132,8 @@ pub trait AccountProvider {
type AccountId;
/// Type for block number.
type BlockNumber;
/// Type for maximum number of schemas that can be granted to a provider.
type MaxSchemaGrants: Get<u32> + Clone + Eq;

/// Gets the MSA Id associated with this `AccountId` if any
/// # Arguments
Expand All @@ -141,7 +151,7 @@ pub trait AccountProvider {
fn get_provider_info_of(
delegator: Delegator,
provider: Provider,
) -> Option<ProviderInfo<Self::BlockNumber>>;
) -> Option<ProviderInfo<Self::BlockNumber, Self::MaxSchemaGrants>>;
/// Check that a key is associated to an MSA and returns key information.
/// Returns a `[DispatchError`] if there is no MSA associated with the key
/// # Arguments
Expand All @@ -157,6 +167,19 @@ pub trait AccountProvider {
/// # Returns
/// * [DispatchResult](https://paritytech.github.io/substrate/master/frame_support/dispatch/type.DispatchResult.html) The return type of a Dispatchable in frame.
fn ensure_valid_delegation(provider: Provider, delegator: Delegator) -> DispatchResult;

/// Validates if the provider is allowed to use the schema
/// # Arguments
/// * `provider` - The `MessageSourceId` that has been delegated to
/// * `delegator` - The `MessageSourceId` that delegated to the provider
/// * `schema_id` - The `SchemaId` that the provider is trying to use
/// # Returns
/// * [DispatchResult](https://paritytech.github.io/substrate/master/frame_support/dispatch/type.DispatchResult.html) The return type of a Dispatchable in frame.
fn ensure_valid_schema_grant(
provider: Provider,
delegator: Delegator,
schema_id: SchemaId,
) -> DispatchResult;
}

/// RPC Response form of [`KeyInfo`]
Expand Down
4 changes: 4 additions & 0 deletions js/api-augment/interfaces/augment-api-consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ declare module '@polkadot/api-base/types/consts' {
* Maximum provider name size allowed per MSA association
**/
maxProviderNameSize: u32 & AugmentedConst<ApiType>;
/**
* Maximum count of schemas granted for publishing data per Provider
**/
maxSchemaGrants: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
Expand Down
8 changes: 8 additions & 0 deletions js/api-augment/interfaces/augment-api-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,10 @@ declare module '@polkadot/api-base/types/errors' {
* The maximum length for a provider name has been exceeded
**/
ExceedsMaxProviderNameSize: AugmentedError<ApiType>;
/**
* The maximum number of schema grants has been exceeded
**/
ExceedsMaxSchemaGrants: AugmentedError<ApiType>;
/**
* An MSA may not be its own delegate
**/
Expand Down Expand Up @@ -425,6 +429,10 @@ declare module '@polkadot/api-base/types/errors' {
* Ony the MSA Owner may perform the operation
**/
NotMsaOwner: AugmentedError<ApiType>;
/**
* Provider is not permitted to publish for given schema_id
**/
SchemaNotGranted: AugmentedError<ApiType>;
/**
* Origin attempted to add a delegate for someone else's MSA
**/
Expand Down
4 changes: 2 additions & 2 deletions js/api-augment/interfaces/augment-api-tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ declare module '@polkadot/api-base/types/submittable' {
* - Returns [`InvalidSignature`](Error::InvalidSignature) if `proof` verification fails; `delegator_key` must have signed `add_provider_payload`
* - Returns [`NoKeyExists`](Error::NoKeyExists) if there is no MSA for `origin`.
**/
addProviderToMsa: AugmentedSubmittable<(providerKey: AccountId32 | string | Uint8Array, proof: SpRuntimeMultiSignature | { Ed25519: any } | { Sr25519: any } | { Ecdsa: any } | string | Uint8Array, addProviderPayload: PalletMsaAddProvider | { authorizedMsaId?: any; permission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32, SpRuntimeMultiSignature, PalletMsaAddProvider]>;
addProviderToMsa: AugmentedSubmittable<(providerKey: AccountId32 | string | Uint8Array, proof: SpRuntimeMultiSignature | { Ed25519: any } | { Sr25519: any } | { Ecdsa: any } | string | Uint8Array, addProviderPayload: PalletMsaAddProvider | { authorizedMsaId?: any; permission?: any; schemaIds?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32, SpRuntimeMultiSignature, PalletMsaAddProvider]>;
/**
* Creates an MSA for the Origin (sender of the transaction). Origin is assigned an MSA ID.
* Deposits [`MsaCreated`](Event::MsaCreated) event, and returns `Ok(())` on success, otherwise returns an error.
Expand All @@ -747,7 +747,7 @@ declare module '@polkadot/api-base/types/submittable' {
* - Returns [`KeyAlreadyRegistered`](Error::KeyAlreadyRegistered) if there is already an MSA for `delegator_key`.
*
**/
createSponsoredAccountWithDelegation: AugmentedSubmittable<(delegatorKey: AccountId32 | string | Uint8Array, proof: SpRuntimeMultiSignature | { Ed25519: any } | { Sr25519: any } | { Ecdsa: any } | string | Uint8Array, addProviderPayload: PalletMsaAddProvider | { authorizedMsaId?: any; permission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32, SpRuntimeMultiSignature, PalletMsaAddProvider]>;
createSponsoredAccountWithDelegation: AugmentedSubmittable<(delegatorKey: AccountId32 | string | Uint8Array, proof: SpRuntimeMultiSignature | { Ed25519: any } | { Sr25519: any } | { Ecdsa: any } | string | Uint8Array, addProviderPayload: PalletMsaAddProvider | { authorizedMsaId?: any; permission?: any; schemaIds?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32, SpRuntimeMultiSignature, PalletMsaAddProvider]>;
/**
* Remove a key associated with an MSA by expiring it at the current block.
* Returns `Ok(())` on success, otherwise returns an error. Deposits event [`KeyRemoved`](Event::KeyRemoved).
Expand Down
4 changes: 1 addition & 3 deletions js/api-augment/interfaces/augment-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import type { AllowedSlots, BabeAuthorityWeight, BabeBlockWeight, BabeEpochConfiguration, BabeEquivocationProof, BabeGenesisConfiguration, BabeGenesisConfigurationV1, BabeWeight, Epoch, EpochAuthorship, MaybeRandomness, MaybeVrf, NextConfigDescriptor, NextConfigDescriptorV1, OpaqueKeyOwnershipProof, Randomness, RawBabePreDigest, RawBabePreDigestCompat, RawBabePreDigestPrimary, RawBabePreDigestPrimaryTo159, RawBabePreDigestSecondaryPlain, RawBabePreDigestSecondaryTo159, RawBabePreDigestSecondaryVRF, RawBabePreDigestTo159, SlotNumber, VrfData, VrfOutput, VrfProof } from '@polkadot/types/interfaces/babe';
import type { AccountData, BalanceLock, BalanceLockTo212, BalanceStatus, Reasons, ReserveData, ReserveIdentifier, VestingSchedule, WithdrawReasons } from '@polkadot/types/interfaces/balances';
import type { BeefyAuthoritySet, BeefyCommitment, BeefyId, BeefyNextAuthoritySet, BeefyPayload, BeefyPayloadId, BeefySignedCommitment, MmrRootHash, ValidatorSet, ValidatorSetId } from '@polkadot/types/interfaces/beefy';
import type { BenchmarkBatch, BenchmarkConfig, BenchmarkList, BenchmarkMetadata, BenchmarkParameter, BenchmarkResult } from '@polkadot/types/interfaces/benchmark';
import type { BenchmarkConfig, BenchmarkList, BenchmarkMetadata, BenchmarkParameter } from '@polkadot/types/interfaces/benchmark';
import type { CheckInherentsResult, InherentData, InherentIdentifier } from '@polkadot/types/interfaces/blockbuilder';
import type { BridgeMessageId, BridgedBlockHash, BridgedBlockNumber, BridgedHeader, CallOrigin, ChainId, DeliveredMessages, DispatchFeePayment, InboundLaneData, InboundRelayer, InitializationData, LaneId, MessageData, MessageKey, MessageNonce, MessagesDeliveryProofOf, MessagesProofOf, OperatingMode, OutboundLaneData, OutboundMessageFee, OutboundPayload, Parameter, RelayerId, UnrewardedRelayer, UnrewardedRelayersState } from '@polkadot/types/interfaces/bridges';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
Expand Down Expand Up @@ -158,12 +158,10 @@ declare module '@polkadot/types/types/registry' {
BeefyPayload: BeefyPayload;
BeefyPayloadId: BeefyPayloadId;
BeefySignedCommitment: BeefySignedCommitment;
BenchmarkBatch: BenchmarkBatch;
BenchmarkConfig: BenchmarkConfig;
BenchmarkList: BenchmarkList;
BenchmarkMetadata: BenchmarkMetadata;
BenchmarkParameter: BenchmarkParameter;
BenchmarkResult: BenchmarkResult;
Bid: Bid;
Bidder: Bidder;
BidKind: BidKind;
Expand Down
Loading

0 comments on commit e20b67e

Please sign in to comment.