Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add block number for CTypes #440

Merged
merged 29 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
d215bea
Update toolchain versions
ntn-x2 Nov 29, 2022
96eacc9
Address new clippy warnings
ntn-x2 Nov 29, 2022
479a782
Remove +nightly from CI jobs
ntn-x2 Nov 29, 2022
89089cd
Remove debug rustup show command
ntn-x2 Nov 29, 2022
8875d86
Replace versioned nightly with just nightly
ntn-x2 Nov 29, 2022
805d193
Revert "Replace versioned nightly with just nightly"
ntn-x2 Nov 29, 2022
de04e4b
Use same version as polkadot 0.9.31 release
ntn-x2 Nov 29, 2022
d1b9eff
Address clippy warning
ntn-x2 Nov 29, 2022
b4644f3
Add block number to stored info for CType
ntn-x2 Nov 29, 2022
427d02d
Add CType migration
ntn-x2 Nov 29, 2022
59a5f99
Merge develop into current branch
ntn-x2 Nov 29, 2022
d0706eb
Add new origin and set_block_number function + tests
ntn-x2 Nov 30, 2022
e213ce9
Fix ctype benchmarking
ntn-x2 Nov 30, 2022
1146e6d
Fix all compilation issues
ntn-x2 Nov 30, 2022
137b0db
Add default weights for new extrinsic
ntn-x2 Nov 30, 2022
caf9b24
Final chores
ntn-x2 Nov 30, 2022
25772b5
Fix ctype migration logic
ntn-x2 Nov 30, 2022
ae3b2b3
Fix ctype migration
ntn-x2 Nov 30, 2022
504b386
Final comments
ntn-x2 Nov 30, 2022
713ec9d
Merge branch origin/develop into aa/ctype-block-number
ntn-x2 Dec 13, 2022
ffc79c2
Rename ctype property
ntn-x2 Dec 13, 2022
147536f
Remove unnecessary return type from closure
ntn-x2 Dec 13, 2022
4d92056
Update migration to use new try-runtime features
ntn-x2 Dec 13, 2022
8b4c9dc
Decode all values after migration
ntn-x2 Dec 13, 2022
85f83f4
Merge develop into branch
ntn-x2 Jan 9, 2023
d1e2def
Replace technical committee with democracy
ntn-x2 Jan 9, 2023
0308d38
Merge branch 'develop' into aa/ctype-block-number
weichweich Jan 23, 2023
ec518eb
fix: ctype call index
weichweich Jan 23, 2023
7f4aec3
Merge branch 'develop' into aa/ctype-block-number
weichweich Jan 23, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

32 changes: 26 additions & 6 deletions pallets/attestation/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use frame_support::traits::{Currency, Get};
use frame_system::RawOrigin;
use sp_runtime::traits::Hash;

use ctype::CtypeEntryOf;
use kilt_support::traits::GenerateBenchmarkOrigin;

use crate::*;
Expand All @@ -33,6 +34,7 @@ benchmarks! {
T: core::fmt::Debug,
<T as Config>::EnsureOrigin: GenerateBenchmarkOrigin<T::RuntimeOrigin, T::AccountId, T::AttesterId>,
T: ctype::Config<CtypeCreatorId = T::AttesterId>,
T::BlockNumber: From<u64>
}

add {
Expand All @@ -41,7 +43,10 @@ benchmarks! {
let claim_hash: T::Hash = T::Hashing::hash(b"claim");
let ctype_hash: T::Hash = T::Hash::default();

ctype::Ctypes::<T>::insert(ctype_hash, attester.clone());
ctype::Ctypes::<T>::insert(ctype_hash, CtypeEntryOf::<T> {
creator: attester.clone(),
created_at: 0u64.into()
});
<T as Config>::Currency::make_free_balance_be(&sender, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());

let origin = <T as Config>::EnsureOrigin::generate_origin(sender.clone(), attester.clone());
Expand All @@ -66,7 +71,10 @@ benchmarks! {
let claim_hash: T::Hash = T::Hashing::hash(b"claim");
let ctype_hash: T::Hash = T::Hash::default();

ctype::Ctypes::<T>::insert(ctype_hash, attester.clone());
ctype::Ctypes::<T>::insert(ctype_hash, CtypeEntryOf::<T> {
creator: attester.clone(),
created_at: 0u64.into()
});
<T as Config>::Currency::make_free_balance_be(&sender, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());

let origin = <T as Config>::EnsureOrigin::generate_origin(sender.clone(), attester.clone());
Expand All @@ -92,7 +100,10 @@ benchmarks! {
let claim_hash: T::Hash = T::Hashing::hash(b"claim");
let ctype_hash: T::Hash = T::Hash::default();

ctype::Ctypes::<T>::insert(ctype_hash, attester.clone());
ctype::Ctypes::<T>::insert(ctype_hash, CtypeEntryOf::<T> {
creator: attester.clone(),
created_at: 0u64.into()
});
<T as Config>::Currency::make_free_balance_be(&sender, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());

let origin = <T as Config>::EnsureOrigin::generate_origin(sender.clone(), attester.clone());
Expand All @@ -109,7 +120,10 @@ benchmarks! {
let claim_hash: T::Hash = T::Hashing::hash(b"claim");
let ctype_hash: T::Hash = T::Hash::default();

ctype::Ctypes::<T>::insert(ctype_hash, attester.clone());
ctype::Ctypes::<T>::insert(ctype_hash, CtypeEntryOf::<T> {
creator: attester.clone(),
created_at: 0u64.into()
});
<T as Config>::Currency::make_free_balance_be(&sender, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());

let origin = <T as Config>::EnsureOrigin::generate_origin(sender.clone(), attester);
Expand All @@ -127,7 +141,10 @@ benchmarks! {
let claim_hash: T::Hash = T::Hashing::hash(b"claim");
let ctype_hash: T::Hash = T::Hash::default();

ctype::Ctypes::<T>::insert(ctype_hash, attester.clone());
ctype::Ctypes::<T>::insert(ctype_hash, CtypeEntryOf::<T> {
creator: attester.clone(),
created_at: 0u64.into()
});
<T as Config>::Currency::make_free_balance_be(&deposit_owner_old, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());
<T as Config>::Currency::make_free_balance_be(&deposit_owner_new, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());

Expand All @@ -154,7 +171,10 @@ benchmarks! {
let claim_hash: T::Hash = T::Hashing::hash(b"claim");
let ctype_hash: T::Hash = T::Hash::default();

ctype::Ctypes::<T>::insert(ctype_hash, attester.clone());
ctype::Ctypes::<T>::insert(ctype_hash, CtypeEntryOf::<T> {
creator: attester.clone(),
created_at: 0u64.into()
});
<T as Config>::Currency::make_free_balance_be(&deposit_owner, <T as Config>::Deposit::get() + <T as Config>::Deposit::get());

let origin = <T as Config>::EnsureOrigin::generate_origin(deposit_owner.clone(), attester.clone());
Expand Down
12 changes: 10 additions & 2 deletions pallets/attestation/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,16 @@ pub fn insert_attestation<T: Config>(claim_hash: ClaimHashOf<T>, details: Attest
/// Mocks that are only used internally
#[cfg(test)]
pub(crate) mod runtime {
use ctype::CtypeCreatorOf;
use frame_support::{parameter_types, weights::constants::RocksDbWeight};
use frame_system::EnsureSigned;
use sp_core::{ed25519, sr25519, Pair};
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify},
MultiSignature, MultiSigner,
};

use ctype::{CtypeCreatorOf, CtypeEntryOf};
use kilt_support::mock::{mock_origin, SubjectId};

use super::*;
Expand Down Expand Up @@ -267,6 +268,7 @@ pub(crate) mod runtime {
type CtypeCreatorId = SubjectId;
type EnsureOrigin = mock_origin::EnsureDoubleOrigin<AccountId, Self::CtypeCreatorId>;
type OriginSuccess = mock_origin::DoubleOrigin<AccountId, Self::CtypeCreatorId>;
type OverarchingOrigin = EnsureSigned<AccountId>;
type RuntimeEvent = ();
type WeightInfo = ();

Expand Down Expand Up @@ -366,7 +368,13 @@ pub(crate) mod runtime {

ext.execute_with(|| {
for ctype in self.ctypes {
ctype::Ctypes::<Test>::insert(ctype.0, ctype.1.clone());
ctype::Ctypes::<Test>::insert(
ctype.0,
CtypeEntryOf::<Test> {
creator: ctype.1.clone(),
created_at: System::block_number(),
},
);
}

for (claim_hash, details) in self.attestations {
Expand Down
29 changes: 26 additions & 3 deletions pallets/ctype/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite};
use frame_support::{
sp_runtime::traits::Hash,
traits::{Currency, Get},
traits::{Currency, EnsureOrigin, Get},
};
use sp_std::{
convert::{TryFrom, TryInto},
Expand All @@ -40,6 +40,7 @@ benchmarks! {
<<T as Config>::Currency as Currency<AccountIdOf<T>>>::Balance: TryFrom<usize>,
<<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance as TryFrom<usize>>::Error: Debug,
T::EnsureOrigin: GenerateBenchmarkOrigin<T::RuntimeOrigin, T::AccountId, T::CtypeCreatorId>,
T::BlockNumber: From<u64>,
}

add {
Expand All @@ -57,10 +58,32 @@ benchmarks! {

}: _<T::RuntimeOrigin>(origin, ctype)
verify {
let stored_ctype_creator: T::CtypeCreatorId = Ctypes::<T>::get(ctype_hash).expect("CType hash should be present on chain.");
let stored_ctype_entry = Ctypes::<T>::get(ctype_hash).expect("CType hash should be present on chain.");

// Verify the CType has the right owner
assert_eq!(stored_ctype_creator, did);
assert_eq!(stored_ctype_entry.creator, did);
}

set_block_number {
let caller = account("caller", 0, SEED);
let did: T::CtypeCreatorId = account("did", 0, SEED);

let ctype: Vec<u8> = (0u8..u8::MAX).cycle().take(MAX_CTYPE_SIZE.try_into().unwrap()).collect();
wischli marked this conversation as resolved.
Show resolved Hide resolved
let ctype_hash = <T as frame_system::Config>::Hashing::hash(&ctype[..]);
let new_block_number = 500u64.into();

let initial_balance = <T as Config>::Fee::get() * ctype.len().try_into().unwrap() + <T as Config>::Currency::minimum_balance();
<T as Config>::Currency::make_free_balance_be(&caller, initial_balance);
let origin = T::EnsureOrigin::generate_origin(caller, did);
Pallet::<T>::add(origin, ctype).expect("CType creation should not fail.");
let overarching_origin = T::OverarchingOrigin::successful_origin();

}: _<T::RuntimeOrigin>(overarching_origin, ctype_hash, new_block_number)
verify {
let stored_ctype_entry = Ctypes::<T>::get(ctype_hash).expect("CType hash should be present on chain.");

// Verify the CType has the right block number
assert_eq!(stored_ctype_entry.created_at, new_block_number);
}
}

Expand Down
12 changes: 12 additions & 0 deletions pallets/ctype/src/ctype_entry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::RuntimeDebug;
use scale_info::TypeInfo;

/// Creation details of a CType.
#[derive(Encode, Decode, RuntimeDebug, MaxEncodedLen, Eq, PartialEq, TypeInfo)]
pub struct CtypeEntry<Creator, BlockNumber> {
/// Identifier of the creator.
pub creator: Creator,
/// Block number in which the creation tx was dispatched.
pub created_at: BlockNumber,
}
15 changes: 14 additions & 1 deletion pallets/ctype/src/default_weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//! Autogenerated weights for ctype
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-11-07, STEPS: {{cmd.steps}}\, REPEAT: {{cmd.repeat}}\, LOW RANGE: {{cmd.lowest_range_values}}\, HIGH RANGE: {{cmd.highest_range_values}}\
//! DATE: 2022-11-30, STEPS: {{cmd.steps}}\, REPEAT: {{cmd.repeat}}\, LOW RANGE: {{cmd.lowest_range_values}}\, HIGH RANGE: {{cmd.highest_range_values}}\
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024

// Executed Command:
Expand Down Expand Up @@ -48,6 +48,7 @@ use sp_std::marker::PhantomData;
/// Weight functions needed for ctype.
pub trait WeightInfo {
fn add(l: u32, ) -> Weight;
fn set_block_number() -> Weight;
}

/// Weights for ctype using the Substrate node and recommended hardware.
Expand All @@ -63,6 +64,12 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
.saturating_add(T::DbWeight::get().reads(3 as u64))
.saturating_add(T::DbWeight::get().writes(3 as u64))
}
// Storage: Ctype Ctypes (r:1 w:1)
fn set_block_number() -> Weight {
Weight::from_ref_time(20_685_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
}

// For backwards compatibility and tests
Expand All @@ -77,4 +84,10 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3 as u64))
.saturating_add(RocksDbWeight::get().writes(3 as u64))
}
// Storage: Ctype Ctypes (r:1 w:1)
fn set_block_number() -> Weight {
Weight::from_ref_time(20_685_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
}
47 changes: 44 additions & 3 deletions pallets/ctype/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

#![cfg_attr(not(feature = "std"), no_std)]

pub mod ctype_entry;
pub mod default_weights;

#[cfg(any(feature = "mock", test))]
Expand Down Expand Up @@ -69,12 +70,16 @@ pub mod pallet {
use sp_runtime::{traits::Saturating, SaturatedConversion};
use sp_std::vec::Vec;

use crate::ctype_entry::CtypeEntry;

/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);

/// Type of a CType hash.
pub type CtypeHashOf<T> = <T as frame_system::Config>::Hash;

pub type CtypeEntryOf<T> = CtypeEntry<<T as Config>::CtypeCreatorId, BlockNumberFor<T>>;

/// Type of a CType creator.
pub type CtypeCreatorOf<T> = <T as Config>::CtypeCreatorId;

Expand All @@ -86,6 +91,7 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config {
type EnsureOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin, Success = Self::OriginSuccess>;
type OverarchingOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
type OriginSuccess: CallSources<AccountIdOf<Self>, CtypeCreatorOf<Self>>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type Currency: Currency<AccountIdOf<Self>>;
Expand All @@ -105,17 +111,21 @@ pub mod pallet {

/// CTypes stored on chain.
///
/// It maps from a CType hash to its creator.
/// It maps from a CType hash to its creator and block number in which it
/// was created.
#[pallet::storage]
#[pallet::getter(fn ctypes)]
pub type Ctypes<T> = StorageMap<_, Blake2_128Concat, CtypeHashOf<T>, CtypeCreatorOf<T>>;
pub type Ctypes<T> = StorageMap<_, Blake2_128Concat, CtypeHashOf<T>, CtypeEntryOf<T>>;

#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A new CType has been created.
/// \[creator identifier, CType hash\]
CTypeCreated(CtypeCreatorOf<T>, CtypeHashOf<T>),
/// Information about a CType has been updated.
/// \[CType hash\]
CTypeUpdated(CtypeHashOf<T>),
}

#[pallet::error]
Expand Down Expand Up @@ -177,11 +187,42 @@ pub mod pallet {

T::FeeCollector::on_unbalanced(imbalance);
log::debug!("Creating CType with hash {:?} and creator {:?}", hash, creator);
Ctypes::<T>::insert(hash, creator.clone());
Ctypes::<T>::insert(
hash,
CtypeEntryOf::<T> {
creator: creator.clone(),
created_at: frame_system::Pallet::<T>::block_number(),
},
);

Self::deposit_event(Event::CTypeCreated(creator, hash));

Ok(())
}

/// Set the creation block number for a given CType, if found.
///
/// Emits `CTypeUpdated`.
#[pallet::call_index(1)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::set_block_number())]
pub fn set_block_number(
origin: OriginFor<T>,
ctype_hash: CtypeHashOf<T>,
block_number: BlockNumberFor<T>,
) -> DispatchResult {
T::OverarchingOrigin::ensure_origin(origin)?;
Ctypes::<T>::try_mutate(ctype_hash, |ctype_entry| {
if let Some(ctype_entry) = ctype_entry {
ctype_entry.created_at = block_number;
Ok(())
} else {
Err(Error::<T>::CTypeNotFound)
}
})?;

Self::deposit_event(Event::CTypeUpdated(ctype_hash));

Ok(())
}
}
}
Loading