Skip to content

Commit

Permalink
Schema BitFlags: Enable fine grained schema controls via optional set…
Browse files Browse the repository at this point in the history
…tings (#1079)

# Goal
The goal of this PR is :-

SchemaSettings: Enable fine grained schema controls via optional
settings

This PR addressed updating schemas pallet and all the dependent
code/tests to be updated

With @aramikm 

Creates : #1106

Closes : #1020 

# Discussion
<!-- List discussion items -->

# Checklist
- [ ] Chain spec updated
- [x] Custom RPC OR Runtime API added/changed? Updated js/api-augment.
- [ ] Design doc(s) updated
- [x] Tests added
- [ ] Benchmarks added
- [ ] Weights updated

---------

Co-authored-by: Aramik <aramikm@gmail.com>
  • Loading branch information
saraswatpuneet and aramikm authored Feb 28, 2023
1 parent d0ebf9e commit f05867c
Show file tree
Hide file tree
Showing 33 changed files with 1,985 additions and 2,457 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions common/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ targets = ['x86_64-unknown-linux-gnu']
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = [
"derive",
] }
enumflags2 = "0.7.5"
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
impl-serde = { version = "0.4.0", default-features = false }
scale-info = { version = "2.2.0", default-features = false, features = [
Expand Down
2 changes: 2 additions & 0 deletions common/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
rustdoc::invalid_codeblock_attributes,
missing_docs
)]
/// macros
pub mod macros;
/// Structs and traits for the Messages pallet.
pub mod messages;
/// Structs and traits for the MSA pallet.
Expand Down
76 changes: 76 additions & 0 deletions common/primitives/src/macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// This file is part of Substrate.

// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// macro_rules! impl_incrementable {
// ($($type:ty),+) => {
// $(
// impl Incrementable for $type {
// fn increment(&self) -> Self {
// let mut val = self.clone();
// val.saturating_inc();
// val
// }
//
// fn initial_value() -> Self {
// 0
// }
// }
// )+
// };
// }
// pub(crate) use impl_incrementable;

#[macro_export]
#[doc(hidden)]
macro_rules! impl_codec_bitflags {
($wrapper:ty, $size:ty, $bitflag_enum:ty) => {
impl MaxEncodedLen for $wrapper {
fn max_encoded_len() -> usize {
<$size>::max_encoded_len()
}
}
impl Encode for $wrapper {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.0.bits().using_encoded(f)
}
}
impl EncodeLike for $wrapper {}
impl Decode for $wrapper {
fn decode<I: codec::Input>(
input: &mut I,
) -> sp_std::result::Result<Self, codec::Error> {
let field = <$size>::decode(input)?;
Ok(Self(BitFlags::from_bits(field as $size).map_err(|_| "invalid value")?))
}
}

impl TypeInfo for $wrapper {
type Identity = Self;

fn type_info() -> Type {
Type::builder()
.path(Path::new("BitFlags", module_path!()))
.type_params(vec![TypeParameter::new("T", Some(meta_type::<$bitflag_enum>()))])
.composite(
Fields::unnamed()
.field(|f| f.ty::<$size>().type_name(stringify!($bitflag_enum))),
)
}
}
};
}
// pub(crate) use impl_codec_bitflags;
51 changes: 49 additions & 2 deletions common/primitives/src/schema.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use crate::impl_codec_bitflags;
#[cfg(feature = "std")]
use crate::utils;
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
use enumflags2::{bitflags, BitFlags};
use frame_support::RuntimeDebug;
use scale_info::{build::Fields, meta_type, Path, Type, TypeInfo, TypeParameter};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_std::prelude::*;
Expand Down Expand Up @@ -35,6 +38,24 @@ pub enum PayloadLocation {
Paginated,
}

/// Support for up to 16 user-enabled features on a collection.
#[bitflags]
#[repr(u16)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, RuntimeDebug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo)]
pub enum SchemaSetting {
/// Schema setting to enforce append-only behavior on payload.
/// Applied to schemas of type `PayloadLocation::Itemized` or `PayloadLocation::Paginated`.
AppendOnly,
/// Schema may enforce signature requirement on payload.
/// Applied to schemas of type `PayloadLocation::Paginated`.
SignatureRequired,
}

/// Wrapper type for `BitFlags<SchemaSetting>` that implements `Codec`.
#[derive(Clone, Copy, PartialEq, Eq, Default, RuntimeDebug)]
pub struct SchemaSettings(pub BitFlags<SchemaSetting>);

/// RPC Response form for a Schema
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Encode, Decode, PartialEq, Debug, TypeInfo, Eq)]
Expand All @@ -48,6 +69,8 @@ pub struct SchemaResponse {
pub model_type: ModelType,
/// The payload location
pub payload_location: PayloadLocation,
/// grants for the schema
pub settings: Vec<SchemaSetting>,
}

/// This allows other pallets to resolve Schema information. With generic SchemaId
Expand All @@ -65,3 +88,27 @@ pub trait SchemaValidator<SchemaId> {
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
fn set_schema_count(n: SchemaId);
}

impl SchemaSettings {
/// Set all settings to disabled
pub fn all_disabled() -> Self {
Self(BitFlags::EMPTY)
}
/// Get all setting enabled
pub fn get_enabled(&self) -> BitFlags<SchemaSetting> {
self.0
}
/// Check if a setting is enabled
pub fn is_enabled(&self, grant: SchemaSetting) -> bool {
self.0.contains(grant)
}
/// Enable a setting
pub fn set(&mut self, grant: SchemaSetting) {
self.0.insert(grant)
}
/// Copy the settings from a BitFlags
pub fn from(settings: BitFlags<SchemaSetting>) -> Self {
Self(settings)
}
}
impl_codec_bitflags!(SchemaSettings, u16, SchemaSetting);
Loading

0 comments on commit f05867c

Please sign in to comment.