Browse Source

Rename to content-directory

iorveth 4 years ago
parent
commit
2395986707

+ 20 - 20
Cargo.lock

@@ -1633,6 +1633,7 @@ dependencies = [
  "substrate-client",
  "substrate-common-module",
  "substrate-consensus-babe-primitives",
+ "substrate-content-directory-module",
  "substrate-content-working-group-module",
  "substrate-forum-module",
  "substrate-governance-module",
@@ -1648,7 +1649,6 @@ dependencies = [
  "substrate-stake-module",
  "substrate-storage-module",
  "substrate-token-mint-module",
- "substrate-versioned-store-permissions-module",
  "substrate-wasm-builder-runner",
 ]
 
@@ -4647,6 +4647,24 @@ dependencies = [
  "substrate-primitives",
 ]
 
+[[package]]
+name = "substrate-content-directory-module"
+version = "1.0.1"
+dependencies = [
+ "hex-literal 0.1.4",
+ "parity-scale-codec",
+ "quote 0.6.13",
+ "serde",
+ "sr-io",
+ "sr-primitives",
+ "sr-std",
+ "srml-support",
+ "srml-support-procedural",
+ "srml-system",
+ "srml-timestamp",
+ "substrate-primitives",
+]
+
 [[package]]
 name = "substrate-content-working-group-module"
 version = "1.0.0"
@@ -4661,6 +4679,7 @@ dependencies = [
  "srml-system",
  "srml-timestamp",
  "substrate-common-module",
+ "substrate-content-directory-module",
  "substrate-forum-module",
  "substrate-hiring-module",
  "substrate-membership-module",
@@ -4668,7 +4687,6 @@ dependencies = [
  "substrate-recurring-reward-module",
  "substrate-stake-module",
  "substrate-token-mint-module",
- "substrate-versioned-store-permissions-module",
 ]
 
 [[package]]
@@ -5397,24 +5415,6 @@ dependencies = [
  "trie-root",
 ]
 
-[[package]]
-name = "substrate-versioned-store-permissions-module"
-version = "1.0.1"
-dependencies = [
- "hex-literal 0.1.4",
- "parity-scale-codec",
- "quote 0.6.13",
- "serde",
- "sr-io",
- "sr-primitives",
- "sr-std",
- "srml-support",
- "srml-support-procedural",
- "srml-system",
- "srml-timestamp",
- "substrate-primitives",
-]
-
 [[package]]
 name = "substrate-wasm-builder-runner"
 version = "1.0.5"

+ 1 - 1
Cargo.toml

@@ -14,7 +14,7 @@ members = [
 	"runtime-modules/stake",
 	"runtime-modules/storage",
 	"runtime-modules/token-minting",
-	"runtime-modules/versioned-store-permissions",
+	"runtime-modules/content-directory",
 	"node",
 	"utils/chain-spec-builder/"
 ]

+ 2 - 2
node/src/chain_spec.rs

@@ -15,7 +15,7 @@
 // along with Joystream node.  If not, see <http://www.gnu.org/licenses/>.
 
 use node_runtime::{
-    versioned_store_permissions::InputValidationLengthConstraint as VsInputValidation, ActorsConfig,
+    content_directory::InputValidationLengthConstraint as VsInputValidation, ActorsConfig,
     AuthorityDiscoveryConfig, BabeConfig, Balance, BalancesConfig, ContentWorkingGroupConfig,
     CouncilConfig, CouncilElectionConfig, DataObjectStorageRegistryConfig,
     DataObjectTypeRegistryConfig, ElectionParameters, GrandpaConfig, ImOnlineConfig, IndicesConfig,
@@ -273,7 +273,7 @@ pub fn testnet_genesis(
             enable_storage_role: true,
             request_life_time: 300,
         }),
-        // versioned_store_permissions: Some(VersionedStorePermissionsConfig {
+        // content_directory: Some(VersionedStorePermissionsConfig {
         //     class_by_id: vec![],
         //     entity_by_id: vec![],
         //     next_class_id: 1,

+ 4 - 4
runtime-modules/content-working-group/Cargo.toml

@@ -19,7 +19,7 @@ std = [
     'hiring/std',
     'stake/std',
     'minting/std',
-    'versioned_store_permissions/std',
+    'content_directory/std',
     'recurringrewards/std',
 ]
 
@@ -90,10 +90,10 @@ default_features = false
 package = 'substrate-hiring-module'
 path = '../hiring'
 
-[dependencies.versioned_store_permissions]
+[dependencies.content_directory]
 default_features = false
-package = 'substrate-versioned-store-permissions-module'
-path = '../versioned-store-permissions'
+package = 'substrate-content-directory-module'
+path = '../content-directory'
 
 [dependencies.membership]
 default_features = false

+ 3 - 3
runtime-modules/content-working-group/src/lib.rs

@@ -41,7 +41,7 @@ pub trait Trait:
     + recurringrewards::Trait
     + stake::Trait
     + hiring::Trait
-    + versioned_store_permissions::Trait
+    + content_directory::Trait
     + members::Trait
 {
     // + Sized
@@ -88,7 +88,7 @@ pub type RewardRelationshipId<T> = <T as recurringrewards::Trait>::RewardRelatio
 pub type StakeId<T> = <T as stake::Trait>::StakeId;
 
 /// Type of permissions module prinicipal identifiers
-pub type PrincipalId<T> = <T as versioned_store_permissions::Trait>::Credential;
+pub type PrincipalId<T> = <T as content_directory::Trait>::Credential;
 
 pub type CuratorApplicationIdToCuratorIdMap<T> = BTreeMap<CuratorApplicationId<T>, CuratorId<T>>;
 
@@ -2000,7 +2000,7 @@ decl_module! {
     }
 }
 
-impl<T: Trait> versioned_store_permissions::CredentialChecker<T> for Module<T> {
+impl<T: Trait> content_directory::CredentialChecker<T> for Module<T> {
     fn account_has_credential(account: &T::AccountId, id: PrincipalId<T>) -> bool {
         // Check that principal exists
         if !PrincipalById::<T>::exists(&id) {

+ 2 - 2
runtime-modules/content-working-group/src/mock.rs

@@ -20,7 +20,7 @@ pub use membership::members;
 pub use minting;
 pub use recurringrewards;
 pub use stake;
-pub use versioned_store_permissions;
+pub use content_directory;
 
 use crate::genesis;
 
@@ -170,7 +170,7 @@ impl hiring::Trait for Test {
 }
 
 type TestPrincipalId = u64;
-impl versioned_store_permissions::Trait for Test {
+impl content_directory::Trait for Test {
     type Credential = TestPrincipalId;
     type CredentialChecker = ();
     type CreateClassPermissionsChecker = ();

+ 0 - 40
runtime-modules/versioned-store-permissions/Cargo.toml

@@ -1,40 +0,0 @@
-[package]
-name = 'substrate-versioned-store-permissions-module'
-version = '1.0.1'
-authors = ['Joystream contributors']
-edition = '2018'
-
-[dependencies]
-hex-literal = '0.1.0'
-codec = { package = 'parity-scale-codec', version = '1.0.0', default-features = false, features = ['derive'] }
-rstd = { package = 'sr-std', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-runtime-primitives = { package = 'sr-primitives', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-srml-support = { package = 'srml-support', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-srml-support-procedural = { package = 'srml-support-procedural', git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-system = { package = 'srml-system', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-timestamp = { package = 'srml-timestamp', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-runtime-io = { package = 'sr-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-# https://users.rust-lang.org/t/failure-derive-compilation-error/39062
-quote = '<=1.0.2'
-
-[dependencies.serde]
-features = ['derive']
-optional = true
-version = '1.0.101'
-
-[dev-dependencies]
-runtime-io = { package = 'sr-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-primitives = { package = 'substrate-primitives', git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-
-[features]
-default = ['std']
-std = [
-	'serde',
-	'codec/std',
-	'rstd/std',
-	'runtime-io/std',
-	'runtime-primitives/std',
-	'srml-support/std',
-	'system/std',
-	'timestamp/std',
-]

+ 0 - 33
runtime-modules/versioned-store-permissions/src/constraint.rs

@@ -1,33 +0,0 @@
-use codec::{Decode, Encode};
-use rstd::collections::btree_set::BTreeSet;
-
-#[cfg(feature = "std")]
-use serde::{Deserialize, Serialize};
-
-/// Reference to a specific property of a specific class.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Eq, PartialEq, Ord, PartialOrd, Clone, Debug)]
-pub struct PropertyOfClass<ClassId, PropertyIndex> {
-    pub class_id: ClassId,
-    pub property_index: PropertyIndex,
-}
-
-/// The type of constraint imposed on referencing a class via class property of type "Internal".
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub enum ReferenceConstraint<ClassId: Ord, PropertyIndex: Ord> {
-    /// No property can reference the class.
-    NoReferencingAllowed,
-
-    /// Any property of any class may reference the class.
-    NoConstraint,
-
-    /// Only a set of properties of specific classes can reference the class.
-    Restricted(BTreeSet<PropertyOfClass<ClassId, PropertyIndex>>),
-}
-
-impl<ClassId: Ord, PropertyIndex: Ord> Default for ReferenceConstraint<ClassId, PropertyIndex> {
-    fn default() -> Self {
-        ReferenceConstraint::NoReferencingAllowed
-    }
-}

+ 0 - 61
runtime-modules/versioned-store-permissions/src/credentials.rs

@@ -1,61 +0,0 @@
-use codec::{Decode, Encode};
-use rstd::collections::btree_set::BTreeSet;
-use rstd::prelude::*;
-
-#[cfg(feature = "std")]
-use serde::{Deserialize, Serialize};
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct CredentialSet<Credential: Ord>(BTreeSet<Credential>);
-
-impl<Credential> From<Vec<Credential>> for CredentialSet<Credential>
-where
-    Credential: Ord,
-{
-    fn from(v: Vec<Credential>) -> CredentialSet<Credential> {
-        let mut set = CredentialSet(BTreeSet::new());
-        for credential in v.into_iter() {
-            set.insert(credential);
-        }
-        set
-    }
-}
-
-/// Default CredentialSet set is just an empty set.
-impl<Credential: Ord> Default for CredentialSet<Credential> {
-    fn default() -> Self {
-        CredentialSet(BTreeSet::new())
-    }
-}
-
-impl<Credential: Ord> CredentialSet<Credential> {
-    pub fn new() -> Self {
-        Self(BTreeSet::new())
-    }
-
-    pub fn insert(&mut self, value: Credential) -> bool {
-        self.0.insert(value)
-    }
-
-    pub fn contains(&self, value: &Credential) -> bool {
-        self.0.contains(value)
-    }
-
-    pub fn is_empty(&self) -> bool {
-        self.0.is_empty()
-    }
-}
-
-/// Type, derived from dispatchable call, identifies the caller
-#[derive(Encode, Decode, Eq, PartialEq, Ord, PartialOrd, Clone, Debug)]
-pub enum AccessLevel<Credential> {
-    /// ROOT origin
-    System,
-    /// Caller identified as the entity maintainer
-    EntityMaintainer, // Maybe enclose EntityId?
-    /// Verified Credential
-    Credential(Credential),
-    /// In cases where a signed extrinsic doesn't provide a Credential
-    Unspecified,
-}

+ 0 - 40
runtime-modules/versioned-store-permissions/src/errors.rs

@@ -1,40 +0,0 @@
-// Validation errors
-// --------------------------------------
-
-pub const ERROR_PROPERTY_NAME_TOO_SHORT: &str = "Property name is too short";
-pub const ERROR_PROPERTY_NAME_TOO_LONG: &str = "Property name is too long";
-pub const ERROR_PROPERTY_DESCRIPTION_TOO_SHORT: &str = "Property description is too long";
-pub const ERROR_PROPERTY_DESCRIPTION_TOO_LONG: &str = "Property description is too long";
-
-pub const ERROR_CLASS_NAME_TOO_SHORT: &str = "Class name is too short";
-pub const ERROR_CLASS_NAME_TOO_LONG: &str = "Class name is too long";
-pub const ERROR_CLASS_DESCRIPTION_TOO_SHORT: &str = "Class description is too long";
-pub const ERROR_CLASS_DESCRIPTION_TOO_LONG: &str = "Class description is too long";
-
-// Main logic errors
-// --------------------------------------
-
-pub const ERROR_CLASS_NOT_FOUND: &str = "Class was not found by id";
-pub const ERROR_UNKNOWN_CLASS_SCHEMA_ID: &str = "Unknown class schema id";
-pub const ERROR_CLASS_SCHEMA_NOT_ACTIVE: &str = "Given class schema is not active";
-pub const ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_PROP_INDEX: &str =
-    "New class schema refers to an unknown property index";
-pub const ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_INTERNAL_ID: &str =
-    "New class schema refers to an unknown internal class id";
-pub const ERROR_NO_PROPS_IN_CLASS_SCHEMA: &str =
-    "Cannot add a class schema with an empty list of properties";
-pub const ERROR_ENTITY_NOT_FOUND: &str = "Entity was not found by id";
-// pub const ERROR_ENTITY_ALREADY_DELETED: &str = "Entity is already deleted";
-pub const ERROR_SCHEMA_ALREADY_ADDED_TO_ENTITY: &str =
-    "Cannot add a schema that is already added to this entity";
-pub const ERROR_PROP_VALUE_DONT_MATCH_TYPE: &str =
-    "Some of the provided property values don't match the expected property type";
-pub const ERROR_PROP_NAME_NOT_UNIQUE_IN_CLASS: &str =
-    "Property name is not unique within its class";
-pub const ERROR_MISSING_REQUIRED_PROP: &str =
-    "Some required property was not found when adding schema support to entity";
-pub const ERROR_UNKNOWN_ENTITY_PROP_ID: &str = "Some of the provided property ids cannot be found on the current list of propery values of this entity";
-pub const ERROR_TEXT_PROP_IS_TOO_LONG: &str = "Text propery is too long";
-pub const ERROR_VEC_PROP_IS_TOO_LONG: &str = "Vector propery is too long";
-pub const ERROR_INTERNAL_RPOP_DOES_NOT_MATCH_ITS_CLASS: &str =
-    "Internal property does not match its class";

+ 0 - 530
runtime-modules/versioned-store-permissions/src/example.rs

@@ -1,530 +0,0 @@
-#![cfg(test)]
-
-use super::*;
-use crate::mock::*;
-
-use srml_support::assert_ok;
-
-/// This example uses Class, Properties, Schema and Entity structures
-/// to describe the Staked podcast channel and its second episode.
-/// See https://staked.libsyn.com/rss
-
-#[test]
-fn create_podcast_class_schema() {
-    with_test_externalities(|| {
-        fn common_text_prop() -> PropertyType {
-            PropertyType::Text(200)
-        }
-
-        fn long_text_prop() -> PropertyType {
-            PropertyType::Text(4000)
-        }
-
-        // Channel props:
-        // ------------------------------------------
-
-        let channel_props = vec![
-            // 0
-            Property {
-                prop_type: common_text_prop(),
-                required: true,
-                name: b"atom:link".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 1
-            Property {
-                prop_type: common_text_prop(),
-                required: true,
-                name: b"title".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 2
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"pubDate".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 3
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"lastBuildDate".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 4
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"generator".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 5
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"link".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 6
-            // Example: en-us
-            Property {
-                prop_type: PropertyType::Text(5),
-                required: false,
-                name: b"language".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 7
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"copyright".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 8
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"docs".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 9
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"managingEditor".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 10
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"image/url".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 11
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"image/title".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 12
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"image/link".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 13
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:summary".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 14
-            // TODO this could be Internal prop.
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:author".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 15
-            // TODO make this as a text vec?
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:keywords".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 16
-            Property {
-                prop_type: PropertyType::TextVec(10, 100),
-                required: false,
-                name: b"itunes:category".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 17
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:image".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 18
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:explicit".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 19
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:owner/itunes:name".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 20
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:owner/itunes:email".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 21
-            Property {
-                prop_type: PropertyType::Text(4000),
-                required: false,
-                name: b"description".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 22
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:subtitle".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 23
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:type".to_vec(),
-                description: b"".to_vec(),
-            },
-        ];
-
-        // Episode props
-        // ------------------------------------------
-
-        let episode_props = vec![
-            // 0
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"title".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 1
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:title".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 2
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"pubDate".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 3
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"guid".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 4
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"link".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 5
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:image".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 6
-            Property {
-                prop_type: long_text_prop(),
-                required: false,
-                name: b"description".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 7
-            Property {
-                prop_type: long_text_prop(),
-                required: false,
-                name: b"content:encoded".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 8
-            Property {
-                prop_type: PropertyType::Text(50),
-                required: false,
-                name: b"enclosure/length".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 9
-            Property {
-                prop_type: PropertyType::Text(50),
-                required: false,
-                name: b"enclosure/type".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 10
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"enclosure/url".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 11
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:duration".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 12
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:explicit".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 13
-            // TODO make this as a text vec?
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:keywords".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 14
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:subtitle".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 15
-            Property {
-                prop_type: long_text_prop(),
-                required: false,
-                name: b"itunes:summary".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 16
-            Property {
-                prop_type: PropertyType::Uint16,
-                required: false,
-                name: b"itunes:season".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 17
-            Property {
-                prop_type: PropertyType::Uint16,
-                required: false,
-                name: b"itunes:episode".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 18
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:episodeType".to_vec(),
-                description: b"".to_vec(),
-            },
-            // 19
-            // TODO this could be Internal prop.
-            Property {
-                prop_type: common_text_prop(),
-                required: false,
-                name: b"itunes:author".to_vec(),
-                description: b"".to_vec(),
-            },
-        ];
-
-        // Channel
-
-        let channel_class_id = TestModule::next_class_id();
-        assert_ok!(TestModule::create_class_with_default_permissions(
-            Origin::signed(CLASS_PERMISSIONS_CREATOR1),
-            b"PodcastChannel".to_vec(),
-            b"A podcast channel".to_vec(),
-        ),);
-
-        let channel_schema_id: u16 = 0;
-
-        assert_ok!(
-            TestModule::append_class_schema(channel_class_id, vec![], channel_props),
-            channel_schema_id
-        );
-
-        // Episodes:
-
-        let episode_class_id = TestModule::next_class_id();
-        assert_ok!(TestModule::create_class_with_default_permissions(
-            Origin::signed(CLASS_PERMISSIONS_CREATOR1),
-            b"PodcastEpisode".to_vec(),
-            b"A podcast episode".to_vec(),
-        ),);
-
-        let episode_schema_id: u16 = 0;
-
-        assert_ok!(
-            TestModule::append_class_schema(episode_class_id, vec![], episode_props,),
-            episode_schema_id
-        );
-
-        let mut p = PropHelper::new();
-        let channel_entity_id = TestModule::next_entity_id();
-
-        assert_eq!(
-            TestModule::perform_entity_creation(channel_class_id),
-            channel_entity_id
-        );
-
-        assert_ok!(
-            TestModule::add_entity_schema_support(
-                channel_entity_id,
-                channel_schema_id,
-                vec![
-                    // 0
-                    p.next_text_value(b"https://staked.libsyn.com/rss".to_vec()),
-                    // 1
-                    p.next_text_value(b"Staked".to_vec()),
-                    // 2
-                    p.next_text_value(b"Wed, 15 May 2019 20:36:20 +0000".to_vec()),
-                    // 3
-                    p.next_text_value(b"Fri, 23 Aug 2019 11:26:24 +0000".to_vec()),
-                    // 4
-                    p.next_text_value(b"Libsyn WebEngine 2.0".to_vec()),
-                    // 5
-                    p.next_text_value(b"https://twitter.com/staked_podcast".to_vec()),
-                    // 6
-                    p.next_text_value(b"en".to_vec()),
-                    // 7
-                    p.next_value(PropertyValue::Bool(false)),
-                    // 8
-                    p.next_text_value(b"https://twitter.com/staked_podcast".to_vec()),
-                    // 9
-                    p.next_text_value(b"staked@jsgenesis.com (staked@jsgenesis.com)".to_vec()),
-                    // 10
-                    p.next_text_value(b"https://ssl-static.libsyn.com/p/assets/2/d/2/5/2d25eb5fa72739f7/iTunes_Cover.png".to_vec()),
-                    // 11
-                    p.next_text_value(b"Staked".to_vec()),
-                    // 12
-                    p.next_text_value(b"https://twitter.com/staked_podcast".to_vec()),
-                    // 13
-                    p.next_text_value(b"Exploring crypto and blockchain governance.".to_vec()),
-                    // 14
-                    p.next_text_value(b"Staked".to_vec()),
-                    // 15
-                    p.next_text_value(b"crypto,blockchain,governance,staking,bitcoin,ethereum".to_vec()),
-                    // 16
-                    p.next_value(PropertyValue::TextVec(vec![
-                        b"Technology".to_vec(), 
-                        b"Software How-To".to_vec()
-                    ])),
-                    // 17
-                    p.next_text_value(b"https://ssl-static.libsyn.com/p/assets/2/d/2/5/2d25eb5fa72739f7/iTunes_Cover.png".to_vec()),
-                    // 18
-                    p.next_text_value(b"yes".to_vec()),
-                    // 19
-                    p.next_text_value(b"Martin Wessel-Berg".to_vec()),
-                    // 20
-                    p.next_text_value(b"staked@jsgenesis.com".to_vec()),
-                    // 21
-                    p.next_text_value(b"Exploring crypto and blockchain governance.".to_vec()),
-                    // 22
-                    p.next_text_value(b"Exploring crypto and blockchain governance.".to_vec()),
-                    // 23
-                    p.next_text_value(b"episodic".to_vec()),
-                ]
-            )
-        );
-
-        let episode_2_summary = b"<p>In July 2017, the SEC published a report following their <a href=\"https://www.sec.gov/litigation/investreport/34-81207.pdf\">investigation of the DAO</a>. This was significant as it was the first actionable statement from the SEC, giving some insight as to how they interpret this new asset class in light of existing securities laws.</p> <p>Staked is brought to you by Joystream - A user governed media platform.</p>".to_vec();
-
-        p = PropHelper::new();
-        let episode_2_entity_id = TestModule::next_entity_id();
-
-        assert_eq!(
-            TestModule::perform_entity_creation(episode_class_id),
-            episode_2_entity_id
-        );
-
-        assert_ok!(
-            TestModule::add_entity_schema_support(
-                episode_2_entity_id,
-                episode_schema_id,
-                vec![
-                    // 0
-                    p.next_text_value(b"Implications of the DAO Report for Crypto Governance".to_vec()),
-                    // 1
-                    p.next_text_value(b"Implications of the DAO Report for Crypto Governance".to_vec()),
-                    // 2
-                    p.next_text_value(b"Wed, 13 Mar 2019 11:20:33 +0000".to_vec()),
-                    // 3
-                    p.next_text_value(b"1bf862ba81ab4ee797526d98e09ad301".to_vec()),
-                    // 4
-                    p.next_text_value(b"http://staked.libsyn.com/implications-of-the-dao-report-for-crypto-governance".to_vec()),
-                    // 5
-                    p.next_text_value(b"https://ssl-static.libsyn.com/p/assets/2/d/2/5/2d25eb5fa72739f7/iTunes_Cover.png".to_vec()),
-                    // 6
-                    p.next_text_value(episode_2_summary.clone()),
-                    // 7
-                    p.next_text_value(episode_2_summary.clone()),
-                    // 8
-                    p.next_text_value(b"87444374".to_vec()),
-                    // 9
-                    p.next_text_value(b"audio/mpeg".to_vec()),
-                    // 10
-                    p.next_text_value(b"https://traffic.libsyn.com/secure/staked/Staked_-_Ep._2_final_cut.mp3?dest-id=1097396".to_vec()),
-                    // 11
-                    p.next_text_value(b"36:27".to_vec()),
-                    // 12
-                    p.next_text_value(b"yes".to_vec()),
-                    // 13
-                    p.next_text_value(b"governance,crypto,sec,securities,dao,bitcoin,blockchain,ethereum".to_vec()),
-                    // 14
-                    p.next_text_value(b"Part I in a series exploring decentralized governance and securities law".to_vec()),
-                    // 15
-                    p.next_text_value(episode_2_summary),
-                    // 16
-                    p.next_value(PropertyValue::Uint16(1)),
-                    // 17
-                    p.next_value(PropertyValue::Uint16(2)),
-                    // 18
-                    p.next_text_value(b"full".to_vec()),
-                    // 19
-                    p.next_text_value(b"Staked".to_vec()),
-                ]
-            )
-        );
-    })
-}
-
-struct PropHelper {
-    prop_idx: u16,
-}
-
-impl PropHelper {
-    fn new() -> PropHelper {
-        PropHelper { prop_idx: 0 }
-    }
-
-    fn next_value(&mut self, value: PropertyValue) -> ClassPropertyValue {
-        let value = ClassPropertyValue {
-            in_class_index: self.prop_idx,
-            value: value,
-        };
-        self.prop_idx += 1;
-        value
-    }
-
-    fn next_text_value(&mut self, text: Vec<u8>) -> ClassPropertyValue {
-        self.next_value(PropertyValue::Text(text))
-    }
-}

+ 0 - 1474
runtime-modules/versioned-store-permissions/src/lib.rs

@@ -1,1474 +0,0 @@
-// Ensure we're `no_std` when compiling for Wasm.
-#![cfg_attr(not(feature = "std"), no_std)]
-
-use codec::{Codec, Encode, Decode};
-use rstd::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
-use rstd::prelude::*;
-use runtime_primitives::traits::{MaybeSerialize, Member, SimpleArithmetic};
-use srml_support::{decl_module, decl_storage, dispatch, ensure, Parameter};
-use system;
-
-#[cfg(feature = "std")]
-pub use serde::{Deserialize, Serialize};
-
-// EntityId, ClassId -> should be configured on versioned_store_permissions::Trait
-
-mod constraint;
-mod credentials;
-mod mock;
-mod operations;
-mod permissions;
-mod tests;
-mod example;
-mod errors;
-
-pub use constraint::*;
-pub use credentials::*;
-pub use operations::*;
-pub use permissions::*;
-pub use errors::*;
-
-pub trait Trait: system::Trait {
-
-    /// Type that represents an actor or group of actors in the system.
-    type Credential: Parameter
-        + Member
-        + SimpleArithmetic
-        + Codec
-        + Default
-        + Copy
-        + Clone
-        + MaybeSerialize
-        + Eq
-        + PartialEq
-        + Ord;
-
-    /// External type for checking if an account has specified credential.
-    type CredentialChecker: CredentialChecker<Self>;
-
-    /// External type used to check if an account has permission to create new Classes.
-    type CreateClassPermissionsChecker: CreateClassPermissionsChecker<Self>;
-}
-
-/// Trait for checking if an account has specified Credential
-pub trait CredentialChecker<T: Trait> {
-    fn account_has_credential(account: &T::AccountId, credential: T::Credential) -> bool;
-}
-
-/// An implementation where no account has any credential. Effectively
-/// only the system will be able to perform any action on the versioned store.
-impl<T: Trait> CredentialChecker<T> for () {
-    fn account_has_credential(_account: &T::AccountId, _credential: T::Credential) -> bool {
-        false
-    }
-}
-
-/// An implementation that calls into multiple checkers. This allows for multiple modules
-/// to maintain AccountId to Credential mappings.
-impl<T: Trait, X: CredentialChecker<T>, Y: CredentialChecker<T>> CredentialChecker<T> for (X, Y) {
-    fn account_has_credential(account: &T::AccountId, group: T::Credential) -> bool {
-        X::account_has_credential(account, group) || Y::account_has_credential(account, group)
-    }
-}
-
-/// Trait for externally checking if an account can create new classes in the versioned store.
-pub trait CreateClassPermissionsChecker<T: Trait> {
-    fn account_can_create_class_permissions(account: &T::AccountId) -> bool;
-}
-
-/// An implementation that does not permit any account to create classes. Effectively
-/// only the system can create classes.
-impl<T: Trait> CreateClassPermissionsChecker<T> for () {
-    fn account_can_create_class_permissions(_account: &T::AccountId) -> bool {
-        false
-    }
-}
-
-/// Length constraint for input validation
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Debug)]
-pub struct InputValidationLengthConstraint {
-    /// Minimum length
-    pub min: u16,
-
-    /// Difference between minimum length and max length.
-    /// While having max would have been more direct, this
-    /// way makes max < min unrepresentable semantically,
-    /// which is safer.
-    pub max_min_diff: u16,
-}
-
-impl InputValidationLengthConstraint {
-    /// Helper for computing max
-    pub fn max(&self) -> u16 {
-        self.min + self.max_min_diff
-    }
-
-    pub fn ensure_valid(
-        &self,
-        len: usize,
-        too_short_msg: &'static str,
-        too_long_msg: &'static str,
-    ) -> Result<(), &'static str> {
-        let length = len as u16;
-        if length < self.min {
-            Err(too_short_msg)
-        } else if length > self.max() {
-            Err(too_long_msg)
-        } else {
-            Ok(())
-        }
-    }
-}
-
-pub type ClassId = u64;
-pub type EntityId = u64;
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct Class<T: Trait> {
-    /// Permissions for an instance of a Class in the versioned store.
-
-    #[cfg_attr(feature = "std", serde(skip))]
-    class_permissions: ClassPermissionsType<T>,
-    /// All properties that have been used on this class across different class schemas.
-    /// Unlikely to be more than roughly 20 properties per class, often less.
-    /// For Person, think "height", "weight", etc.
-    pub properties: Vec<Property>,
-
-    /// All scehmas that are available for this class, think v0.0 Person, v.1.0 Person, etc.
-    pub schemas: Vec<Schema>,
-
-    pub name: Vec<u8>,
-    pub description: Vec<u8>,
-}
-
-impl <T: Trait> Default for Class <T> {
-    fn default() -> Self {
-        Self {
-            class_permissions: ClassPermissionsType::<T>::default(),
-            properties: vec![],
-            schemas: vec![],
-            name: vec![],
-            description: vec![]
-        }
-    }
-}
-
-impl <T: Trait> Class<T> {
-    fn new(class_permissions: ClassPermissionsType<T>, name: Vec<u8>, description: Vec<u8>) -> Self {
-        Self {
-            class_permissions,
-            properties: vec![],
-            schemas: vec![],
-            name,
-            description
-        }
-    }
-
-    fn is_active_schema(&self, schema_index: u16) -> bool {
-        // Such indexing safe, when length bounds were previously checked
-        self.schemas[schema_index as usize].is_active
-    }
-
-    fn update_schema_status(&mut self, schema_index: u16, schema_status: bool) {
-        // Such indexing safe, when length bounds were previously checked
-        self.schemas[schema_index as usize].is_active = schema_status;
-    }
-
-    fn get_permissions_mut(&mut self) -> &mut ClassPermissionsType<T> {
-        &mut self.class_permissions
-    }
-
-    fn get_permissions(& self) -> &ClassPermissionsType<T> {
-        &self.class_permissions
-    }
-
-    fn refresh_last_permissions_update(&mut self) {
-        self.class_permissions.last_permissions_update = <system::Module<T>>::block_number();
-    }
-}
-
-pub type ClassPermissionsType<T> =
-    ClassPermissions<ClassId, <T as Trait>::Credential, u16, <T as system::Trait>::BlockNumber>;
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Debug)]
-pub struct Entity {
-
-    /// The class id of this entity.
-    pub class_id: ClassId,
-
-    /// What schemas under which this entity of a class is available, think
-    /// v.2.0 Person schema for John, v3.0 Person schema for John
-    /// Unlikely to be more than roughly 20ish, assuming schemas for a given class eventually stableize, or that very old schema are eventually removed.
-    pub in_class_schema_indexes: Vec<u16>, // indices of schema in corresponding class
-
-    /// Values for properties on class that are used by some schema used by this entity!
-    /// Length is no more than Class.properties.
-    pub values: Vec<ClassPropertyValue>,
-    // pub deleted: bool,
-}
-
-/// A schema defines what properties describe an entity
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
-pub struct Schema {
-    /// Indices into properties vector for the corresponding class.
-    pub properties: Vec<u16>,
-    pub is_active: bool
-}
-
-impl Default for Schema {
-    fn default() -> Self {
-        Self {
-            properties: vec![],
-            // Default schema status
-            is_active: true
-        }
-    }
-}
-
-impl Schema {
-    fn new(properties: Vec<u16>) -> Self {
-        Self {
-            properties,
-            // Default schema status
-            is_active: true
-        }
-    }
-}
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Debug)]
-pub struct Property {
-    pub prop_type: PropertyType,
-    pub required: bool,
-    pub name: Vec<u8>,
-    pub description: Vec<u8>,
-}
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
-pub enum PropertyType {
-
-    // Single value:
-    Bool,
-    Uint16,
-    Uint32,
-    Uint64,
-    Int16,
-    Int32,
-    Int64,
-    Text(u16),
-    Reference(ClassId),
-
-    // Vector of values.
-    // The first u16 value is the max length of this vector.
-    BoolVec(u16),
-    Uint16Vec(u16),
-    Uint32Vec(u16),
-    Uint64Vec(u16),
-    Int16Vec(u16),
-    Int32Vec(u16),
-    Int64Vec(u16),
-
-    /// The first u16 value is the max length of this vector.
-    /// The second u16 value is the max length of every text item in this vector.
-    TextVec(u16, u16),
-
-    /// The first u16 value is the max length of this vector.
-    /// The second ClassId value tells that an every element of this vector
-    /// should be of a specific ClassId.
-    ReferenceVec(u16, ClassId),
-    // External(ExternalProperty),
-    // ExternalVec(u16, ExternalProperty),
-}
-
-impl Default for PropertyType {
-    fn default() -> Self {
-        PropertyType::Bool
-    }
-}
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
-pub enum PropertyValue {
-
-    // Single value:
-    Bool(bool),
-    Uint16(u16),
-    Uint32(u32),
-    Uint64(u64),
-    Int16(i16),
-    Int32(i32),
-    Int64(i64),
-    Text(Vec<u8>),
-    Reference(EntityId),
-
-    // Vector of values:
-    BoolVec(Vec<bool>),
-    Uint16Vec(Vec<u16>),
-    Uint32Vec(Vec<u32>),
-    Uint64Vec(Vec<u64>),
-    Int16Vec(Vec<i16>),
-    Int32Vec(Vec<i32>),
-    Int64Vec(Vec<i64>),
-    TextVec(Vec<Vec<u8>>),
-    ReferenceVec(Vec<EntityId>),
-    // External(ExternalPropertyType),
-    // ExternalVec(Vec<ExternalPropertyType>),
-}
-
-impl Default for PropertyValue {
-    fn default() -> Self {
-        PropertyValue::Bool(false)
-    }
-}
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Debug)]
-pub struct ClassPropertyValue {
-    /// Index is into properties vector of class.
-    pub in_class_index: u16,
-
-    /// Value of property with index `in_class_index` in a given class.
-    pub value: PropertyValue,
-}
-
-// Shortcuts for faster readability of match expression:
-use PropertyType as PT;
-use PropertyValue as PV;
-
-decl_storage! {
-    trait Store for Module<T: Trait> as VersionedStorePermissions {
-        /// ClassPermissions of corresponding Classes in the versioned store
-        pub ClassById get(class_by_id) config(): linked_map ClassId => Class<T>;
-
-        pub EntityById get(entity_by_id) config(): map EntityId => Entity;
-
-        /// Owner of an entity in the versioned store. If it is None then it is owned by the system.
-        pub EntityMaintainerByEntityId get(entity_maintainer_by_entity_id): linked_map EntityId => Option<T::Credential>;
-
-        pub NextClassId get(next_class_id) config(): ClassId;
-
-        pub NextEntityId get(next_entity_id) config(): EntityId;
-
-        pub PropertyNameConstraint get(property_name_constraint)
-            config(): InputValidationLengthConstraint;
-
-        pub PropertyDescriptionConstraint get(property_description_constraint)
-            config(): InputValidationLengthConstraint;
-
-        pub ClassNameConstraint get(class_name_constraint)
-            config(): InputValidationLengthConstraint;
-
-        pub ClassDescriptionConstraint get(class_description_constraint)
-            config(): InputValidationLengthConstraint;
-        }
-}
-
-decl_module! {
-    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
-
-
-        /// Sets the admins for a class
-        fn set_class_admins(
-            origin,
-            class_id: ClassId,
-            admins: CredentialSet<T::Credential>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                None,
-                Self::is_system, // root origin
-                class_id,
-                |class_permissions| {
-                    class_permissions.admins = admins;
-                    Ok(())
-                }
-            )
-        }
-
-        // Methods for updating concrete permissions
-
-        fn set_class_entity_permissions(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            entity_permissions: EntityPermissions<T::Credential>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                with_credential,
-                ClassPermissions::is_admin,
-                class_id,
-                |class_permissions| {
-                    class_permissions.entity_permissions = entity_permissions;
-                    Ok(())
-                }
-            )
-        }
-
-        fn set_class_entities_can_be_created(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            can_be_created: bool
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                with_credential,
-                ClassPermissions::is_admin,
-                class_id,
-                |class_permissions| {
-                    class_permissions.entities_can_be_created = can_be_created;
-                    Ok(())
-                }
-            )
-        }
-
-        fn set_class_add_schemas_set(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            credential_set: CredentialSet<T::Credential>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                with_credential,
-                ClassPermissions::is_admin,
-                class_id,
-                |class_permissions| {
-                    class_permissions.add_schemas = credential_set;
-                    Ok(())
-                }
-            )
-        }
-
-        fn set_class_update_schemas_status_set(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            credential_set: CredentialSet<T::Credential>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                with_credential,
-                ClassPermissions::is_admin,
-                class_id,
-                |class_permissions| {
-                    class_permissions.update_schemas_status = credential_set;
-                    Ok(())
-                }
-            )
-        }
-
-        fn set_class_create_entities_set(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            credential_set: CredentialSet<T::Credential>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                with_credential,
-                ClassPermissions::is_admin,
-                class_id,
-                |class_permissions| {
-                    class_permissions.create_entities = credential_set;
-                    Ok(())
-                }
-            )
-        }
-
-        fn set_class_reference_constraint(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            constraint: ReferenceConstraint<ClassId, u16>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::mutate_class_permissions(
-                &raw_origin,
-                with_credential,
-                ClassPermissions::is_admin,
-                class_id,
-                |class_permissions| {
-                    class_permissions.reference_constraint = constraint;
-                    Ok(())
-                }
-            )
-        }
-
-        // Setting a new maintainer for an entity may require having additional constraints.
-        // So for now it is disabled.
-        // pub fn set_entity_maintainer(
-        //     origin,
-        //     entity_id: EntityId,
-        //     new_maintainer: Option<T::Credential>
-        // ) -> dispatch::Result {
-        //     ensure_root(origin)?;
-
-        //     // ensure entity exists in the versioned store
-        //     let _ = Self::get_class_id_by_entity_id(entity_id)?;
-
-        //     <EntityMaintainerByEntityId<T>>::mutate(entity_id, |maintainer| {
-        //         *maintainer = new_maintainer;
-        //     });
-
-        //     Ok(())
-        // }
-
-        // Permissioned proxy calls to versioned store
-
-        pub fn create_class(
-            origin,
-            name: Vec<u8>,
-            description: Vec<u8>,
-            class_permissions: ClassPermissionsType<T>
-        ) -> dispatch::Result {
-            Self::ensure_can_create_class(origin)?;
-
-            Self::ensure_class_name_is_valid(&name)?;
-    
-            Self::ensure_class_description_is_valid(&description)?;
-
-            // is there a need to assert class_id is unique?
-
-            let class_id = NextClassId::get();
-
-            let class = Class::new(class_permissions, name, description);
-
-            <ClassById<T>>::insert(&class_id, class);
-
-            // Increment the next class id:
-            NextClassId::mutate(|n| *n += 1);
-
-            Ok(())
-        }
-
-        pub fn create_class_with_default_permissions(
-            origin,
-            name: Vec<u8>,
-            description: Vec<u8>
-        ) -> dispatch::Result {
-            Self::create_class(origin, name, description, ClassPermissions::default())
-        }
-
-        pub fn add_class_schema(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            existing_properties: Vec<u16>,
-            new_properties: Vec<Property>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::if_class_permissions_satisfied(
-                &raw_origin,
-                with_credential,
-                None,
-                ClassPermissions::can_add_class_schema,
-                class_id,
-                |_class_permissions, _access_level| {
-                    // If a new property points at another class,
-                    // at this point we don't enforce anything about reference constraints
-                    // because of the chicken and egg problem. Instead enforcement is done
-                    // at the time of creating an entity.
-                    let _schema_index = Self::append_class_schema(class_id, existing_properties, new_properties)?;
-                    Ok(())
-                }
-            )
-        }
-
-        pub fn update_class_schema_status(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId,
-            schema_id: u16, // Do not type alias u16!! - u16,
-            is_active: bool
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            Self::if_class_permissions_satisfied(
-                &raw_origin,
-                with_credential,
-                None,
-                ClassPermissions::can_update_schema_status,
-                class_id,
-                |_class_permissions, _access_level| {
-                    // If a new property points at another class,
-                    // at this point we don't enforce anything about reference constraints
-                    // because of the chicken and egg problem. Instead enforcement is done
-                    // at the time of creating an entity.
-                    let _schema_index = Self::complete_class_schema_status_update(class_id, schema_id, is_active)?;
-                    Ok(())
-                }
-            )
-        }
-
-        /// Creates a new entity of type class_id. The maintainer is set to be either None if the origin is root, or the provided credential
-        /// associated with signer.
-        pub fn create_entity(
-            origin,
-            with_credential: Option<T::Credential>,
-            class_id: ClassId
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-            let _entity_id = Self::do_create_entity(&raw_origin, with_credential, class_id)?;
-            Ok(())
-        }
-
-        pub fn add_schema_support_to_entity(
-            origin,
-            with_credential: Option<T::Credential>,
-            as_entity_maintainer: bool,
-            entity_id: EntityId,
-            schema_id: u16, // Do not type alias u16!! - u16,
-            property_values: Vec<ClassPropertyValue>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-            Self::do_add_schema_support_to_entity(&raw_origin, with_credential, as_entity_maintainer, entity_id, schema_id, property_values)
-        }
-
-        pub fn update_entity_property_values(
-            origin,
-            with_credential: Option<T::Credential>,
-            as_entity_maintainer: bool,
-            entity_id: EntityId,
-            property_values: Vec<ClassPropertyValue>
-        ) -> dispatch::Result {
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-            Self::do_update_entity_property_values(&raw_origin, with_credential, as_entity_maintainer, entity_id, property_values)
-        }
-
-        pub fn transaction(origin, operations: Vec<Operation<T::Credential>>) -> dispatch::Result {
-            // This map holds the EntityId of the entity created as a result of executing a CreateEntity Operation
-            // keyed by the indexed of the operation, in the operations vector.
-            let mut entity_created_in_operation: BTreeMap<usize, EntityId> = BTreeMap::new();
-
-            let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-            for (op_index, operation) in operations.into_iter().enumerate() {
-                match operation.operation_type {
-                    OperationType::CreateEntity(create_entity_operation) => {
-                        let entity_id = Self::do_create_entity(&raw_origin, operation.with_credential, create_entity_operation.class_id)?;
-                        entity_created_in_operation.insert(op_index, entity_id);
-                    },
-                    OperationType::UpdatePropertyValues(update_property_values_operation) => {
-                        let entity_id = operations::parametrized_entity_to_entity_id(&entity_created_in_operation, update_property_values_operation.entity_id)?;
-                        let property_values = operations::parametrized_property_values_to_property_values(&entity_created_in_operation, update_property_values_operation.new_parametrized_property_values)?;
-                        Self::do_update_entity_property_values(&raw_origin, operation.with_credential, operation.as_entity_maintainer, entity_id, property_values)?;
-                    },
-                    OperationType::AddSchemaSupportToEntity(add_schema_support_to_entity_operation) => {
-                        let entity_id = operations::parametrized_entity_to_entity_id(&entity_created_in_operation, add_schema_support_to_entity_operation.entity_id)?;
-                        let schema_id = add_schema_support_to_entity_operation.schema_id;
-                        let property_values = operations::parametrized_property_values_to_property_values(&entity_created_in_operation, add_schema_support_to_entity_operation.parametrized_property_values)?;
-                        Self::do_add_schema_support_to_entity(&raw_origin, operation.with_credential, operation.as_entity_maintainer, entity_id, schema_id, property_values)?;
-                    }
-                }
-            }
-
-            Ok(())
-        }
-    }
-}
-
-impl<T: Trait> Module<T> {
-    fn ensure_root_or_signed(
-        origin: T::Origin,
-    ) -> Result<system::RawOrigin<T::AccountId>, &'static str> {
-        match origin.into() {
-            Ok(system::RawOrigin::Root) => Ok(system::RawOrigin::Root),
-            Ok(system::RawOrigin::Signed(account_id)) => Ok(system::RawOrigin::Signed(account_id)),
-            _ => Err("BadOrigin:ExpectedRootOrSigned"),
-        }
-    }
-
-    fn ensure_can_create_class(origin: T::Origin) -> Result<(),  &'static str> {
-        let raw_origin = Self::ensure_root_or_signed(origin)?;
-
-        let can_create_class = match raw_origin {
-            system::RawOrigin::Root => true,
-            system::RawOrigin::Signed(sender) => {
-                T::CreateClassPermissionsChecker::account_can_create_class_permissions(&sender)
-            },
-            _ => false
-        };
-        ensure!(can_create_class, "NotPermittedToCreateClass");
-        Ok(())
-    }
-
-    fn do_create_entity(
-        raw_origin: &system::RawOrigin<T::AccountId>,
-        with_credential: Option<T::Credential>,
-        class_id: ClassId,
-    ) -> Result<EntityId, &'static str> {
-        Self::if_class_permissions_satisfied(
-            raw_origin,
-            with_credential,
-            None,
-            ClassPermissions::can_create_entity,
-            class_id,
-            |_class_permissions, access_level| {
-                let entity_id = Self::perform_entity_creation(class_id);
-
-                // Note: mutating value to None is equivalient to removing the value from storage map
-                <EntityMaintainerByEntityId<T>>::mutate(
-                    entity_id,
-                    |maintainer| match access_level {
-                        AccessLevel::System => *maintainer = None,
-                        AccessLevel::Credential(credential) => *maintainer = Some(*credential),
-                        _ => *maintainer = None,
-                    },
-                );
-
-                Ok(entity_id)
-            },
-        )
-    }
-
-    fn perform_entity_creation(class_id: ClassId) -> EntityId {
-
-        let entity_id = NextEntityId::get();
-
-        let new_entity = Entity {
-            class_id,
-            in_class_schema_indexes: vec![],
-            values: vec![],
-        };
-
-        // Save newly created entity:
-        EntityById::insert(entity_id, new_entity);
-
-        // Increment the next entity id:
-        NextEntityId::mutate(|n| *n += 1);
-
-        entity_id
-    }
-
-    fn do_update_entity_property_values(
-        raw_origin: &system::RawOrigin<T::AccountId>,
-        with_credential: Option<T::Credential>,
-        as_entity_maintainer: bool,
-        entity_id: EntityId,
-        property_values: Vec<ClassPropertyValue>,
-    ) -> dispatch::Result {
-        let class_id = Self::get_class_id_by_entity_id(entity_id)?;
-
-        Self::ensure_internal_property_values_permitted(class_id, &property_values)?;
-
-        let as_entity_maintainer = if as_entity_maintainer {
-            Some(entity_id)
-        } else {
-            None
-        };
-
-        Self::if_class_permissions_satisfied(
-            raw_origin,
-            with_credential,
-            as_entity_maintainer,
-            ClassPermissions::can_update_entity,
-            class_id,
-            |_class_permissions, _access_level| {
-                Self::complete_entity_property_values_update(
-                    entity_id,
-                    property_values,
-                )
-            },
-        )
-    }
-
-    pub fn complete_class_schema_status_update(
-        class_id: ClassId,
-        schema_id: u16, // Do not type alias u16!! - u16,
-        schema_status: bool
-    ) -> dispatch::Result {
-        // Check that schema_id is a valid index of class schemas vector:
-        Self::ensure_class_schema_id_exists(&Self::class_by_id(class_id), schema_id)?;
-        <ClassById<T>>::mutate(class_id, |class| class.update_schema_status(schema_id, schema_status));
-        Ok(())
-    }
-
-    pub fn complete_entity_property_values_update(
-        entity_id: EntityId,
-        new_property_values: Vec<ClassPropertyValue>,
-    ) -> dispatch::Result {
-        Self::ensure_known_entity_id(entity_id)?;
-
-        let (entity, class) = Self::get_entity_and_class(entity_id);
-
-        // Get current property values of an entity as a mutable vector,
-        // so we can update them if new values provided present in new_property_values.
-        let mut updated_values = entity.values;
-        let mut updates_count = 0;
-
-        // Iterate over a vector of new values and update corresponding properties
-        // of this entity if new values are valid.
-        for new_prop_value in new_property_values.iter() {
-            let ClassPropertyValue {
-                in_class_index: id,
-                value: new_value,
-            } = new_prop_value;
-
-            // Try to find a current property value in the entity
-            // by matching its id to the id of a property with an updated value.
-            if let Some(current_prop_value) = updated_values
-                .iter_mut()
-                .find(|prop| *id == prop.in_class_index)
-            {
-                let ClassPropertyValue {
-                    in_class_index: valid_id,
-                    value: current_value,
-                } = current_prop_value;
-
-                // Get class-level information about this property
-                let class_prop = class.properties.get(*valid_id as usize).unwrap();
-
-                // Validate a new property value against the type of this property
-                // and check any additional constraints like the length of a vector
-                // if it's a vector property or the length of a text if it's a text property.
-                Self::ensure_property_value_is_valid(new_value.clone(), class_prop.clone())?;
-
-                // Update a current prop value in a mutable vector, if a new value is valid.
-                *current_value = new_value.clone();
-                updates_count += 1;
-            } else {
-                // Throw an error if a property was not found on entity
-                // by an in-class index of a property update.
-                return Err(ERROR_UNKNOWN_ENTITY_PROP_ID);
-            }
-        }
-
-        // If at least one of the entity property values should be update:
-        if updates_count > 0 {
-            EntityById::mutate(entity_id, |entity| {
-                entity.values = updated_values;
-            });
-        }
-
-        Ok(())
-    }
-
-    fn do_add_schema_support_to_entity(
-        raw_origin: &system::RawOrigin<T::AccountId>,
-        with_credential: Option<T::Credential>,
-        as_entity_maintainer: bool,
-        entity_id: EntityId,
-        schema_id: u16,
-        property_values: Vec<ClassPropertyValue>,
-    ) -> dispatch::Result {
-        // class id of the entity being updated
-        let class_id = Self::get_class_id_by_entity_id(entity_id)?;
-
-        Self::ensure_internal_property_values_permitted(class_id, &property_values)?;
-
-        let as_entity_maintainer = if as_entity_maintainer {
-            Some(entity_id)
-        } else {
-            None
-        };
-
-        Self::if_class_permissions_satisfied(
-            raw_origin,
-            with_credential,
-            as_entity_maintainer,
-            ClassPermissions::can_update_entity,
-            class_id,
-            |_class_permissions, _access_level| {
-                Self::add_entity_schema_support(
-                    entity_id,
-                    schema_id,
-                    property_values,
-                )
-            },
-        )
-    }
-
-    /// Derives the AccessLevel the caller is attempting to act with.
-    /// It expects only signed or root origin.
-    fn derive_access_level(
-        raw_origin: &system::RawOrigin<T::AccountId>,
-        with_credential: Option<T::Credential>,
-        as_entity_maintainer: Option<EntityId>,
-    ) -> Result<AccessLevel<T::Credential>, &'static str> {
-        match raw_origin {
-            system::RawOrigin::Root => Ok(AccessLevel::System),
-            system::RawOrigin::Signed(account_id) => {
-                if let Some(credential) = with_credential {
-                    if T::CredentialChecker::account_has_credential(&account_id, credential) {
-                        if let Some(entity_id) = as_entity_maintainer {
-                            // is entity maintained by system
-                            ensure!(
-                                <EntityMaintainerByEntityId<T>>::exists(entity_id),
-                                "NotEnityMaintainer"
-                            );
-                            // ensure entity maintainer matches
-                            match Self::entity_maintainer_by_entity_id(entity_id) {
-                                Some(maintainer_credential)
-                                    if credential == maintainer_credential =>
-                                {
-                                    Ok(AccessLevel::EntityMaintainer)
-                                }
-                                _ => Err("NotEnityMaintainer"),
-                            }
-                        } else {
-                            Ok(AccessLevel::Credential(credential))
-                        }
-                    } else {
-                        Err("OriginCannotActWithRequestedCredential")
-                    }
-                } else {
-                    Ok(AccessLevel::Unspecified)
-                }
-            }
-            _ => Err("BadOrigin:ExpectedRootOrSigned"),
-        }
-    }
-
-    /// Returns the stored class if exist, error otherwise.
-    fn ensure_class_exists(
-        class_id: ClassId,
-    ) -> Result<Class<T>, &'static str> {
-        ensure!(
-            <ClassById<T>>::exists(class_id),
-            ERROR_CLASS_NOT_FOUND
-        );
-        Ok(Self::class_by_id(class_id))
-    }
-
-    /// Derives the access level of the caller.
-    /// If the predicate passes, the mutate method is invoked.
-    fn mutate_class_permissions<Predicate, Mutate>(
-        raw_origin: &system::RawOrigin<T::AccountId>,
-        with_credential: Option<T::Credential>,
-        // predicate to test
-        predicate: Predicate,
-        // class permissions to perform mutation on if it exists
-        class_id: ClassId,
-        // actual mutation to apply.
-        mutate: Mutate,
-    ) -> dispatch::Result
-    where
-        Predicate:
-            FnOnce(&ClassPermissionsType<T>, &AccessLevel<T::Credential>) -> dispatch::Result,
-        Mutate: FnOnce(&mut ClassPermissionsType<T>) -> dispatch::Result,
-    {
-        let access_level = Self::derive_access_level(raw_origin, with_credential, None)?;
-        let class = Self::ensure_class_exists(class_id)?;
-        predicate(class.get_permissions(), &access_level)?;
-        <ClassById<T>>::mutate(class_id, |inner_class|  {
-            //It is safe to not check for an error here, as result always be  Ok(())
-            let _ = mutate(inner_class.get_permissions_mut());
-            // Refresh last permissions update block number.
-            inner_class.refresh_last_permissions_update();
-        });
-        Ok(())
-    }
-
-    fn is_system(
-        _: &ClassPermissionsType<T>,
-        access_level: &AccessLevel<T::Credential>,
-    ) -> dispatch::Result {
-        if *access_level == AccessLevel::System {
-            Ok(())
-        } else {
-            Err("NotRootOrigin")
-        }
-    }
-
-    /// Derives the access level of the caller.
-    /// If the peridcate passes the callback is invoked. Returns result of the callback
-    /// or error from failed predicate.
-    fn if_class_permissions_satisfied<Predicate, Callback, R>(
-        raw_origin: &system::RawOrigin<T::AccountId>,
-        with_credential: Option<T::Credential>,
-        as_entity_maintainer: Option<EntityId>,
-        // predicate to test
-        predicate: Predicate,
-        // class permissions to test
-        class_id: ClassId,
-        // callback to invoke if predicate passes
-        callback: Callback,
-    ) -> Result<R, &'static str>
-    where
-        Predicate:
-            FnOnce(&ClassPermissionsType<T>, &AccessLevel<T::Credential>) -> dispatch::Result,
-        Callback: FnOnce(
-            &ClassPermissionsType<T>,
-            &AccessLevel<T::Credential>,
-        ) -> Result<R, &'static str>,
-    {
-        let access_level =
-            Self::derive_access_level(raw_origin, with_credential, as_entity_maintainer)?;
-        let class = Self::ensure_class_exists(class_id)?;
-        let class_permissions = class.get_permissions();
-        predicate(class_permissions, &access_level)?;
-        callback(class_permissions, &access_level)
-    }
-
-    fn get_class_id_by_entity_id(entity_id: EntityId) -> Result<ClassId, &'static str> {
-        // use a utility method on versioned_store module
-        ensure!(
-            EntityById::exists(entity_id),
-            "EntityNotFound"
-        );
-        let entity = Self::entity_by_id(entity_id);
-        Ok(entity.class_id)
-    }
-
-    // Ensures property_values of type Internal that point to a class,
-    // the target entity and class exists and constraint allows it.
-    fn ensure_internal_property_values_permitted(
-        source_class_id: ClassId,
-        property_values: &[ClassPropertyValue],
-    ) -> dispatch::Result {
-        for property_value in property_values.iter() {
-            if let PropertyValue::Reference(ref target_entity_id) = property_value.value {
-                // get the class permissions for target class
-                let target_class_id = Self::get_class_id_by_entity_id(*target_entity_id)?;
-                // assert class permissions exists for target class
-                let class = Self::class_by_id(target_class_id);
-
-                // ensure internal reference is permitted
-                match &class.get_permissions().reference_constraint {
-                    ReferenceConstraint::NoConstraint => Ok(()),
-                    ReferenceConstraint::NoReferencingAllowed => {
-                        Err("EntityCannotReferenceTargetEntity")
-                    }
-                    ReferenceConstraint::Restricted(permitted_properties) => {
-                        if permitted_properties.contains(&PropertyOfClass {
-                            class_id: source_class_id,
-                            property_index: property_value.in_class_index,
-                        }) {
-                            Ok(())
-                        } else {
-                            Err("EntityCannotReferenceTargetEntity")
-                        }
-                    }
-                }?;
-            }
-        }
-
-        // if we reach here all Internal properties have passed the constraint check
-        Ok(())
-    }
-    
-        /// Returns an index of a newly added class schema on success.
-        pub fn append_class_schema(
-            class_id: ClassId,
-            existing_properties: Vec<u16>,
-            new_properties: Vec<Property>,
-        ) -> Result<u16, &'static str> {
-            Self::ensure_known_class_id(class_id)?;
-    
-            let non_empty_schema = !existing_properties.is_empty() || !new_properties.is_empty();
-    
-            ensure!(non_empty_schema, ERROR_NO_PROPS_IN_CLASS_SCHEMA);
-    
-            let class = <ClassById<T>>::get(class_id);
-    
-            // TODO Use BTreeSet for prop unique names when switched to Substrate 2.
-            // There is no support for BTreeSet in Substrate 1 runtime.
-            // use rstd::collections::btree_set::BTreeSet;
-            let mut unique_prop_names = BTreeSet::new();
-            for prop in class.properties.iter() {
-                unique_prop_names.insert(prop.name.clone());
-            }
-    
-            for prop in new_properties.iter() {
-                Self::ensure_property_name_is_valid(&prop.name)?;
-                Self::ensure_property_description_is_valid(&prop.description)?;
-    
-                // Check that the name of a new property is unique within its class.
-                ensure!(
-                    !unique_prop_names.contains(&prop.name),
-                    ERROR_PROP_NAME_NOT_UNIQUE_IN_CLASS
-                );
-                unique_prop_names.insert(prop.name.clone());
-            }
-    
-            // Check that existing props are valid indices of class properties vector:
-            let has_unknown_props = existing_properties
-                .iter()
-                .any(|&prop_id| prop_id >= class.properties.len() as u16);
-            ensure!(
-                !has_unknown_props,
-                ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_PROP_INDEX
-            );
-    
-            // Check validity of Internal(ClassId) for new_properties.
-            let has_unknown_internal_id = new_properties.iter().any(|prop| match prop.prop_type {
-                PropertyType::Reference(other_class_id) => !<ClassById<T>>::exists(other_class_id),
-                _ => false,
-            });
-            ensure!(
-                !has_unknown_internal_id,
-                ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_INTERNAL_ID
-            );
-    
-            // Use the current length of schemas in this class as an index
-            // for the next schema that will be sent in a result of this function.
-            let schema_idx = class.schemas.len() as u16;
-    
-            let mut schema = Schema::new(existing_properties);
-    
-            let mut updated_class_props = class.properties;
-            new_properties.into_iter().for_each(|prop| {
-                let prop_id = updated_class_props.len() as u16;
-                updated_class_props.push(prop);
-                schema.properties.push(prop_id);
-            });
-    
-            <ClassById<T>>::mutate(class_id, |class| {
-                class.properties = updated_class_props;
-                class.schemas.push(schema);
-            });
-    
-            Ok(schema_idx)
-        }
-    
-        pub fn add_entity_schema_support(
-            entity_id: EntityId,
-            schema_id: u16,
-            property_values: Vec<ClassPropertyValue>,
-        ) -> dispatch::Result {
-            Self::ensure_known_entity_id(entity_id)?;
-    
-            let (entity, class) = Self::get_entity_and_class(entity_id);
-    
-            // Check that schema_id is a valid index of class schemas vector:
-            Self::ensure_class_schema_id_exists(&class, schema_id)?;
-
-            // Ensure class schema is active
-            Self::ensure_class_schema_is_active(&class, schema_id)?;
-    
-            // Check that schema id is not yet added to this entity:
-            Self::ensure_schema_id_is_not_added(&entity, schema_id)?;
-    
-            let class_schema_opt = class.schemas.get(schema_id as usize);
-            let schema_prop_ids = class_schema_opt.unwrap().properties.clone();
-    
-            let current_entity_values = entity.values.clone();
-            let mut appended_entity_values = entity.values;
-    
-            for &prop_id in schema_prop_ids.iter() {
-                let prop_already_added = current_entity_values
-                    .iter()
-                    .any(|prop| prop.in_class_index == prop_id);
-    
-                if prop_already_added {
-                    // A property is already added to the entity and cannot be updated
-                    // while adding a schema support to this entity.
-                    continue;
-                }
-    
-                let class_prop = class.properties.get(prop_id as usize).unwrap();
-    
-                // If a value was not povided for the property of this schema:
-                match property_values
-                    .iter()
-                    .find(|prop| prop.in_class_index == prop_id)
-                {
-                    Some(new_prop) => {
-                        let ClassPropertyValue {
-                            in_class_index: new_id,
-                            value: new_value,
-                        } = new_prop;
-    
-                        Self::ensure_property_value_is_valid(new_value.clone(), class_prop.clone())?;
-    
-                        appended_entity_values.push(ClassPropertyValue {
-                            in_class_index: *new_id,
-                            value: new_value.clone(),
-                        });
-                    }
-                    None => {
-                        // All required prop values should be are provided
-                        if class_prop.required {
-                            return Err(ERROR_MISSING_REQUIRED_PROP);
-                        }
-                        // Add all missing non required schema prop values as PropertyValue::None
-                        else {
-                            appended_entity_values.push(ClassPropertyValue {
-                                in_class_index: prop_id,
-                                value: PropertyValue::Bool(false),
-                            });
-                        }
-                    }
-                }
-            }
-    
-            EntityById::mutate(entity_id, |entity| {
-                // Add a new schema to the list of schemas supported by this entity.
-                entity.in_class_schema_indexes.push(schema_id);
-    
-                // Update entity values only if new properties have been added.
-                if appended_entity_values.len() > entity.values.len() {
-                    entity.values = appended_entity_values;
-                }
-            });
-    
-            Ok(())
-        }
-    
-        // Commented out for now <- requested by Bedeho.
-        // pub fn delete_entity(entity_id: EntityId) -> dispatch::Result {
-        //     Self::ensure_known_entity_id(entity_id)?;
-    
-        //     let is_deleted = EntityById::get(entity_id).deleted;
-        //     ensure!(!is_deleted, ERROR_ENTITY_ALREADY_DELETED);
-    
-        //     EntityById::mutate(entity_id, |x| {
-        //         x.deleted = true;
-        //     });
-    
-        //     Self::deposit_event(RawEvent::EntityDeleted(entity_id));
-        //     Ok(())
-        // }
-    
-        // Helper functions:
-        // ----------------------------------------------------------------
-    
-        pub fn ensure_known_class_id(class_id: ClassId) -> dispatch::Result {
-            ensure!(<ClassById<T>>::exists(class_id), ERROR_CLASS_NOT_FOUND);
-            Ok(())
-        }
-    
-        pub fn ensure_known_entity_id(entity_id: EntityId) -> dispatch::Result {
-            ensure!(EntityById::exists(entity_id), ERROR_ENTITY_NOT_FOUND);
-            Ok(())
-        }
-
-        pub fn ensure_class_schema_id_exists(class: &Class<T>, schema_id: u16) -> dispatch::Result {
-            ensure!(schema_id < class.schemas.len() as u16, ERROR_UNKNOWN_CLASS_SCHEMA_ID);
-            Ok(())
-        }
-
-        pub fn ensure_class_schema_is_active(class: &Class<T>, schema_id: u16) -> dispatch::Result {
-            ensure!(class.is_active_schema(schema_id), ERROR_CLASS_SCHEMA_NOT_ACTIVE);
-            Ok(())
-        }
-
-        pub fn ensure_schema_id_is_not_added(entity: &Entity, schema_id: u16) -> dispatch::Result {
-            let schema_not_added = entity
-                .in_class_schema_indexes
-                .iter()
-                .position(|x| *x == schema_id)
-                .is_none();
-            ensure!(schema_not_added, ERROR_SCHEMA_ALREADY_ADDED_TO_ENTITY);
-            Ok(())
-        }
-    
-        pub fn ensure_valid_internal_prop(value: PropertyValue, prop: Property) -> dispatch::Result {
-            match (value, prop.prop_type) {
-                (PV::Reference(entity_id), PT::Reference(class_id)) => {
-                    Self::ensure_known_class_id(class_id)?;
-                    Self::ensure_known_entity_id(entity_id)?;
-                    let entity = Self::entity_by_id(entity_id);
-                    ensure!(
-                        entity.class_id == class_id,
-                        ERROR_INTERNAL_RPOP_DOES_NOT_MATCH_ITS_CLASS
-                    );
-                    Ok(())
-                }
-                _ => Ok(()),
-            }
-        }
-    
-        pub fn is_unknown_internal_entity_id(id: PropertyValue) -> bool {
-            if let PropertyValue::Reference(entity_id) = id {
-                !EntityById::exists(entity_id)
-            } else {
-                false
-            }
-        }
-    
-        pub fn get_entity_and_class(entity_id: EntityId) -> (Entity, Class<T>) {
-            let entity = EntityById::get(entity_id);
-            let class = ClassById::get(entity.class_id);
-            (entity, class)
-        }
-    
-        pub fn ensure_property_value_is_valid(
-            value: PropertyValue,
-            prop: Property,
-        ) -> dispatch::Result {
-            Self::ensure_prop_value_matches_its_type(value.clone(), prop.clone())?;
-            Self::ensure_valid_internal_prop(value.clone(), prop.clone())?;
-            Self::validate_max_len_if_text_prop(value.clone(), prop.clone())?;
-            Self::validate_max_len_if_vec_prop(value.clone(), prop.clone())?;
-            Ok(())
-        }
-    
-        pub fn validate_max_len_if_text_prop(value: PropertyValue, prop: Property) -> dispatch::Result {
-            match (value, prop.prop_type) {
-                (PV::Text(text), PT::Text(max_len)) => Self::validate_max_len_of_text(text, max_len),
-                _ => Ok(()),
-            }
-        }
-    
-        pub fn validate_max_len_of_text(text: Vec<u8>, max_len: u16) -> dispatch::Result {
-            if text.len() <= max_len as usize {
-                Ok(())
-            } else {
-                Err(ERROR_TEXT_PROP_IS_TOO_LONG)
-            }
-        }
-    
-        #[rustfmt::skip]
-        pub fn validate_max_len_if_vec_prop(
-            value: PropertyValue,
-            prop: Property,
-        ) -> dispatch::Result {
-    
-            fn validate_vec_len<T>(vec: Vec<T>, max_len: u16) -> bool {
-                vec.len() <= max_len as usize
-            }
-    
-            fn validate_vec_len_ref<T>(vec: &Vec<T>, max_len: u16) -> bool {
-                vec.len() <= max_len as usize
-            }
-    
-            let is_valid_len = match (value, prop.prop_type) {
-                (PV::BoolVec(vec),     PT::BoolVec(max_len))   => validate_vec_len(vec, max_len),
-                (PV::Uint16Vec(vec),   PT::Uint16Vec(max_len)) => validate_vec_len(vec, max_len),
-                (PV::Uint32Vec(vec),   PT::Uint32Vec(max_len)) => validate_vec_len(vec, max_len),
-                (PV::Uint64Vec(vec),   PT::Uint64Vec(max_len)) => validate_vec_len(vec, max_len),
-                (PV::Int16Vec(vec),    PT::Int16Vec(max_len))  => validate_vec_len(vec, max_len),
-                (PV::Int32Vec(vec),    PT::Int32Vec(max_len))  => validate_vec_len(vec, max_len),
-                (PV::Int64Vec(vec),    PT::Int64Vec(max_len))  => validate_vec_len(vec, max_len),
-    
-                (PV::TextVec(vec),     PT::TextVec(vec_max_len, text_max_len)) => {
-                    if validate_vec_len_ref(&vec, vec_max_len) {
-                        for text_item in vec.iter() {
-                            Self::validate_max_len_of_text(text_item.clone(), text_max_len)?;
-                        }
-                        true
-                    } else {
-                        false
-                    }
-                },
-    
-                (PV::ReferenceVec(vec), PT::ReferenceVec(vec_max_len, class_id)) => {
-                    Self::ensure_known_class_id(class_id)?;
-                    if validate_vec_len_ref(&vec, vec_max_len) {
-                        for entity_id in vec.iter() {
-                            Self::ensure_known_entity_id(entity_id.clone())?;
-                            let entity = Self::entity_by_id(entity_id);
-                            ensure!(entity.class_id == class_id, ERROR_INTERNAL_RPOP_DOES_NOT_MATCH_ITS_CLASS);
-                        }
-                        true
-                    } else {
-                        false
-                    }
-                },
-    
-                _ => true
-            };
-    
-            if is_valid_len {
-                Ok(())
-            } else {
-                Err(ERROR_VEC_PROP_IS_TOO_LONG)
-            }
-        }
-    
-        pub fn ensure_prop_value_matches_its_type(
-            value: PropertyValue,
-            prop: Property,
-        ) -> dispatch::Result {
-            if Self::does_prop_value_match_type(value, prop) {
-                Ok(())
-            } else {
-                Err(ERROR_PROP_VALUE_DONT_MATCH_TYPE)
-            }
-        }
-    
-        #[rustfmt::skip]
-        pub fn does_prop_value_match_type(
-            value: PropertyValue,
-            prop: Property,
-        ) -> bool {
-    
-            // A non required property can be updated to None:
-            if !prop.required && value == PV::Bool(false) {
-                return true
-            }
-    
-            match (value, prop.prop_type) {
-    
-                // Single values
-                (PV::Bool(_),     PT::Bool) |
-                (PV::Uint16(_),   PT::Uint16) |
-                (PV::Uint32(_),   PT::Uint32) |
-                (PV::Uint64(_),   PT::Uint64) |
-                (PV::Int16(_),    PT::Int16) |
-                (PV::Int32(_),    PT::Int32) |
-                (PV::Int64(_),    PT::Int64) |
-                (PV::Text(_),     PT::Text(_)) |
-                (PV::Reference(_), PT::Reference(_)) |
-    
-                // Vectors:
-                (PV::BoolVec(_),     PT::BoolVec(_)) |
-                (PV::Uint16Vec(_),   PT::Uint16Vec(_)) |
-                (PV::Uint32Vec(_),   PT::Uint32Vec(_)) |
-                (PV::Uint64Vec(_),   PT::Uint64Vec(_)) |
-                (PV::Int16Vec(_),    PT::Int16Vec(_)) |
-                (PV::Int32Vec(_),    PT::Int32Vec(_)) |
-                (PV::Int64Vec(_),    PT::Int64Vec(_)) |
-                (PV::TextVec(_),     PT::TextVec(_, _)) |
-                (PV::ReferenceVec(_), PT::ReferenceVec(_, _)) => true,
-    
-                // (PV::External(_), PT::External(_)) => true,
-                // (PV::ExternalVec(_), PT::ExternalVec(_, _)) => true,
-                _ => false,
-            }
-        }
-    
-        pub fn ensure_property_name_is_valid(text: &Vec<u8>) -> dispatch::Result {
-            PropertyNameConstraint::get().ensure_valid(
-                text.len(),
-                ERROR_PROPERTY_NAME_TOO_SHORT,
-                ERROR_PROPERTY_NAME_TOO_LONG,
-            )
-        }
-    
-        pub fn ensure_property_description_is_valid(text: &Vec<u8>) -> dispatch::Result {
-            PropertyDescriptionConstraint::get().ensure_valid(
-                text.len(),
-                ERROR_PROPERTY_DESCRIPTION_TOO_SHORT,
-                ERROR_PROPERTY_DESCRIPTION_TOO_LONG,
-            )
-        }
-    
-        pub fn ensure_class_name_is_valid(text: &Vec<u8>) -> dispatch::Result {
-            ClassNameConstraint::get().ensure_valid(
-                text.len(),
-                ERROR_CLASS_NAME_TOO_SHORT,
-                ERROR_CLASS_NAME_TOO_LONG,
-            )
-        }
-    
-        pub fn ensure_class_description_is_valid(text: &Vec<u8>) -> dispatch::Result {
-            ClassDescriptionConstraint::get().ensure_valid(
-                text.len(),
-                ERROR_CLASS_DESCRIPTION_TOO_SHORT,
-                ERROR_CLASS_DESCRIPTION_TOO_LONG,
-            )
-        }
-}

+ 0 - 352
runtime-modules/versioned-store-permissions/src/mock.rs

@@ -1,352 +0,0 @@
-#![cfg(test)]
-
-use crate::*;
-
-use crate::InputValidationLengthConstraint;
-use primitives::H256;
-use runtime_primitives::{
-    testing::Header,
-    traits::{BlakeTwo256, IdentityLookup},
-    Perbill,
-};
-use srml_support::{assert_err, assert_ok, impl_outer_origin, parameter_types};
-
-pub const MEMBER_ONE_WITH_CREDENTIAL_ZERO: u64 = 100;
-pub const MEMBER_TWO_WITH_CREDENTIAL_ZERO: u64 = 101;
-pub const MEMBER_ONE_WITH_CREDENTIAL_ONE: u64 = 102;
-pub const MEMBER_TWO_WITH_CREDENTIAL_ONE: u64 = 103;
-
-pub const UNKNOWN_CLASS_ID: ClassId = 111;
-pub const UNKNOWN_ENTITY_ID: EntityId = 222;
-pub const UNKNOWN_PROP_ID: u16 = 333;
-pub const UNKNOWN_SCHEMA_ID: u16 = 444;
-
-pub const SCHEMA_ID_0: u16 = 0;
-pub const SCHEMA_ID_1: u16 = 1;
-
-pub const PROP_ID_BOOL: u16 = 0;
-pub const PROP_ID_U32: u16 = 1;
-pub const PROP_ID_INTERNAL: u16 = 2;
-
-pub const PRINCIPAL_GROUP_MEMBERS: [[u64; 2]; 2] = [
-    [
-        MEMBER_ONE_WITH_CREDENTIAL_ZERO,
-        MEMBER_TWO_WITH_CREDENTIAL_ZERO,
-    ],
-    [
-        MEMBER_ONE_WITH_CREDENTIAL_ONE,
-        MEMBER_TWO_WITH_CREDENTIAL_ONE,
-    ],
-];
-
-pub const CLASS_PERMISSIONS_CREATOR1: u64 = 200;
-pub const CLASS_PERMISSIONS_CREATOR2: u64 = 300;
-pub const UNAUTHORIZED_CLASS_PERMISSIONS_CREATOR: u64 = 50;
-
-const CLASS_PERMISSIONS_CREATORS: [u64; 2] =
-    [CLASS_PERMISSIONS_CREATOR1, CLASS_PERMISSIONS_CREATOR2];
-
-impl_outer_origin! {
-    pub enum Origin for Runtime {}
-}
-
-// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
-#[derive(Clone, Default, PartialEq, Eq, Debug)]
-pub struct Runtime;
-parameter_types! {
-    pub const BlockHashCount: u64 = 250;
-    pub const MaximumBlockWeight: u32 = 1024;
-    pub const MaximumBlockLength: u32 = 2 * 1024;
-    pub const AvailableBlockRatio: Perbill = Perbill::one();
-    pub const MinimumPeriod: u64 = 5;
-}
-
-impl system::Trait for Runtime {
-    type Origin = Origin;
-    type Index = u64;
-    type BlockNumber = u64;
-    type Call = ();
-    type Hash = H256;
-    type Hashing = BlakeTwo256;
-    type AccountId = u64;
-    type Lookup = IdentityLookup<Self::AccountId>;
-    type Header = Header;
-    type Event = ();
-    type BlockHashCount = BlockHashCount;
-    type MaximumBlockWeight = MaximumBlockWeight;
-    type MaximumBlockLength = MaximumBlockLength;
-    type AvailableBlockRatio = AvailableBlockRatio;
-    type Version = ();
-}
-
-impl timestamp::Trait for Runtime {
-    type Moment = u64;
-    type OnTimestampSet = ();
-    type MinimumPeriod = MinimumPeriod;
-}
-
-impl Trait for Runtime {
-    type Credential = u64;
-    type CredentialChecker = MockCredentialChecker;
-    type CreateClassPermissionsChecker = MockCreateClassPermissionsChecker;
-}
-
-pub struct MockCredentialChecker {}
-
-impl CredentialChecker<Runtime> for MockCredentialChecker {
-    fn account_has_credential(
-        account_id: &<Runtime as system::Trait>::AccountId,
-        credential_id: <Runtime as Trait>::Credential,
-    ) -> bool {
-        if (credential_id as usize) < PRINCIPAL_GROUP_MEMBERS.len() {
-            PRINCIPAL_GROUP_MEMBERS[credential_id as usize]
-                .iter()
-                .any(|id| *id == *account_id)
-        } else {
-            false
-        }
-    }
-}
-
-pub struct MockCreateClassPermissionsChecker {}
-
-impl CreateClassPermissionsChecker<Runtime> for MockCreateClassPermissionsChecker {
-    fn account_can_create_class_permissions(
-        account_id: &<Runtime as system::Trait>::AccountId,
-    ) -> bool {
-        CLASS_PERMISSIONS_CREATORS
-            .iter()
-            .any(|id| *id == *account_id)
-    }
-}
-
-// This function basically just builds a genesis storage key/value store according to
-// our desired mockup.
-
-fn default_versioned_store_genesis_config() -> GenesisConfig<Runtime> {
-    GenesisConfig {
-        class_by_id: vec![],
-        entity_by_id: vec![],
-        next_class_id: 1,
-        next_entity_id: 1,
-        property_name_constraint: InputValidationLengthConstraint {
-            min: 1,
-            max_min_diff: 49,
-        },
-        property_description_constraint: InputValidationLengthConstraint {
-            min: 0,
-            max_min_diff: 500,
-        },
-        class_name_constraint: InputValidationLengthConstraint {
-            min: 1,
-            max_min_diff: 49,
-        },
-        class_description_constraint: InputValidationLengthConstraint {
-            min: 0,
-            max_min_diff: 500,
-        },
-    }
-}
-
-fn build_test_externalities(config: GenesisConfig<Runtime>) -> runtime_io::TestExternalities {
-    let mut t = system::GenesisConfig::default()
-        .build_storage::<Runtime>()
-        .unwrap();
-
-    config.assimilate_storage(&mut t).unwrap();
-
-    t.into()
-}
-
-pub fn with_test_externalities<R, F: FnOnce() -> R>(f: F) -> R {
-    let versioned_store_config = default_versioned_store_genesis_config();
-    build_test_externalities(versioned_store_config).execute_with(f)
-}
-
-impl Property {
-    fn required(&self) -> Property {
-        let mut new_self = self.clone();
-        new_self.required = true;
-        new_self
-    }
-}
-
-pub fn assert_class_props(class_id: ClassId, expected_props: Vec<Property>) {
-    let class = TestModule::class_by_id(class_id);
-    assert_eq!(class.properties, expected_props);
-}
-
-pub fn assert_class_schemas(class_id: ClassId, expected_schema_prop_ids: Vec<Vec<u16>>) {
-    let class = TestModule::class_by_id(class_id);
-    let schemas: Vec<_> = expected_schema_prop_ids
-        .iter()
-        .map(|prop_ids| Schema::new(prop_ids.to_owned()))
-        .collect();
-    assert_eq!(class.schemas, schemas);
-}
-
-pub fn assert_entity_not_found(result: dispatch::Result) {
-    assert_err!(result, ERROR_ENTITY_NOT_FOUND);
-}
-
-pub fn simple_test_schema() -> Vec<Property> {
-    vec![Property {
-        prop_type: PropertyType::Int64,
-        required: false,
-        name: b"field1".to_vec(),
-        description: b"Description field1".to_vec(),
-    }]
-}
-
-pub fn simple_test_entity_property_values() -> Vec<ClassPropertyValue> {
-    vec![ClassPropertyValue {
-        in_class_index: 0,
-        value: PropertyValue::Int64(1337),
-    }]
-}
-
-pub fn create_simple_class(permissions: ClassPermissionsType<Runtime>) -> ClassId {
-    let class_id = TestModule::next_class_id();
-    assert_ok!(TestModule::create_class(
-        Origin::signed(CLASS_PERMISSIONS_CREATOR1),
-        b"class_name_1".to_vec(),
-        b"class_description_1".to_vec(),
-        permissions
-    ));
-    class_id
-}
-
-pub fn create_simple_class_with_default_permissions() -> ClassId {
-    create_simple_class(Default::default())
-}
-
-pub fn class_minimal() -> ClassPermissionsType<Runtime> {
-    ClassPermissions {
-        // remove special permissions for entity maintainers
-        entity_permissions: EntityPermissions {
-            maintainer_has_all_permissions: false,
-            ..Default::default()
-        },
-        ..Default::default()
-    }
-}
-
-pub fn class_minimal_with_admins(
-    admins: Vec<<Runtime as Trait>::Credential>,
-) -> ClassPermissionsType<Runtime> {
-    ClassPermissions {
-        admins: admins.into(),
-        ..class_minimal()
-    }
-}
-
-pub fn next_entity_id() -> EntityId {
-    TestModule::next_entity_id()
-}
-
-pub fn create_entity_of_class(class_id: ClassId) -> EntityId {
-    let entity_id = TestModule::next_entity_id();
-    assert_eq!(TestModule::perform_entity_creation(class_id,), entity_id);
-    entity_id
-}
-
-pub fn create_entity_with_schema_support() -> EntityId {
-    let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-    assert_ok!(TestModule::add_entity_schema_support(
-        entity_id,
-        schema_id,
-        vec![prop_value(PROP_ID_BOOL, PropertyValue::Bool(true))]
-    ));
-    entity_id
-}
-
-pub fn create_class_with_schema() -> (ClassId, u16) {
-    let class_id = create_simple_class_with_default_permissions();
-    let schema_id = TestModule::append_class_schema(
-        class_id,
-        vec![],
-        vec![
-            good_prop_bool().required(),
-            good_prop_u32(),
-            new_internal_class_prop(class_id),
-        ],
-    ).expect("This should not happen");
-    (class_id, schema_id)
-}
-
-pub fn create_class_with_schema_and_entity() -> (ClassId, u16, EntityId) {
-    let (class_id, schema_id) = create_class_with_schema();
-    let entity_id = create_entity_of_class(class_id);
-    (class_id, schema_id, entity_id)
-}
-
-pub fn good_prop_bool() -> Property {
-    Property {
-        prop_type: PropertyType::Bool,
-        required: false,
-        name: b"Name of a bool property".to_vec(),
-        description: b"Description of a bool property".to_vec(),
-    }
-}
-
-pub fn good_prop_u32() -> Property {
-    Property {
-        prop_type: PropertyType::Uint32,
-        required: false,
-        name: b"Name of a u32 property".to_vec(),
-        description: b"Description of a u32 property".to_vec(),
-    }
-}
-
-pub fn good_prop_text() -> Property {
-    Property {
-        prop_type: PropertyType::Text(20),
-        required: false,
-        name: b"Name of a text property".to_vec(),
-        description: b"Description of a text property".to_vec(),
-    }
-}
-
-pub fn new_internal_class_prop(class_id: ClassId) -> Property {
-    Property {
-        prop_type: PropertyType::Reference(class_id),
-        required: false,
-        name: b"Name of a internal property".to_vec(),
-        description: b"Description of a internal property".to_vec(),
-    }
-}
-
-pub fn good_class_name() -> Vec<u8> {
-    b"Name of a class".to_vec()
-}
-
-pub fn good_class_description() -> Vec<u8> {
-    b"Description of a class".to_vec()
-}
-
-pub fn good_props() -> Vec<Property> {
-    vec![good_prop_bool(), good_prop_u32()]
-}
-
-pub fn good_prop_ids() -> Vec<u16> {
-    vec![0, 1]
-}
-
-pub fn bool_prop_value() -> ClassPropertyValue {
-    ClassPropertyValue {
-        in_class_index: 0,
-        value: PropertyValue::Bool(true),
-    }
-}
-
-pub fn prop_value(index: u16, value: PropertyValue) -> ClassPropertyValue {
-    ClassPropertyValue {
-        in_class_index: index,
-        value: value,
-    }
-}
-
-// pub type System = system::Module;
-
-/// Export module on a test runtime
-pub type TestModule = Module<Runtime>;

+ 0 - 135
runtime-modules/versioned-store-permissions/src/operations.rs

@@ -1,135 +0,0 @@
-use crate::{ClassId, ClassPropertyValue, EntityId, PropertyValue};
-use codec::{Decode, Encode};
-use rstd::collections::btree_map::BTreeMap;
-use rstd::prelude::*;
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub enum ParametrizedPropertyValue {
-    /// Same fields as normal PropertyValue
-    PropertyValue(PropertyValue),
-
-    /// This is the index of an operation creating an entity in the transaction/batch operations
-    InternalEntityJustAdded(u32), // should really be usize but it doesn't have Encode/Decode support
-
-    /// Vector of mix of Entities already existing and just added in a recent operation
-    InternalEntityVec(Vec<ParameterizedEntity>),
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub enum ParameterizedEntity {
-    InternalEntityJustAdded(u32),
-    ExistingEntity(EntityId),
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct ParametrizedClassPropertyValue {
-    /// Index is into properties vector of class.
-    pub in_class_index: u16,
-
-    /// Value of property with index `in_class_index` in a given class.
-    pub value: ParametrizedPropertyValue,
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct CreateEntityOperation {
-    pub class_id: ClassId,
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct UpdatePropertyValuesOperation {
-    pub entity_id: ParameterizedEntity,
-    pub new_parametrized_property_values: Vec<ParametrizedClassPropertyValue>,
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct AddSchemaSupportToEntityOperation {
-    pub entity_id: ParameterizedEntity,
-    pub schema_id: u16,
-    pub parametrized_property_values: Vec<ParametrizedClassPropertyValue>,
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub enum OperationType {
-    CreateEntity(CreateEntityOperation),
-    UpdatePropertyValues(UpdatePropertyValuesOperation),
-    AddSchemaSupportToEntity(AddSchemaSupportToEntityOperation),
-}
-
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug)]
-pub struct Operation<Credential> {
-    pub with_credential: Option<Credential>,
-    pub as_entity_maintainer: bool,
-    pub operation_type: OperationType,
-}
-
-pub fn parametrized_entity_to_entity_id(
-    created_entities: &BTreeMap<usize, EntityId>,
-    entity: ParameterizedEntity,
-) -> Result<EntityId, &'static str> {
-    match entity {
-        ParameterizedEntity::ExistingEntity(entity_id) => Ok(entity_id),
-        ParameterizedEntity::InternalEntityJustAdded(op_index_u32) => {
-            let op_index = op_index_u32 as usize;
-            if created_entities.contains_key(&op_index) {
-                let entity_id = created_entities.get(&op_index).unwrap();
-                Ok(*entity_id)
-            } else {
-                Err("EntityNotCreatedByOperation")
-            }
-        }
-    }
-}
-
-pub fn parametrized_property_values_to_property_values(
-    created_entities: &BTreeMap<usize, EntityId>,
-    parametrized_property_values: Vec<ParametrizedClassPropertyValue>,
-) -> Result<Vec<ClassPropertyValue>, &'static str> {
-    let mut class_property_values: Vec<ClassPropertyValue> = vec![];
-
-    for parametrized_class_property_value in parametrized_property_values.into_iter() {
-        let property_value = match parametrized_class_property_value.value {
-            ParametrizedPropertyValue::PropertyValue(value) => value,
-            ParametrizedPropertyValue::InternalEntityJustAdded(
-                entity_created_in_operation_index,
-            ) => {
-                // Verify that referenced entity was indeed created created
-                let op_index = entity_created_in_operation_index as usize;
-                if created_entities.contains_key(&op_index) {
-                    let entity_id = created_entities.get(&op_index).unwrap();
-                    PropertyValue::Reference(*entity_id)
-                } else {
-                    return Err("EntityNotCreatedByOperation");
-                }
-            }
-            ParametrizedPropertyValue::InternalEntityVec(parametrized_entities) => {
-                let mut entities: Vec<EntityId> = vec![];
-
-                for parametrized_entity in parametrized_entities.into_iter() {
-                    match parametrized_entity {
-                        ParameterizedEntity::ExistingEntity(id) => entities.push(id),
-                        ParameterizedEntity::InternalEntityJustAdded(
-                            entity_created_in_operation_index,
-                        ) => {
-                            let op_index = entity_created_in_operation_index as usize;
-                            if created_entities.contains_key(&op_index) {
-                                let entity_id = created_entities.get(&op_index).unwrap();
-                                entities.push(*entity_id);
-                            } else {
-                                return Err("EntityNotCreatedByOperation");
-                            }
-                        }
-                    }
-                }
-
-                PropertyValue::ReferenceVec(entities)
-            }
-        };
-
-        class_property_values.push(ClassPropertyValue {
-            in_class_index: parametrized_class_property_value.in_class_index,
-            value: property_value,
-        });
-    }
-
-    Ok(class_property_values)
-}

+ 0 - 180
runtime-modules/versioned-store-permissions/src/permissions.rs

@@ -1,180 +0,0 @@
-use codec::{Decode, Encode};
-use srml_support::dispatch;
-
-#[cfg(feature = "std")]
-use serde::{Deserialize, Serialize};
-
-use crate::constraint::*;
-use crate::credentials::*;
-
-/// Permissions for an instance of a Class in the versioned store.
-//#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Eq, PartialEq, Clone, Debug)]
-pub struct ClassPermissions<ClassId, Credential, PropertyIndex, BlockNumber>
-where
-    ClassId: Ord,
-    Credential: Ord + Clone,
-    PropertyIndex: Ord,
-{
-    // concrete permissions
-    /// Permissions that are applied to entities of this class, define who in addition to
-    /// root origin can update entities of this class.
-    pub entity_permissions: EntityPermissions<Credential>,
-
-    /// Wether new entities of this class be created or not. Is not enforced for root origin.
-    pub entities_can_be_created: bool,
-
-    /// Who can add new schemas in the versioned store for this class
-    pub add_schemas: CredentialSet<Credential>,
-
-    /// Who can activate/deactivate already existing schemas for this class
-    pub update_schemas_status: CredentialSet<Credential>,
-
-    /// Who can create new entities in the versioned store of this class
-    pub create_entities: CredentialSet<Credential>,
-
-    /// The type of constraint on referencing the class from other entities.
-    pub reference_constraint: ReferenceConstraint<ClassId, PropertyIndex>,
-
-    /// Who (in addition to root origin) can update all concrete permissions.
-    /// The admins can only be set by the root origin, "System".
-    pub admins: CredentialSet<Credential>,
-
-    // Block where permissions were changed
-    pub last_permissions_update: BlockNumber,
-}
-
-impl<ClassId, Credential, PropertyIndex, BlockNumber>
-    ClassPermissions<ClassId, Credential, PropertyIndex, BlockNumber>
-where
-    ClassId: Ord,
-    Credential: Ord + Clone,
-    PropertyIndex: Ord,
-{
-    /// Returns Ok if access_level is root origin or credential is in admins set, Err otherwise
-    pub fn is_admin(
-        class_permissions: &Self,
-        access_level: &AccessLevel<Credential>,
-    ) -> dispatch::Result {
-        match access_level {
-            AccessLevel::System => Ok(()),
-            AccessLevel::Credential(credential) => {
-                if class_permissions.admins.contains(credential) {
-                    Ok(())
-                } else {
-                    Err("NotInAdminsSet")
-                }
-            }
-            AccessLevel::Unspecified => Err("UnspecifiedActor"),
-            AccessLevel::EntityMaintainer => Err("AccessLevel::EntityMaintainer-UsedOutOfPlace"),
-        }
-    }
-
-    pub fn can_add_class_schema(
-        class_permissions: &Self,
-        access_level: &AccessLevel<Credential>,
-    ) -> dispatch::Result {
-        match access_level {
-            AccessLevel::System => Ok(()),
-            AccessLevel::Credential(credential) => {
-                if class_permissions.add_schemas.contains(credential) {
-                    Ok(())
-                } else {
-                    Err("NotInAddSchemasSet")
-                }
-            }
-            AccessLevel::Unspecified => Err("UnspecifiedActor"),
-            AccessLevel::EntityMaintainer => Err("AccessLevel::EntityMaintainer-UsedOutOfPlace"),
-        }
-    }
-
-    pub fn can_update_schema_status(
-        class_permissions: &Self,
-        access_level: &AccessLevel<Credential>,
-    ) -> dispatch::Result {
-        match access_level {
-            AccessLevel::System => Ok(()),
-            AccessLevel::Credential(credential) => {
-                if class_permissions.update_schemas_status.contains(credential) {
-                    Ok(())
-                } else {
-                    Err("NotInUpdateSchemasStatusSet")
-                }
-            }
-            AccessLevel::Unspecified => Err("UnspecifiedActor"),
-            AccessLevel::EntityMaintainer => Err("AccessLevel::EntityMaintainer-UsedOutOfPlace"),
-        }
-    }
-
-    pub fn can_create_entity(
-        class_permissions: &Self,
-        access_level: &AccessLevel<Credential>,
-    ) -> dispatch::Result {
-        match access_level {
-            AccessLevel::System => Ok(()),
-            AccessLevel::Credential(credential) => {
-                if !class_permissions.entities_can_be_created {
-                    Err("EntitiesCannotBeCreated")
-                } else if class_permissions.create_entities.contains(credential) {
-                    Ok(())
-                } else {
-                    Err("NotInCreateEntitiesSet")
-                }
-            }
-            AccessLevel::Unspecified => Err("UnspecifiedActor"),
-            AccessLevel::EntityMaintainer => Err("AccessLevel::EntityMaintainer-UsedOutOfPlace"),
-        }
-    }
-
-    pub fn can_update_entity(
-        class_permissions: &Self,
-        access_level: &AccessLevel<Credential>,
-    ) -> dispatch::Result {
-        match access_level {
-            AccessLevel::System => Ok(()),
-            AccessLevel::Credential(credential) => {
-                if class_permissions
-                    .entity_permissions
-                    .update
-                    .contains(credential)
-                {
-                    Ok(())
-                } else {
-                    Err("CredentialNotInEntityPermissionsUpdateSet")
-                }
-            }
-            AccessLevel::EntityMaintainer => {
-                if class_permissions
-                    .entity_permissions
-                    .maintainer_has_all_permissions
-                {
-                    Ok(())
-                } else {
-                    Err("MaintainerNotGivenAllPermissions")
-                }
-            }
-            _ => Err("UnknownActor"),
-        }
-    }
-}
-
-//#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Clone, Debug, Eq, PartialEq)]
-pub struct EntityPermissions<Credential>
-where
-    Credential: Ord,
-{
-    // Principals permitted to update any entity of the class which this permission is associated with.
-    pub update: CredentialSet<Credential>,
-    /// Wether the designated maintainer (if set) of an entity has permission to update it.
-    pub maintainer_has_all_permissions: bool,
-}
-
-impl<Credential: Ord> Default for EntityPermissions<Credential> {
-    fn default() -> Self {
-        EntityPermissions {
-            maintainer_has_all_permissions: true,
-            update: CredentialSet::new(),
-        }
-    }
-}

+ 0 - 1246
runtime-modules/versioned-store-permissions/src/tests.rs

@@ -1,1246 +0,0 @@
-#![cfg(test)]
-
-use super::*;
-use crate::mock::*;
-use rstd::collections::btree_set::BTreeSet;
-
-use srml_support::{assert_err, assert_ok};
-
-#[test]
-fn create_class_then_entity_with_default_class() {
-    with_test_externalities(|| {
-        // Only authorized accounts can create classes
-        assert_err!(
-            TestModule::create_class_with_default_permissions(
-                Origin::signed(UNAUTHORIZED_CLASS_PERMISSIONS_CREATOR),
-                b"class_name".to_vec(),
-                b"class_description".to_vec(),
-            ),
-            "NotPermittedToCreateClass"
-        );
-
-        let class_id = create_simple_class_with_default_permissions();
-
-        assert!(<ClassById<Runtime>>::exists(class_id));
-
-        assert_eq!(TestModule::next_class_id(), class_id + 1);
-
-        // default class permissions have empty add_schema acl
-        assert_err!(
-            TestModule::add_class_schema(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),
-                Some(0),
-                class_id,
-                vec![],
-                simple_test_schema()
-            ),
-            "NotInAddSchemasSet"
-        );
-
-        // attemt to add class schema to nonexistent class
-        assert_err!(
-            TestModule::add_class_schema(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),
-                Some(0),
-                class_id + 1,
-                vec![],
-                simple_test_schema()
-            ),
-            ERROR_CLASS_NOT_FOUND
-        );
-
-        // give members of GROUP_ZERO permission to add schemas
-        let add_schema_set = CredentialSet::from(vec![0]);
-        assert_ok!(TestModule::set_class_add_schemas_set(
-            Origin::ROOT,
-            None,
-            class_id,
-            add_schema_set
-        ));
-
-        // successfully add a new schema
-        assert_ok!(TestModule::add_class_schema(
-            Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),
-            Some(0),
-            class_id,
-            vec![],
-            simple_test_schema()
-        ));
-
-        // System can always create entities (provided class exists) bypassing any permissions
-        let entity_id_1 = next_entity_id();
-        assert_ok!(TestModule::create_entity(Origin::ROOT, None, class_id,));
-        // entities created by system are "un-owned"
-        assert!(!<EntityMaintainerByEntityId<Runtime>>::exists(entity_id_1));
-        assert_eq!(
-            TestModule::entity_maintainer_by_entity_id(entity_id_1),
-            None
-        );
-
-        assert_eq!(TestModule::next_entity_id(), entity_id_1 + 1);
-
-        // default permissions have empty create_entities set and by default no entities can be created
-        assert_err!(
-            TestModule::create_entity(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-            ),
-            "EntitiesCannotBeCreated"
-        );
-
-        assert_ok!(TestModule::set_class_entities_can_be_created(
-            Origin::ROOT,
-            None,
-            class_id,
-            true
-        ));
-
-        assert_err!(
-            TestModule::create_entity(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-            ),
-            "NotInCreateEntitiesSet"
-        );
-
-        // give members of GROUP_ONE permission to create entities
-        let create_entities_set = CredentialSet::from(vec![1]);
-        assert_ok!(TestModule::set_class_create_entities_set(
-            Origin::ROOT,
-            None,
-            class_id,
-            create_entities_set
-        ));
-
-        let entity_id_2 = next_entity_id();
-        assert_ok!(TestModule::create_entity(
-            Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-            Some(1),
-            class_id,
-        ));
-
-        assert!(<EntityMaintainerByEntityId<Runtime>>::exists(entity_id_2));
-        assert_eq!(
-            TestModule::entity_maintainer_by_entity_id(entity_id_2),
-            Some(1)
-        );
-
-        assert_eq!(TestModule::next_entity_id(), entity_id_2 + 1);
-
-        // Updating entity must be authorized
-        assert_err!(
-            TestModule::add_schema_support_to_entity(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),
-                Some(0),
-                false, // not claiming to be entity maintainer
-                entity_id_2,
-                0, // first schema created
-                simple_test_entity_property_values()
-            ),
-            "CredentialNotInEntityPermissionsUpdateSet"
-        );
-
-        // default permissions give entity maintainer permission to update and delete
-        assert_ok!(TestModule::add_schema_support_to_entity(
-            Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-            Some(1),
-            true, // we are claiming to be the entity maintainer
-            entity_id_2,
-            0,
-            simple_test_entity_property_values()
-        ));
-        assert_ok!(TestModule::update_entity_property_values(
-            Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-            Some(1),
-            true, // we are claiming to be the entity maintainer
-            entity_id_2,
-            simple_test_entity_property_values()
-        ));
-    })
-}
-
-#[test]
-fn cannot_create_class_with_empty_name() {
-    with_test_externalities(|| {
-        let empty_name = vec![];
-        assert_err!(
-            TestModule::create_class_with_default_permissions(
-                Origin::signed(CLASS_PERMISSIONS_CREATOR1),
-                empty_name,
-                good_class_description(),
-            ),
-            ERROR_CLASS_NAME_TOO_SHORT
-        );
-    })
-}
-
-#[test]
-fn create_class_with_empty_description() {
-    with_test_externalities(|| {
-        let empty_description = vec![];
-        assert_ok!(TestModule::create_class_with_default_permissions(
-            Origin::signed(CLASS_PERMISSIONS_CREATOR1),
-            good_class_name(),
-            empty_description
-        ));
-    })
-}
-
-#[test]
-fn cannot_create_entity_with_unknown_class_id() {
-    with_test_externalities(|| {
-        assert_err!(
-            TestModule::create_entity(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                UNKNOWN_CLASS_ID,
-            ),
-            ERROR_CLASS_NOT_FOUND
-        );
-    })
-}
-
-#[test]
-fn class_set_admins() {
-    with_test_externalities(|| {
-        // create a class where all permission sets are empty
-        let class_id = create_simple_class(class_minimal());
-        let class = TestModule::class_by_id(class_id);
-
-        assert!(class.get_permissions().admins.is_empty());
-
-        let credential_set = CredentialSet::from(vec![1]);
-
-        // only root should be able to set admins
-        assert_err!(
-            TestModule::set_class_admins(Origin::signed(1), class_id, credential_set.clone()),
-            "NotRootOrigin"
-        );
-        assert_err!(
-            TestModule::set_class_admins(
-                Origin::NONE, //unsigned inherent?
-                class_id,
-                credential_set.clone()
-            ),
-            "BadOrigin:ExpectedRootOrSigned"
-        );
-
-        // root origin can set admins
-        assert_ok!(TestModule::set_class_admins(
-            Origin::ROOT,
-            class_id,
-            credential_set.clone()
-        ));
-
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().admins, credential_set);
-    })
-}
-
-#[test]
-fn class_set_add_schemas_set() {
-    with_test_externalities(|| {
-        const ADMIN_ACCOUNT: u64 = MEMBER_ONE_WITH_CREDENTIAL_ZERO;
-        // create a class where all permission sets are empty
-        let class_id = create_simple_class(class_minimal_with_admins(vec![0]));
-        let class = TestModule::class_by_id(class_id);
-
-        assert!(class.get_permissions().add_schemas.is_empty());
-
-        let credential_set1 = CredentialSet::from(vec![1, 2]);
-        let credential_set2 = CredentialSet::from(vec![3, 4]);
-
-        // root
-        assert_ok!(TestModule::set_class_add_schemas_set(
-            Origin::ROOT,
-            None,
-            class_id,
-            credential_set1.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().add_schemas, credential_set1);
-
-        // admins
-        assert_ok!(TestModule::set_class_add_schemas_set(
-            Origin::signed(ADMIN_ACCOUNT),
-            Some(0),
-            class_id,
-            credential_set2.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().add_schemas, credential_set2);
-
-        // non-admins
-        assert_err!(
-            TestModule::set_class_add_schemas_set(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-                credential_set2.clone()
-            ),
-            "NotInAdminsSet"
-        );
-    })
-}
-
-#[test]
-fn class_set_class_create_entities_set() {
-    with_test_externalities(|| {
-        const ADMIN_ACCOUNT: u64 = MEMBER_ONE_WITH_CREDENTIAL_ZERO;
-        // create a class where all permission sets are empty
-        let class_id = create_simple_class(class_minimal_with_admins(vec![0]));
-        let class = TestModule::class_by_id(class_id);
-
-        assert!(class.get_permissions().create_entities.is_empty());
-
-        let credential_set1 = CredentialSet::from(vec![1, 2]);
-        let credential_set2 = CredentialSet::from(vec![3, 4]);
-
-        // root
-        assert_ok!(TestModule::set_class_create_entities_set(
-            Origin::ROOT,
-            None,
-            class_id,
-            credential_set1.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().create_entities, credential_set1);
-
-        // admins
-        assert_ok!(TestModule::set_class_create_entities_set(
-            Origin::signed(ADMIN_ACCOUNT),
-            Some(0),
-            class_id,
-            credential_set2.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().create_entities, credential_set2);
-
-        // non-admins
-        assert_err!(
-            TestModule::set_class_create_entities_set(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-                credential_set2.clone()
-            ),
-            "NotInAdminsSet"
-        );
-    })
-}
-
-#[test]
-fn class_set_class_entities_can_be_created() {
-    with_test_externalities(|| {
-        const ADMIN_ACCOUNT: u64 = MEMBER_ONE_WITH_CREDENTIAL_ZERO;
-        // create a class where all permission sets are empty
-        let class_id = create_simple_class(class_minimal_with_admins(vec![0]));
-        let class = TestModule::class_by_id(class_id);
-
-        assert_eq!(class.get_permissions().entities_can_be_created, false);
-
-        // root
-        assert_ok!(TestModule::set_class_entities_can_be_created(
-            Origin::ROOT,
-            None,
-            class_id,
-            true
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().entities_can_be_created, true);
-
-        // admins
-        assert_ok!(TestModule::set_class_entities_can_be_created(
-            Origin::signed(ADMIN_ACCOUNT),
-            Some(0),
-            class_id,
-            false
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(class.get_permissions().entities_can_be_created, false);
-
-        // non-admins
-        assert_err!(
-            TestModule::set_class_entities_can_be_created(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-                true
-            ),
-            "NotInAdminsSet"
-        );
-    })
-}
-
-#[test]
-fn class_set_class_entity_permissions() {
-    with_test_externalities(|| {
-        const ADMIN_ACCOUNT: u64 = MEMBER_ONE_WITH_CREDENTIAL_ZERO;
-        // create a class where all permission sets are empty
-        let class_id = create_simple_class(class_minimal_with_admins(vec![0]));
-        let class = TestModule::class_by_id(class_id);
-
-        assert!(class.get_permissions().entity_permissions.update.is_empty());
-
-        let entity_permissions1 = EntityPermissions {
-            update: CredentialSet::from(vec![1]),
-            maintainer_has_all_permissions: true,
-        };
-
-        //root
-        assert_ok!(TestModule::set_class_entity_permissions(
-            Origin::ROOT,
-            None,
-            class_id,
-            entity_permissions1.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(
-            class.get_permissions().entity_permissions,
-            entity_permissions1
-        );
-
-        let entity_permissions2 = EntityPermissions {
-            update: CredentialSet::from(vec![4]),
-            maintainer_has_all_permissions: true,
-        };
-        //admins
-        assert_ok!(TestModule::set_class_entity_permissions(
-            Origin::signed(ADMIN_ACCOUNT),
-            Some(0),
-            class_id,
-            entity_permissions2.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(
-            class.get_permissions().entity_permissions,
-            entity_permissions2
-        );
-
-        // non admins
-        assert_err!(
-            TestModule::set_class_entity_permissions(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-                entity_permissions2.clone()
-            ),
-            "NotInAdminsSet"
-        );
-    })
-}
-
-#[test]
-fn class_set_class_reference_constraint() {
-    with_test_externalities(|| {
-        const ADMIN_ACCOUNT: u64 = MEMBER_ONE_WITH_CREDENTIAL_ZERO;
-        // create a class where all permission sets are empty
-        let class_id = create_simple_class(class_minimal_with_admins(vec![0]));
-        let class = TestModule::class_by_id(class_id);
-
-        assert_eq!(
-            class.get_permissions().reference_constraint,
-            Default::default()
-        );
-
-        let mut constraints_set = BTreeSet::new();
-        constraints_set.insert(PropertyOfClass {
-            class_id: 1,
-            property_index: 0,
-        });
-        let reference_constraint1 = ReferenceConstraint::Restricted(constraints_set);
-
-        //root
-        assert_ok!(TestModule::set_class_reference_constraint(
-            Origin::ROOT,
-            None,
-            class_id,
-            reference_constraint1.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(
-            class.get_permissions().reference_constraint,
-            reference_constraint1
-        );
-
-        let mut constraints_set = BTreeSet::new();
-        constraints_set.insert(PropertyOfClass {
-            class_id: 2,
-            property_index: 2,
-        });
-        let reference_constraint2 = ReferenceConstraint::Restricted(constraints_set);
-
-        //admins
-        assert_ok!(TestModule::set_class_reference_constraint(
-            Origin::signed(ADMIN_ACCOUNT),
-            Some(0),
-            class_id,
-            reference_constraint2.clone()
-        ));
-        let class = TestModule::class_by_id(class_id);
-        assert_eq!(
-            class.get_permissions().reference_constraint,
-            reference_constraint2
-        );
-
-        // non admins
-        assert_err!(
-            TestModule::set_class_reference_constraint(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-                Some(1),
-                class_id,
-                reference_constraint2.clone()
-            ),
-            "NotInAdminsSet"
-        );
-    })
-}
-
-#[test]
-fn batch_transaction_simple() {
-    with_test_externalities(|| {
-        const CREDENTIAL_ONE: u64 = 1;
-
-        let new_class_id = create_simple_class(ClassPermissions {
-            entities_can_be_created: true,
-            create_entities: vec![CREDENTIAL_ONE].into(),
-            reference_constraint: ReferenceConstraint::NoConstraint,
-            ..Default::default()
-        });
-
-        let new_properties = vec![Property {
-            prop_type: PropertyType::Reference(new_class_id),
-            required: true,
-            name: b"entity".to_vec(),
-            description: b"another entity of same class".to_vec(),
-        }];
-
-        assert_ok!(TestModule::add_class_schema(
-            Origin::ROOT,
-            None,
-            new_class_id,
-            vec![],
-            new_properties
-        ));
-
-        let operations = vec![
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: false,
-                operation_type: OperationType::CreateEntity(CreateEntityOperation {
-                    class_id: new_class_id,
-                }),
-            },
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: true, // in prior operation CREDENTIAL_ONE became the maintainer
-                operation_type: OperationType::AddSchemaSupportToEntity(
-                    AddSchemaSupportToEntityOperation {
-                        entity_id: ParameterizedEntity::InternalEntityJustAdded(0), // index 0 (prior operation)
-                        schema_id: 0,
-                        parametrized_property_values: vec![ParametrizedClassPropertyValue {
-                            in_class_index: 0,
-                            value: ParametrizedPropertyValue::InternalEntityJustAdded(0),
-                        }],
-                    },
-                ),
-            },
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: false,
-                operation_type: OperationType::CreateEntity(CreateEntityOperation {
-                    class_id: new_class_id,
-                }),
-            },
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: true, // in prior operation CREDENTIAL_ONE became the maintainer
-                operation_type: OperationType::UpdatePropertyValues(
-                    UpdatePropertyValuesOperation {
-                        entity_id: ParameterizedEntity::InternalEntityJustAdded(0), // index 0 (prior operation)
-                        new_parametrized_property_values: vec![ParametrizedClassPropertyValue {
-                            in_class_index: 0,
-                            value: ParametrizedPropertyValue::InternalEntityJustAdded(2),
-                        }],
-                    },
-                ),
-            },
-        ];
-
-        let entity_id = next_entity_id();
-
-        assert_ok!(TestModule::transaction(
-            Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-            operations
-        ));
-
-        // two entities created
-        assert!(EntityById::exists(entity_id));
-        assert!(EntityById::exists(entity_id + 1));
-    })
-}
-
-#[test]
-fn batch_transaction_vector_of_entities() {
-    with_test_externalities(|| {
-        const CREDENTIAL_ONE: u64 = 1;
-
-        let new_class_id = create_simple_class(ClassPermissions {
-            entities_can_be_created: true,
-            create_entities: vec![CREDENTIAL_ONE].into(),
-            reference_constraint: ReferenceConstraint::NoConstraint,
-            ..Default::default()
-        });
-
-        let new_properties = vec![Property {
-            prop_type: PropertyType::ReferenceVec(10, new_class_id),
-            required: true,
-            name: b"entities".to_vec(),
-            description: b"vector of entities of same class".to_vec(),
-        }];
-
-        assert_ok!(TestModule::add_class_schema(
-            Origin::ROOT,
-            None,
-            new_class_id,
-            vec![],
-            new_properties
-        ));
-
-        let operations = vec![
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: false,
-                operation_type: OperationType::CreateEntity(CreateEntityOperation {
-                    class_id: new_class_id,
-                }),
-            },
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: false,
-                operation_type: OperationType::CreateEntity(CreateEntityOperation {
-                    class_id: new_class_id,
-                }),
-            },
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: false,
-                operation_type: OperationType::CreateEntity(CreateEntityOperation {
-                    class_id: new_class_id,
-                }),
-            },
-            Operation {
-                with_credential: Some(CREDENTIAL_ONE),
-                as_entity_maintainer: true, // in prior operation CREDENTIAL_ONE became the maintainer
-                operation_type: OperationType::AddSchemaSupportToEntity(
-                    AddSchemaSupportToEntityOperation {
-                        entity_id: ParameterizedEntity::InternalEntityJustAdded(0),
-                        schema_id: 0,
-                        parametrized_property_values: vec![ParametrizedClassPropertyValue {
-                            in_class_index: 0,
-                            value: ParametrizedPropertyValue::InternalEntityVec(vec![
-                                ParameterizedEntity::InternalEntityJustAdded(1),
-                                ParameterizedEntity::InternalEntityJustAdded(2),
-                            ]),
-                        }],
-                    },
-                ),
-            },
-        ];
-
-        let entity_id = next_entity_id();
-
-        assert_ok!(TestModule::transaction(
-            Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ONE),
-            operations
-        ));
-
-        // three entities created
-        assert!(EntityById::exists(entity_id));
-        assert!(EntityById::exists(entity_id + 1));
-        assert!(EntityById::exists(entity_id + 2));
-
-        assert_eq!(
-            EntityById::get(entity_id),
-            Entity {
-                class_id: new_class_id,
-                in_class_schema_indexes: vec![0],
-                values: vec![ClassPropertyValue {
-                    in_class_index: 0,
-                    value: PropertyValue::ReferenceVec(vec![entity_id + 1, entity_id + 2,])
-                }]
-            }
-        );
-    })
-}
-
-// Add class schema
-// --------------------------------------
-
-#[test]
-fn cannot_add_schema_to_unknown_class() {
-    with_test_externalities(|| {
-        assert_err!(
-            TestModule::append_class_schema(UNKNOWN_CLASS_ID, good_prop_ids(), good_props()),
-            ERROR_CLASS_NOT_FOUND
-        );
-    })
-}
-
-#[test]
-fn cannot_add_class_schema_when_no_props_passed() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-        assert_err!(
-            TestModule::append_class_schema(class_id, vec![], vec![]),
-            ERROR_NO_PROPS_IN_CLASS_SCHEMA
-        );
-    })
-}
-
-#[test]
-fn cannot_add_class_schema_when_it_refers_unknown_prop_index_and_class_has_no_props() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-        assert_err!(
-            TestModule::append_class_schema(class_id, vec![UNKNOWN_PROP_ID], vec![]),
-            ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_PROP_INDEX
-        );
-    })
-}
-
-#[test]
-fn cannot_add_class_schema_when_it_refers_unknown_prop_index() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-
-        assert_eq!(
-            TestModule::append_class_schema(class_id, vec![], good_props()),
-            Ok(SCHEMA_ID_0)
-        );
-
-        // Try to add a new schema that is based on one valid prop ids
-        // plus another prop id is unknown on this class.
-        assert_err!(
-            TestModule::append_class_schema(class_id, vec![0, UNKNOWN_PROP_ID], vec![]),
-            ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_PROP_INDEX
-        );
-
-        // Verify that class props and schemas remain unchanged:
-        assert_class_props(class_id, good_props());
-        assert_class_schemas(class_id, vec![good_prop_ids()]);
-    })
-}
-
-#[test]
-fn cannot_add_class_schema_when_it_refers_unknown_internal_id() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-        let bad_internal_prop = new_internal_class_prop(UNKNOWN_CLASS_ID);
-
-        assert_err!(
-            TestModule::append_class_schema(
-                class_id,
-                vec![],
-                vec![good_prop_bool(), bad_internal_prop]
-            ),
-            ERROR_CLASS_SCHEMA_REFERS_UNKNOWN_INTERNAL_ID
-        );
-    })
-}
-
-#[test]
-fn should_add_class_schema_with_internal_class_prop() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-        let internal_class_prop = new_internal_class_prop(class_id);
-
-        // Add first schema with new props.
-        // No other props on the class at this time.
-        assert_eq!(
-            TestModule::append_class_schema(class_id, vec![], vec![internal_class_prop.clone()]),
-            Ok(SCHEMA_ID_0)
-        );
-
-        assert_class_props(class_id, vec![internal_class_prop]);
-        assert_class_schemas(class_id, vec![vec![SCHEMA_ID_0]]);
-    })
-}
-
-#[test]
-fn should_add_class_schema_when_only_new_props_passed() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-
-        // Add first schema with new props.
-        // No other props on the class at this time.
-        assert_eq!(
-            TestModule::append_class_schema(class_id, vec![], good_props()),
-            Ok(SCHEMA_ID_0)
-        );
-
-        assert_class_props(class_id, good_props());
-        assert_class_schemas(class_id, vec![good_prop_ids()]);
-    })
-}
-
-#[test]
-fn should_add_class_schema_when_only_prop_ids_passed() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-
-        // Add first schema with new props.
-        // No other props on the class at this time.
-        assert_eq!(
-            TestModule::append_class_schema(class_id, vec![], good_props()),
-            Ok(SCHEMA_ID_0)
-        );
-
-        // Add a new schema that is based solely on the props ids
-        // of the previously added schema.
-        assert_eq!(
-            TestModule::append_class_schema(class_id, good_prop_ids(), vec![]),
-            Ok(SCHEMA_ID_1)
-        );
-    })
-}
-
-#[test]
-fn cannot_add_class_schema_when_new_props_have_duplicate_names() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-
-        // Add first schema with new props.
-        // No other props on the class at this time.
-        assert_eq!(
-            TestModule::append_class_schema(class_id, vec![], good_props()),
-            Ok(SCHEMA_ID_0)
-        );
-
-        // Add a new schema with not unique property names:
-        assert_err!(
-            TestModule::append_class_schema(class_id, vec![], good_props()),
-            ERROR_PROP_NAME_NOT_UNIQUE_IN_CLASS
-        );
-    })
-}
-
-#[test]
-fn should_add_class_schema_when_both_prop_ids_and_new_props_passed() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-
-        // Add first schema with new props.
-        // No other props on the class at this time.
-        assert_eq!(
-            TestModule::append_class_schema(
-                class_id,
-                vec![],
-                vec![good_prop_bool(), good_prop_u32()]
-            ),
-            Ok(SCHEMA_ID_0)
-        );
-
-        // Add a new schema that is based on some prop ids
-        // added with previous schema plus some new props,
-        // introduced by this new schema.
-        assert_eq!(
-            TestModule::append_class_schema(class_id, vec![1], vec![good_prop_text()]),
-            Ok(SCHEMA_ID_1)
-        );
-
-        assert_class_props(
-            class_id,
-            vec![good_prop_bool(), good_prop_u32(), good_prop_text()],
-        );
-
-        assert_class_schemas(class_id, vec![vec![0, 1], vec![1, 2]]);
-    })
-}
-
-// Update class schema status
-// --------------------------------------
-
-#[test]
-fn update_class_schema_status_success() {
-    with_test_externalities(|| {
-        let (class_id, schema_id) = create_class_with_schema();
-
-        // Check given class schema status before update performed
-        assert_eq!(TestModule::class_by_id(class_id).is_active_schema(schema_id), true);
-
-        // Give members of GROUP_ZERO permission to add schemas
-        let update_schema_set = CredentialSet::from(vec![0]);
-        assert_ok!(TestModule::set_class_update_schemas_status_set(
-            Origin::ROOT,
-            None,
-            class_id,
-            update_schema_set
-        ));
-
-        // Make class schema under given index inactive.
-        assert_ok!(
-            TestModule::update_class_schema_status(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),
-                Some(0),
-                class_id,
-                schema_id,
-                false
-            )
-        );
-
-        // Check given class schema status after update performed
-        assert_eq!(TestModule::class_by_id(class_id).is_active_schema(schema_id), false);
-    })
-}
-
-#[test]
-fn update_class_schema_status_class_not_found() {
-    with_test_externalities(|| {
-        // attemt to update class schema of nonexistent class
-        assert_err!(
-            TestModule::update_class_schema_status(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),                
-                Some(0),
-                UNKNOWN_CLASS_ID,
-                UNKNOWN_SCHEMA_ID,
-                false
-            ),
-            ERROR_CLASS_NOT_FOUND
-        );
-    })
-}
-
-#[test]
-fn update_class_schema_status_not_in_update_class_schema_status_set() {
-    with_test_externalities(|| {
-        let (class_id, schema_id) = create_class_with_schema();
-
-        // Check given class schema status before update performed
-        assert_eq!(TestModule::class_by_id(class_id).is_active_schema(schema_id), true);
-
-        // attemt to update class schema of nonexistent schema
-        assert_err!(
-            TestModule::update_class_schema_status(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),                
-                Some(0),
-                class_id,
-                schema_id,
-                false
-            ),
-            "NotInUpdateSchemasStatusSet"
-        );
-
-        // Check given class schema status after update performed
-        assert_eq!(TestModule::class_by_id(class_id).is_active_schema(schema_id), true);
-    })
-}
-
-#[test]
-fn update_class_schema_status_schema_not_found() {
-    with_test_externalities(|| {
-        let class_id = create_simple_class_with_default_permissions();
-
-        // give members of GROUP_ZERO permission to update schemas
-        let update_schema_set = CredentialSet::from(vec![0]);
-        assert_ok!(TestModule::set_class_update_schemas_status_set(
-            Origin::ROOT,
-            None,
-            class_id,
-            update_schema_set
-        ));
-
-        // attemt to update class schema of nonexistent class
-        assert_err!(
-            TestModule::update_class_schema_status(
-                Origin::signed(MEMBER_ONE_WITH_CREDENTIAL_ZERO),
-                Some(0),
-                class_id,
-                UNKNOWN_SCHEMA_ID,
-                false
-            ),
-            ERROR_UNKNOWN_CLASS_SCHEMA_ID
-        );
-    })
-}
-
-// Add schema support to entity
-// --------------------------------------
-
-#[test]
-fn cannot_add_schema_to_entity_when_entity_not_found() {
-    with_test_externalities(|| {
-        assert_entity_not_found(TestModule::add_entity_schema_support(
-            UNKNOWN_ENTITY_ID,
-            1,
-            vec![],
-        ));
-    })
-}
-
-#[test]
-fn cannot_add_schema_to_entity_when_schema_is_not_active() {
-    with_test_externalities(|| {
-        let (class_id, schema_id, entity_id) = create_class_with_schema_and_entity();
-
-        // Firstly we make class schema under given index inactive.
-        assert_ok!(TestModule::complete_class_schema_status_update(
-            class_id,
-            schema_id,
-            false
-        ));
-
-        // Secondly we try to add support for the same schema.
-        assert_err!(
-            TestModule::add_entity_schema_support(entity_id, schema_id, vec![bool_prop_value()]),
-            ERROR_CLASS_SCHEMA_NOT_ACTIVE
-        );
-    })
-}
-
-#[test]
-fn cannot_add_schema_to_entity_when_schema_already_added_to_entity() {
-    with_test_externalities(|| {
-        let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-
-        // Firstly we just add support for a valid class schema.
-        assert_ok!(TestModule::add_entity_schema_support(
-            entity_id,
-            schema_id,
-            vec![bool_prop_value()]
-        ));
-
-        // Secondly we try to add support for the same schema.
-        assert_err!(
-            TestModule::add_entity_schema_support(entity_id, schema_id, vec![]),
-            ERROR_SCHEMA_ALREADY_ADDED_TO_ENTITY
-        );
-    })
-}
-
-#[test]
-fn cannot_add_schema_to_entity_when_schema_id_is_unknown() {
-    with_test_externalities(|| {
-        let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-        let unknown_schema_id = schema_id + 1;
-        assert_err!(
-            TestModule::add_entity_schema_support(
-                entity_id,
-                unknown_schema_id,
-                vec![prop_value(0, PropertyValue::Bool(false))]
-            ),
-            ERROR_UNKNOWN_CLASS_SCHEMA_ID
-        );
-    })
-}
-
-#[test]
-fn cannot_add_schema_to_entity_when_prop_value_dont_match_type() {
-    with_test_externalities(|| {
-        let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-        assert_err!(
-            TestModule::add_entity_schema_support(
-                entity_id,
-                schema_id,
-                vec![
-                    bool_prop_value(),
-                    prop_value(PROP_ID_U32, PropertyValue::Bool(true))
-                ]
-            ),
-            ERROR_PROP_VALUE_DONT_MATCH_TYPE
-        );
-    })
-}
-
-#[test]
-fn cannot_add_schema_to_entity_when_unknown_internal_entity_id() {
-    with_test_externalities(|| {
-        let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-        assert_err!(
-            TestModule::add_entity_schema_support(
-                entity_id,
-                schema_id,
-                vec![
-                    bool_prop_value(),
-                    prop_value(
-                        PROP_ID_INTERNAL,
-                        PropertyValue::Reference(UNKNOWN_ENTITY_ID)
-                    )
-                ]
-            ),
-            ERROR_ENTITY_NOT_FOUND
-        );
-    })
-}
-
-#[test]
-fn cannot_add_schema_to_entity_when_missing_required_prop() {
-    with_test_externalities(|| {
-        let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-        assert_err!(
-            TestModule::add_entity_schema_support(
-                entity_id,
-                schema_id,
-                vec![prop_value(PROP_ID_U32, PropertyValue::Uint32(456))]
-            ),
-            ERROR_MISSING_REQUIRED_PROP
-        );
-    })
-}
-
-#[test]
-fn should_add_schema_to_entity_when_some_optional_props_provided() {
-    with_test_externalities(|| {
-        let (_, schema_id, entity_id) = create_class_with_schema_and_entity();
-        assert_ok!(TestModule::add_entity_schema_support(
-            entity_id,
-            schema_id,
-            vec![
-                bool_prop_value(),
-                prop_value(PROP_ID_U32, PropertyValue::Uint32(123)),
-                // Note that an optional internal prop is not provided here.
-            ]
-        ));
-
-        let entity = TestModule::entity_by_id(entity_id);
-        assert_eq!(entity.in_class_schema_indexes, [SCHEMA_ID_0]);
-        assert_eq!(
-            entity.values,
-            vec![
-                bool_prop_value(),
-                prop_value(PROP_ID_U32, PropertyValue::Uint32(123)),
-                prop_value(PROP_ID_INTERNAL, PropertyValue::Bool(false)),
-            ]
-        );
-    })
-}
-
-// Update entity properties
-// --------------------------------------
-
-#[test]
-fn cannot_update_entity_props_when_entity_not_found() {
-    with_test_externalities(|| {
-        assert_entity_not_found(TestModule::complete_entity_property_values_update(
-            UNKNOWN_ENTITY_ID,
-            vec![],
-        ));
-    })
-}
-
-#[test]
-fn cannot_update_entity_props_when_prop_value_dont_match_type() {
-    with_test_externalities(|| {
-        let entity_id = create_entity_with_schema_support();
-        assert_err!(
-            TestModule::complete_entity_property_values_update(
-                entity_id,
-                vec![prop_value(PROP_ID_BOOL, PropertyValue::Uint32(1))]
-            ),
-            ERROR_PROP_VALUE_DONT_MATCH_TYPE
-        );
-    })
-}
-
-#[test]
-fn cannot_update_entity_props_when_unknown_internal_entity_id() {
-    with_test_externalities(|| {
-        let entity_id = create_entity_with_schema_support();
-        assert_err!(
-            TestModule::complete_entity_property_values_update(
-                entity_id,
-                vec![prop_value(
-                    PROP_ID_INTERNAL,
-                    PropertyValue::Reference(UNKNOWN_ENTITY_ID)
-                )]
-            ),
-            ERROR_ENTITY_NOT_FOUND
-        );
-    })
-}
-
-#[test]
-fn cannot_update_entity_props_when_unknown_entity_prop_id() {
-    with_test_externalities(|| {
-        let entity_id = create_entity_with_schema_support();
-        assert_err!(
-            TestModule::complete_entity_property_values_update(
-                entity_id,
-                vec![prop_value(UNKNOWN_PROP_ID, PropertyValue::Bool(true))]
-            ),
-            ERROR_UNKNOWN_ENTITY_PROP_ID
-        );
-    })
-}
-
-#[test]
-fn update_entity_props_successfully() {
-    with_test_externalities(|| {
-        let entity_id = create_entity_with_schema_support();
-        assert_eq!(
-            TestModule::entity_by_id(entity_id).values,
-            vec![
-                prop_value(PROP_ID_BOOL, PropertyValue::Bool(true)),
-                prop_value(PROP_ID_U32, PropertyValue::Bool(false)),
-                prop_value(PROP_ID_INTERNAL, PropertyValue::Bool(false)),
-            ]
-        );
-        assert_ok!(TestModule::complete_entity_property_values_update(
-            entity_id,
-            vec![
-                prop_value(PROP_ID_BOOL, PropertyValue::Bool(false)),
-                prop_value(PROP_ID_U32, PropertyValue::Uint32(123)),
-                prop_value(PROP_ID_INTERNAL, PropertyValue::Reference(entity_id)),
-            ]
-        ));
-        assert_eq!(
-            TestModule::entity_by_id(entity_id).values,
-            vec![
-                prop_value(PROP_ID_BOOL, PropertyValue::Bool(false)),
-                prop_value(PROP_ID_U32, PropertyValue::Uint32(123)),
-                prop_value(PROP_ID_INTERNAL, PropertyValue::Reference(entity_id)),
-            ]
-        );
-    })
-}
-
-// TODO test text max len
-
-// TODO test vec max len
-
-// Delete entity
-// --------------------------------------
-
-// #[test]
-// fn delete_entity_successfully() {
-//     with_test_externalities(|| {
-//         let entity_id = create_entity();
-//         assert_ok!(
-//             TestModule::delete_entity(entity_id),
-//             ()
-//         );
-//     })
-// }
-
-// #[test]
-// fn cannot_delete_entity_when_entity_not_found() {
-//     with_test_externalities(|| {
-//         assert_entity_not_found(
-//             TestModule::delete_entity(UNKNOWN_ENTITY_ID)
-//         );
-//     })
-// }
-
-// #[test]
-// fn cannot_delete_already_deleted_entity() {
-//     with_test_externalities(|| {
-//         let entity_id = create_entity();
-//         let _ok = TestModule::delete_entity(entity_id);
-//         assert_err!(
-//             TestModule::delete_entity(entity_id),
-//             ERROR_ENTITY_ALREADY_DELETED
-//         );
-//     })
-// }

+ 4 - 4
runtime/Cargo.toml

@@ -49,7 +49,7 @@ std = [
     'recurringrewards/std',
     'stake/std',
     'hiring/std',
-    'versioned_store_permissions/std',
+    'content_directory/std',
     'common/std',
     'content_working_group/std',
     'governance/std',
@@ -295,10 +295,10 @@ default_features = false
 package = 'substrate-hiring-module'
 path = '../runtime-modules/hiring'
 
-[dependencies.versioned_store_permissions]
+[dependencies.content_directory]
 default_features = false
-package = 'substrate-versioned-store-permissions-module'
-path = '../runtime-modules/versioned-store-permissions'
+package = 'substrate-content-directory-module'
+path = '../runtime-modules/content-directory'
 
 [dependencies.common]
 default_features = false

+ 14 - 14
runtime/src/lib.rs

@@ -400,7 +400,7 @@ pub use governance::election_params::ElectionParameters;
 use governance::{council, election, proposals};
 use membership::members;
 use storage::{data_directory, data_object_storage_registry, data_object_type_registry};
-pub use versioned_store_permissions;
+pub use content_directory;
 
 pub use content_working_group as content_wg;
 mod migration;
@@ -414,7 +414,7 @@ use stake;
 /// Alias for ContentId, used in various places.
 pub type ContentId = primitives::H256;
 
-impl versioned_store_permissions::Trait for Runtime {
+impl content_directory::Trait for Runtime {
     type Credential = Credential;
     type CredentialChecker = (ContentWorkingGroupCredentials, SudoKeyHasAllCredentials);
     type CreateClassPermissionsChecker = ContentLeadOrSudoKeyCanCreateClasses;
@@ -422,10 +422,10 @@ impl versioned_store_permissions::Trait for Runtime {
 
 // Credential Checker that gives the sudo key holder all credentials
 pub struct SudoKeyHasAllCredentials {}
-impl versioned_store_permissions::CredentialChecker<Runtime> for SudoKeyHasAllCredentials {
+impl content_directory::CredentialChecker<Runtime> for SudoKeyHasAllCredentials {
     fn account_has_credential(
         account: &AccountId,
-        _credential: <Runtime as versioned_store_permissions::Trait>::Credential,
+        _credential: <Runtime as content_directory::Trait>::Credential,
     ) -> bool {
         <sudo::Module<Runtime>>::key() == *account
     }
@@ -439,10 +439,10 @@ parameter_types! {
 }
 
 pub struct ContentWorkingGroupCredentials {}
-impl versioned_store_permissions::CredentialChecker<Runtime> for ContentWorkingGroupCredentials {
+impl content_directory::CredentialChecker<Runtime> for ContentWorkingGroupCredentials {
     fn account_has_credential(
         account: &AccountId,
-        credential: <Runtime as versioned_store_permissions::Trait>::Credential,
+        credential: <Runtime as content_directory::Trait>::Credential,
     ) -> bool {
         match credential {
             // Credentials from 0..999 represents groups or more complex requirements
@@ -499,7 +499,7 @@ impl versioned_store_permissions::CredentialChecker<Runtime> for ContentWorkingG
 
 // Allow sudo key holder permission to create classes
 pub struct SudoKeyCanCreateClasses {}
-impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
+impl content_directory::CreateClassPermissionsChecker<Runtime>
     for SudoKeyCanCreateClasses
 {
     fn account_can_create_class_permissions(account: &AccountId) -> bool {
@@ -510,10 +510,10 @@ impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
 // Impl this in the permissions module - can't be done here because
 // neither CreateClassPermissionsChecker or (X, Y) are local types?
 // impl<
-//         T: versioned_store_permissions::Trait,
-//         X: versioned_store_permissions::CreateClassPermissionsChecker<T>,
-//         Y: versioned_store_permissions::CreateClassPermissionsChecker<T>,
-//     > versioned_store_permissions::CreateClassPermissionsChecker<T> for (X, Y)
+//         T: content_directory::Trait,
+//         X: content_directory::CreateClassPermissionsChecker<T>,
+//         Y: content_directory::CreateClassPermissionsChecker<T>,
+//     > content_directory::CreateClassPermissionsChecker<T> for (X, Y)
 // {
 //     fn account_can_create_class_permissions(account: &T::AccountId) -> bool {
 //         X::account_can_create_class_permissions(account)
@@ -522,7 +522,7 @@ impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
 // }
 
 pub struct ContentLeadOrSudoKeyCanCreateClasses {}
-impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
+impl content_directory::CreateClassPermissionsChecker<Runtime>
     for ContentLeadOrSudoKeyCanCreateClasses
 {
     fn account_can_create_class_permissions(account: &AccountId) -> bool {
@@ -533,7 +533,7 @@ impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
 
 // Allow content working group lead to create classes in content directory
 pub struct ContentLeadCanCreateClasses {}
-impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
+impl content_directory::CreateClassPermissionsChecker<Runtime>
     for ContentLeadCanCreateClasses
 {
     fn account_can_create_class_permissions(account: &AccountId) -> bool {
@@ -833,7 +833,7 @@ construct_runtime!(
         DataDirectory: data_directory::{Module, Call, Storage, Event<T>},
         DataObjectStorageRegistry: data_object_storage_registry::{Module, Call, Storage, Event<T>, Config<T>},
         Discovery: discovery::{Module, Call, Storage, Event<T>},
-        VersionedStorePermissions: versioned_store_permissions::{Module, Call, Storage, Config<T>},
+        VersionedStorePermissions: content_directory::{Module, Call, Storage, Config<T>},
         Stake: stake::{Module, Call, Storage},
         Minting: minting::{Module, Call, Storage},
         RecurringRewards: recurringrewards::{Module, Call, Storage},