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

411 Allow calling extrinsics of clients-info crate from authorized accounts #418

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Binary file modified clients/runtime/metadata-standalone.scale
Binary file not shown.
38 changes: 36 additions & 2 deletions pallets/clients-info/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,64 @@ use super::Pallet as ClientsInfo;
#[benchmarks]
pub mod benchmarks {
use super::*;
use frame_benchmarking::{account, whitelisted_caller};

#[benchmark]
fn set_current_client_release(n: Linear<0, 255>, u: Linear<0, 255>) {
let caller: T::AccountId = whitelisted_caller();
AuthorizedAccounts::<T>::insert(caller.clone(), ());

let name = BoundedVec::try_from(vec![0; n as usize]).unwrap();
let uri = BoundedVec::try_from(vec![0; u as usize]).unwrap();
let client_release = ClientRelease { uri, checksum: Default::default() };

#[extrinsic_call]
_(RawOrigin::Root, name.clone(), client_release.clone());
_(RawOrigin::Signed(caller), name.clone(), client_release.clone());

assert_eq!(CurrentClientReleases::<T>::get(name), Some(client_release));
}

#[benchmark]
fn set_pending_client_release(n: Linear<0, 255>, u: Linear<0, 255>) {
let caller: T::AccountId = whitelisted_caller();
AuthorizedAccounts::<T>::insert(caller.clone(), ());

let name = BoundedVec::try_from(vec![0; n as usize]).unwrap();
let uri = BoundedVec::try_from(vec![0; u as usize]).unwrap();
let client_release = ClientRelease { uri, checksum: Default::default() };

#[extrinsic_call]
_(RawOrigin::Root, name.clone(), client_release.clone());
_(RawOrigin::Signed(caller), name.clone(), client_release.clone());

assert_eq!(PendingClientReleases::<T>::get(name), Some(client_release));
}

#[benchmark]
fn authorize_account() {
let caller: T::AccountId = whitelisted_caller();
let account: T::AccountId = account("test", 2, 2);

AuthorizedAccounts::<T>::insert(caller.clone(), ());

#[extrinsic_call]
_(RawOrigin::Signed(caller), account.clone());

assert!(AuthorizedAccounts::<T>::get(account).is_some());
}

#[benchmark]
fn deauthorize_account() {
let caller: T::AccountId = whitelisted_caller();
let account: T::AccountId = account("test", 2, 2);

AuthorizedAccounts::<T>::insert(caller.clone(), ());
AuthorizedAccounts::<T>::insert(account.clone(), ());

#[extrinsic_call]
_(RawOrigin::Signed(caller), account.clone());

assert!(AuthorizedAccounts::<T>::get(account).is_none());
}

impl_benchmark_test_suite!(ClientsInfo, crate::mock::ExtBuilder::build(), crate::mock::Test);
}
130 changes: 64 additions & 66 deletions pallets/clients-info/src/default_weights.rs
Original file line number Diff line number Diff line change
@@ -1,108 +1,106 @@

//! Autogenerated weights for clients_info
//! Autogenerated weights for `clients_info`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-09-13, STEPS: `100`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2023-10-13, STEPS: `20`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `pop-os`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz`
//! HOSTNAME: `Bs-MacBook-Pro.local`, CPU: `<UNKNOWN>`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024

// Executed Command:
// ./target/release/spacewalk-standalone
// benchmark
// pallet
// --chain=dev
// --chain
// dev
// --pallet=clients-info
// --extrinsic=*
// --steps=100
// --repeat=10
// --wasm-execution=compiled
// --output=pallets/clients-info/src/default_weights.rs
// --template=./.maintain/frame-weight-template.hbs
// --extrinsic
// *
// --steps
// 20
// --repeat
// 10
// --output
// default_weights.rs

#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]

use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use core::marker::PhantomData;
use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;

/// Weight functions needed for clients_info.
pub trait WeightInfo {
fn set_current_client_release(n: u32, u: u32, ) -> Weight;
fn set_pending_client_release(n: u32, u: u32, ) -> Weight;
fn authorize_account() -> Weight;
fn deauthorize_account() -> Weight;
}

/// Weights for clients_info using the Substrate node and recommended hardware.
/// Weight functions for `clients_info`.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: ClientsInfo AuthorizedAccounts (r:1 w:0)
/// Proof: ClientsInfo AuthorizedAccounts (max_values: None, max_size: Some(48), added: 2523, mode: MaxEncodedLen)
/// Storage: ClientsInfo CurrentClientReleases (r:0 w:1)
/// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen)
/// The range of component `n` is `[0, 255]`.
/// The range of component `u` is `[0, 255]`.
fn set_current_client_release(n: u32, u: u32, ) -> Weight {
fn set_current_client_release(n: u32, _u: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 7_607_000 picoseconds.
Weight::from_parts(9_560_259, 0)
// Standard Error: 845
.saturating_add(Weight::from_parts(2_586, 0).saturating_mul(n.into()))
// Standard Error: 845
.saturating_add(Weight::from_parts(689, 0).saturating_mul(u.into()))
.saturating_add(T::DbWeight::get().writes(1_u64))
// Measured: `77`
// Estimated: `3513`
// Minimum execution time: 6_000_000 picoseconds.
Weight::from_parts(6_960_200, 0)
.saturating_add(Weight::from_parts(0, 3513))
// Standard Error: 394
.saturating_add(Weight::from_parts(3_078, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: ClientsInfo AuthorizedAccounts (r:1 w:0)
/// Proof: ClientsInfo AuthorizedAccounts (max_values: None, max_size: Some(48), added: 2523, mode: MaxEncodedLen)
/// Storage: ClientsInfo PendingClientReleases (r:0 w:1)
/// Proof: ClientsInfo PendingClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen)
/// The range of component `n` is `[0, 255]`.
/// The range of component `u` is `[0, 255]`.
fn set_pending_client_release(n: u32, u: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 7_557_000 picoseconds.
Weight::from_parts(9_238_573, 0)
// Standard Error: 840
.saturating_add(Weight::from_parts(3_011, 0).saturating_mul(n.into()))
// Standard Error: 840
.saturating_add(Weight::from_parts(892, 0).saturating_mul(u.into()))
.saturating_add(T::DbWeight::get().writes(1_u64))
// Measured: `77`
// Estimated: `3513`
// Minimum execution time: 6_000_000 picoseconds.
Weight::from_parts(6_567_981, 0)
.saturating_add(Weight::from_parts(0, 3513))
// Standard Error: 405
.saturating_add(Weight::from_parts(3_456, 0).saturating_mul(n.into()))
// Standard Error: 405
.saturating_add(Weight::from_parts(1_017, 0).saturating_mul(u.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}

// For backwards compatibility and tests
impl WeightInfo for () {
/// Storage: ClientsInfo CurrentClientReleases (r:0 w:1)
/// Proof: ClientsInfo CurrentClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen)
/// The range of component `n` is `[0, 255]`.
/// The range of component `u` is `[0, 255]`.
fn set_current_client_release(n: u32, u: u32, ) -> Weight {
/// Storage: ClientsInfo AuthorizedAccounts (r:2 w:1)
/// Proof: ClientsInfo AuthorizedAccounts (max_values: None, max_size: Some(48), added: 2523, mode: MaxEncodedLen)
fn authorize_account() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 7_607_000 picoseconds.
Weight::from_parts(9_560_259, 0)
// Standard Error: 845
.saturating_add(Weight::from_parts(2_586, 0).saturating_mul(n.into()))
// Standard Error: 845
.saturating_add(Weight::from_parts(689, 0).saturating_mul(u.into()))
.saturating_add(RocksDbWeight::get().writes(1_u64))
// Measured: `77`
// Estimated: `6036`
// Minimum execution time: 6_000_000 picoseconds.
Weight::from_parts(7_000_000, 0)
.saturating_add(Weight::from_parts(0, 6036))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: ClientsInfo PendingClientReleases (r:0 w:1)
/// Proof: ClientsInfo PendingClientReleases (max_values: None, max_size: Some(562), added: 3037, mode: MaxEncodedLen)
/// The range of component `n` is `[0, 255]`.
/// The range of component `u` is `[0, 255]`.
fn set_pending_client_release(n: u32, u: u32, ) -> Weight {
/// Storage: ClientsInfo AuthorizedAccounts (r:2 w:1)
/// Proof: ClientsInfo AuthorizedAccounts (max_values: None, max_size: Some(48), added: 2523, mode: MaxEncodedLen)
fn deauthorize_account() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 7_557_000 picoseconds.
Weight::from_parts(9_238_573, 0)
// Standard Error: 840
.saturating_add(Weight::from_parts(3_011, 0).saturating_mul(n.into()))
// Standard Error: 840
.saturating_add(Weight::from_parts(892, 0).saturating_mul(u.into()))
.saturating_add(RocksDbWeight::get().writes(1_u64))
// Measured: `134`
// Estimated: `6036`
// Minimum execution time: 8_000_000 picoseconds.
Weight::from_parts(9_000_000, 0)
.saturating_add(Weight::from_parts(0, 6036))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(1))
}
}
}
75 changes: 72 additions & 3 deletions pallets/clients-info/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub mod pallet {
client_name: NameOf<T>,
release: ClientRelease<UriOf<T>, T::Hash>,
) -> DispatchResult {
ensure_root(origin)?;
Pallet::<T>::check_origin_rights(origin)?;
CurrentClientReleases::<T>::insert(client_name, release.clone());
Self::deposit_event(Event::<T>::ApplyClientRelease { release });
Ok(())
Expand All @@ -108,22 +108,64 @@ pub mod pallet {
client_name: NameOf<T>,
release: ClientRelease<UriOf<T>, T::Hash>,
) -> DispatchResult {
ensure_root(origin)?;
Pallet::<T>::check_origin_rights(origin)?;
PendingClientReleases::<T>::insert(client_name, release.clone());
Self::deposit_event(Event::<T>::NotifyClientRelease { release });
Ok(())
}

#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::authorize_account())]
#[transactional]
pub fn authorize_account(origin: OriginFor<T>, account_id: T::AccountId) -> DispatchResult {
Pallet::<T>::check_origin_rights(origin)?;

if !<AuthorizedAccounts<T>>::contains_key(&account_id) {
Self::deposit_event(Event::<T>::AccountIdAuthorized(account_id.clone()));
<AuthorizedAccounts<T>>::insert(account_id, ());
}

Ok(())
}

#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::deauthorize_account())]
#[transactional]
pub fn deauthorize_account(
origin: OriginFor<T>,
account_id: T::AccountId,
) -> DispatchResult {
if let Err(_) = ensure_root(origin.clone()) {
let origin_account_id = Pallet::<T>::check_non_root_rights(origin)?;
ensure!(
account_id != origin_account_id,
Error::<T>::UserUnableToDeauthorizeThemself
);
}

if <AuthorizedAccounts<T>>::contains_key(&account_id) {
Self::deposit_event(Event::<T>::AccountIdDeauthorized(account_id.clone()));
<AuthorizedAccounts<T>>::remove(account_id);
}

Ok(())
}
}

#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
NotifyClientRelease { release: ClientRelease<UriOf<T>, T::Hash> },
ApplyClientRelease { release: ClientRelease<UriOf<T>, T::Hash> },
AccountIdAuthorized(T::AccountId),
AccountIdDeauthorized(T::AccountId),
}

#[pallet::error]
pub enum Error<T> {}
pub enum Error<T> {
ThisAccountIdIsNotAuthorized,
UserUnableToDeauthorizeThemself,
}

/// Mapping of client name (string literal represented as bytes) to its release details.
#[pallet::storage]
Expand All @@ -136,6 +178,33 @@ pub mod pallet {
#[pallet::getter(fn pending_client_release)]
pub(super) type PendingClientReleases<T: Config> =
StorageMap<_, Blake2_128Concat, NameOf<T>, ClientRelease<UriOf<T>, T::Hash>, OptionQuery>;

/// List of all authorized accounts
#[pallet::storage]
#[pallet::getter(fn authorized_accounts)]
pub(super) type AuthorizedAccounts<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, ()>;

impl<T: Config> Pallet<T> {
fn check_non_root_rights(origin: OriginFor<T>) -> Result<T::AccountId, DispatchError> {
let origin_account_id = ensure_signed(origin)?;

ensure!(
<AuthorizedAccounts<T>>::contains_key(&origin_account_id),
Error::<T>::ThisAccountIdIsNotAuthorized
);

Ok(origin_account_id)
}

fn check_origin_rights(origin: OriginFor<T>) -> DispatchResult {
if ensure_root(origin.clone()).is_err() {
Pallet::<T>::check_non_root_rights(origin)?;
}

Ok(())
}
}
}

pub mod upgrade_client_releases {
Expand Down
5 changes: 3 additions & 2 deletions pallets/clients-info/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate as clients_info;
use crate::Config;
use crate::{Config, Error};
use frame_support::{
parameter_types,
traits::{ConstU32, Everything},
Expand Down Expand Up @@ -29,6 +29,7 @@ frame_support::construct_runtime!(
pub type AccountId = u64;
pub type BlockNumber = u64;
pub type Index = u64;
pub type TestError = Error<Test>;

parameter_types! {
pub const BlockHashCount: u64 = 250;
Expand Down Expand Up @@ -64,7 +65,7 @@ impl frame_system::Config for Test {

impl Config for Test {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type WeightInfo = crate::SubstrateWeight<Test>;
type MaxNameLength = ConstU32<255>;
type MaxUriLength = ConstU32<255>;
}
Expand Down
Loading