Generalised proxies (#6156)

* Initial work

* It should work

* Fix node

* Fix tests

* Initial test

* Tests

* Expunge proxy functionality from democracy and elections

* Allow different proxy types

* Repotted

* Build

* Build

* Making a start on weights

* Undo breaking change

* Line widths.

* Fix

* fix tests

* finish benchmarks?

* Storage name!

* Utility -> Proxy

* proxy weight

* add proxy weight

* remove weights

* Update transfer constraint

* Again, fix constraints

* Fix negation

* Update frame/proxy/Cargo.toml

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Remove unneeded event.

* Grumbles

* Apply suggestions from code review

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
Gavin Wood
2020-06-02 18:15:15 +02:00
committed by GitHub
parent ffea161765
commit 4adac40c07
20 changed files with 724 additions and 738 deletions
+88
View File
@@ -0,0 +1,88 @@
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Benchmarks for Proxy Pallet
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks, account};
use sp_runtime::traits::Bounded;
use crate::Module as Proxy;
const SEED: u32 = 0;
fn add_proxies<T: Trait>(n: u32) -> Result<(), &'static str> {
let caller: T::AccountId = account("caller", 0, SEED);
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
for i in 0..n {
Proxy::<T>::add_proxy(
RawOrigin::Signed(caller.clone()).into(),
account("target", i, SEED),
T::ProxyType::default()
)?;
}
Ok(())
}
benchmarks! {
_ {
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p)?;
}
proxy {
let p in ...;
// In this case the caller is the "target" proxy
let caller: T::AccountId = account("target", p - 1, SEED);
// ... and "real" is the traditional caller. This is not a typo.
let real: T::AccountId = account("caller", 0, SEED);
let call: <T as Trait>::Call = frame_system::Call::<T>::remark(vec![]).into();
}: _(RawOrigin::Signed(caller), real, Some(T::ProxyType::default()), Box::new(call))
add_proxy {
let p in ...;
let caller: T::AccountId = account("caller", 0, SEED);
}: _(RawOrigin::Signed(caller), account("target", T::MaxProxies::get().into(), SEED), T::ProxyType::default())
remove_proxy {
let p in ...;
let caller: T::AccountId = account("caller", 0, SEED);
}: _(RawOrigin::Signed(caller), account("target", 0, SEED), T::ProxyType::default())
remove_proxies {
let p in ...;
let caller: T::AccountId = account("caller", 0, SEED);
}: _(RawOrigin::Signed(caller))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{new_test_ext, Test};
use frame_support::assert_ok;
#[test]
fn test_benchmarks() {
new_test_ext().execute_with(|| {
assert_ok!(test_benchmark_proxy::<Test>());
assert_ok!(test_benchmark_add_proxy::<Test>());
assert_ok!(test_benchmark_remove_proxy::<Test>());
assert_ok!(test_benchmark_remove_proxies::<Test>());
});
}
}
+271
View File
@@ -0,0 +1,271 @@
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Proxy Module
//! A module allowing accounts to give permission to other accounts to dispatch types of calls from
//! their signed origin.
//!
//! - [`proxy::Trait`](./trait.Trait.html)
//! - [`Call`](./enum.Call.html)
//!
//! ## Overview
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! [`Call`]: ./enum.Call.html
//! [`Trait`]: ./trait.Trait.html
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
use sp_std::prelude::*;
use frame_support::{decl_module, decl_event, decl_error, decl_storage, Parameter, ensure};
use frame_support::{
traits::{Get, ReservableCurrency, Currency, Filter, InstanceFilter},
weights::{GetDispatchInfo, constants::{WEIGHT_PER_MICROS, WEIGHT_PER_NANOS}},
dispatch::{PostDispatchInfo, IsSubType},
};
use frame_system::{self as system, ensure_signed};
use sp_runtime::{DispatchResult, traits::{Dispatchable, Zero}};
use sp_runtime::traits::Member;
mod tests;
mod benchmarking;
type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::Balance;
/// Configuration trait.
pub trait Trait: frame_system::Trait {
/// The overarching event type.
type Event: From<Event> + Into<<Self as frame_system::Trait>::Event>;
/// The overarching call type.
type Call: Parameter + Dispatchable<Origin=Self::Origin, PostInfo=PostDispatchInfo>
+ GetDispatchInfo + From<frame_system::Call<Self>> + IsSubType<Module<Self>, Self>;
/// The currency mechanism.
type Currency: ReservableCurrency<Self::AccountId>;
/// Is a given call compatible with the proxying subsystem?
type IsCallable: Filter<<Self as Trait>::Call>;
/// A kind of proxy; specified with the proxy and passed in to the `IsProxyable` fitler.
/// The instance filter determines whether a given call may be proxied under this type.
type ProxyType: Parameter + Member + Ord + PartialOrd + InstanceFilter<<Self as Trait>::Call>
+ Default;
/// The base amount of currency needed to reserve for creating a proxy.
///
/// This is held for an additional storage item whose value size is
/// `sizeof(Balance)` bytes and whose key size is `sizeof(AccountId)` bytes.
type ProxyDepositBase: Get<BalanceOf<Self>>;
/// The amount of currency needed per proxy added.
///
/// This is held for adding 32 bytes plus an instance of `ProxyType` more into a pre-existing
/// storage value.
type ProxyDepositFactor: Get<BalanceOf<Self>>;
/// The maximum amount of proxies allowed for a single account.
type MaxProxies: Get<u16>;
}
decl_storage! {
trait Store for Module<T: Trait> as Proxy {
/// The set of account proxies. Maps the account which has delegated to the accounts
/// which are being delegated to, together with the amount held on deposit.
pub Proxies: map hasher(twox_64_concat) T::AccountId => (Vec<(T::AccountId, T::ProxyType)>, BalanceOf<T>);
}
}
decl_error! {
pub enum Error for Module<T: Trait> {
/// There are too many proxies registered.
TooMany,
/// Proxy registration not found.
NotFound,
/// Sender is not a proxy of the account to be proxied.
NotProxy,
/// A call with a `false` `IsCallable` filter was attempted.
Uncallable,
/// A call which is incompatible with the proxy type's filter was attempted.
Unproxyable,
/// Account is already a proxy.
Duplicate,
/// Call may not be made by proxy because it may escalate its privileges.
NoPermission,
}
}
decl_event! {
/// Events type.
pub enum Event {
/// A proxy was executed correctly, with the given result.
ProxyExecuted(DispatchResult),
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
type Error = Error<T>;
/// Deposit one of this module's events by using the default implementation.
fn deposit_event() = default;
/// Dispatch the given `call` from an account that the sender is authorised for through
/// `add_proxy`.
///
/// The dispatch origin for this call must be _Signed_.
///
/// Parameters:
/// - `real`: The account that the proxy will make a call on behalf of.
/// - `force_proxy_type`: Specify the exact proxy type to be used and checked for this call.
/// - `call`: The call to be made by the `real` account.
///
/// # <weight>
/// P is the number of proxies the user has
/// - Base weight: 19.87 + .141 * P µs
/// - DB weight: 1 storage read.
/// - Plus the weight of the `call`
/// # </weight>
#[weight = {
let di = call.get_dispatch_info();
(T::DbWeight::get().reads(1)
.saturating_add(di.weight)
.saturating_add(20 * WEIGHT_PER_MICROS)
.saturating_add((140 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into())),
di.class)
}]
fn proxy(origin,
real: T::AccountId,
force_proxy_type: Option<T::ProxyType>,
call: Box<<T as Trait>::Call>
) {
let who = ensure_signed(origin)?;
ensure!(T::IsCallable::filter(&call), Error::<T>::Uncallable);
let (_, proxy_type) = Proxies::<T>::get(&real).0.into_iter()
.find(|x| &x.0 == &who && force_proxy_type.as_ref().map_or(true, |y| &x.1 == y))
.ok_or(Error::<T>::NotProxy)?;
match call.is_sub_type() {
Some(Call::add_proxy(_, ref pt)) | Some(Call::remove_proxy(_, ref pt)) =>
ensure!(&proxy_type == pt, Error::<T>::NoPermission),
_ => (),
}
ensure!(proxy_type.filter(&call), Error::<T>::Unproxyable);
let e = call.dispatch(frame_system::RawOrigin::Signed(real).into());
Self::deposit_event(Event::ProxyExecuted(e.map(|_| ()).map_err(|e| e.error)));
}
/// Register a proxy account for the sender that is able to make calls on its behalf.
///
/// The dispatch origin for this call must be _Signed_.
///
/// Parameters:
/// - `proxy`: The account that the `caller` would like to make a proxy.
/// - `proxy_type`: The permissions allowed for this proxy account.
///
/// # <weight>
/// P is the number of proxies the user has
/// - Base weight: 17.48 + .176 * P µs
/// - DB weight: 1 storage read and write.
/// # </weight>
#[weight = T::DbWeight::get().reads_writes(1, 1)
.saturating_add(18 * WEIGHT_PER_MICROS)
.saturating_add((200 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
]
fn add_proxy(origin, proxy: T::AccountId, proxy_type: T::ProxyType) -> DispatchResult {
let who = ensure_signed(origin)?;
Proxies::<T>::try_mutate(&who, |(ref mut proxies, ref mut deposit)| {
ensure!(proxies.len() < T::MaxProxies::get() as usize, Error::<T>::TooMany);
let typed_proxy = (proxy, proxy_type);
let i = proxies.binary_search(&typed_proxy).err().ok_or(Error::<T>::Duplicate)?;
proxies.insert(i, typed_proxy);
let new_deposit = T::ProxyDepositBase::get()
+ T::ProxyDepositFactor::get() * (proxies.len() as u32).into();
if new_deposit > *deposit {
T::Currency::reserve(&who, new_deposit - *deposit)?;
} else if new_deposit < *deposit {
T::Currency::unreserve(&who, *deposit - new_deposit);
}
*deposit = new_deposit;
Ok(())
})
}
/// Unregister a proxy account for the sender.
///
/// The dispatch origin for this call must be _Signed_.
///
/// Parameters:
/// - `proxy`: The account that the `caller` would like to remove as a proxy.
/// - `proxy_type`: The permissions currently enabled for the removed proxy account.
///
/// # <weight>
/// P is the number of proxies the user has
/// - Base weight: 14.37 + .164 * P µs
/// - DB weight: 1 storage read and write.
/// # </weight>
#[weight = T::DbWeight::get().reads_writes(1, 1)
.saturating_add(14 * WEIGHT_PER_MICROS)
.saturating_add((160 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
]
fn remove_proxy(origin, proxy: T::AccountId, proxy_type: T::ProxyType) -> DispatchResult {
let who = ensure_signed(origin)?;
Proxies::<T>::try_mutate_exists(&who, |x| {
let (mut proxies, old_deposit) = x.take().ok_or(Error::<T>::NotFound)?;
let typed_proxy = (proxy, proxy_type);
let i = proxies.binary_search(&typed_proxy).ok().ok_or(Error::<T>::NotFound)?;
proxies.remove(i);
let new_deposit = if proxies.is_empty() {
BalanceOf::<T>::zero()
} else {
T::ProxyDepositBase::get() + T::ProxyDepositFactor::get() * (proxies.len() as u32).into()
};
if new_deposit > old_deposit {
T::Currency::reserve(&who, new_deposit - old_deposit)?;
} else if new_deposit < old_deposit {
T::Currency::unreserve(&who, old_deposit - new_deposit);
}
if !proxies.is_empty() {
*x = Some((proxies, new_deposit))
}
Ok(())
})
}
/// Unregister all proxy accounts for the sender.
///
/// The dispatch origin for this call must be _Signed_.
///
/// # <weight>
/// P is the number of proxies the user has
/// - Base weight: 13.73 + .129 * P µs
/// - DB weight: 1 storage read and write.
/// # </weight>
#[weight = T::DbWeight::get().reads_writes(1, 1)
.saturating_add(14 * WEIGHT_PER_MICROS)
.saturating_add((130 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
]
fn remove_proxies(origin) {
let who = ensure_signed(origin)?;
let (_, old_deposit) = Proxies::<T>::take(&who);
T::Currency::unreserve(&who, old_deposit);
}
}
}
+220
View File
@@ -0,0 +1,220 @@
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests for Proxy Pallet
#![cfg(test)]
use super::*;
use frame_support::{
assert_ok, assert_noop, impl_outer_origin, parameter_types, impl_outer_dispatch,
weights::Weight, impl_outer_event, RuntimeDebug
};
use codec::{Encode, Decode};
use sp_core::H256;
use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
use crate as proxy;
impl_outer_origin! {
pub enum Origin for Test where system = frame_system {}
}
impl_outer_event! {
pub enum TestEvent for Test {
system<T>,
pallet_balances<T>,
proxy,
}
}
impl_outer_dispatch! {
pub enum Call for Test where origin: Origin {
frame_system::System,
pallet_balances::Balances,
proxy::Proxy,
}
}
// For testing the pallet, we construct most of a mock runtime. This means
// first constructing a configuration type (`Test`) which `impl`s each of the
// configuration traits of pallets we want to use.
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Call = Call;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = TestEvent;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumExtrinsicWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
}
impl pallet_balances::Trait for Test {
type Balance = u64;
type Event = TestEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
parameter_types! {
pub const ProxyDepositBase: u64 = 1;
pub const ProxyDepositFactor: u64 = 1;
pub const MaxProxies: u16 = 3;
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug)]
pub enum ProxyType {
Any,
JustTransfer,
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl InstanceFilter<Call> for ProxyType {
fn filter(&self, c: &Call) -> bool {
match self {
ProxyType::Any => true,
ProxyType::JustTransfer => match c {
Call::Balances(pallet_balances::Call::transfer(..)) => true,
_ => false,
}
}
}
}
pub struct TestIsCallable;
impl Filter<Call> for TestIsCallable {
fn filter(c: &Call) -> bool {
match *c {
Call::Balances(_) => true,
_ => false,
}
}
}
impl Trait for Test {
type Event = TestEvent;
type Call = Call;
type Currency = Balances;
type IsCallable = TestIsCallable;
type ProxyType = ProxyType;
type ProxyDepositBase = ProxyDepositBase;
type ProxyDepositFactor = ProxyDepositFactor;
type MaxProxies = MaxProxies;
}
type System = frame_system::Module<Test>;
type Balances = pallet_balances::Module<Test>;
type Proxy = Module<Test>;
use frame_system::Call as SystemCall;
use pallet_balances::Call as BalancesCall;
use pallet_balances::Error as BalancesError;
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10), (2, 10), (3, 10), (4, 10), (5, 2)],
}.assimilate_storage(&mut t).unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
fn last_event() -> TestEvent {
system::Module::<Test>::events().pop().map(|e| e.event).expect("Event expected")
}
fn expect_event<E: Into<TestEvent>>(e: E) {
assert_eq!(last_event(), e.into());
}
#[test]
fn add_remove_proxies_works() {
new_test_ext().execute_with(|| {
assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::Any));
assert_noop!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::Any), Error::<Test>::Duplicate);
assert_eq!(Balances::reserved_balance(1), 2);
assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::JustTransfer));
assert_eq!(Balances::reserved_balance(1), 3);
assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any));
assert_eq!(Balances::reserved_balance(1), 4);
assert_noop!(Proxy::add_proxy(Origin::signed(1), 4, ProxyType::Any), Error::<Test>::TooMany);
assert_noop!(Proxy::remove_proxy(Origin::signed(1), 3, ProxyType::JustTransfer), Error::<Test>::NotFound);
assert_ok!(Proxy::remove_proxy(Origin::signed(1), 3, ProxyType::Any));
assert_eq!(Balances::reserved_balance(1), 3);
assert_ok!(Proxy::remove_proxy(Origin::signed(1), 2, ProxyType::Any));
assert_eq!(Balances::reserved_balance(1), 2);
assert_ok!(Proxy::remove_proxy(Origin::signed(1), 2, ProxyType::JustTransfer));
assert_eq!(Balances::reserved_balance(1), 0);
});
}
#[test]
fn cannot_add_proxy_without_balance() {
new_test_ext().execute_with(|| {
assert_ok!(Proxy::add_proxy(Origin::signed(5), 3, ProxyType::Any));
assert_eq!(Balances::reserved_balance(5), 2);
assert_noop!(
Proxy::add_proxy(Origin::signed(5), 4, ProxyType::Any),
BalancesError::<Test, _>::InsufficientBalance
);
});
}
#[test]
fn proxying_works() {
new_test_ext().execute_with(|| {
assert_ok!(Proxy::add_proxy(Origin::signed(1), 2, ProxyType::JustTransfer));
assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 1)));
assert_noop!(Proxy::proxy(Origin::signed(4), 1, None, call.clone()), Error::<Test>::NotProxy);
assert_noop!(Proxy::proxy(Origin::signed(2), 1, Some(ProxyType::Any), call.clone()), Error::<Test>::NotProxy);
assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone()));
expect_event(Event::ProxyExecuted(Ok(())));
assert_eq!(Balances::free_balance(6), 1);
let call = Box::new(Call::System(SystemCall::remark(vec![])));
assert_noop!(Proxy::proxy(Origin::signed(3), 1, None, call.clone()), Error::<Test>::Uncallable);
let call = Box::new(Call::Balances(BalancesCall::transfer_keep_alive(6, 1)));
assert_noop!(Proxy::proxy(Origin::signed(2), 1, None, call.clone()), Error::<Test>::Unproxyable);
assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone()));
expect_event(Event::ProxyExecuted(Ok(())));
assert_eq!(Balances::free_balance(6), 2);
});
}