Introduce stacked filtering (#6273)

* Introduce stacked filtering.

* Benchmarks

* Remove unneeded crates

* Fix proxy type's permissiveness checks.

* Repot multisig to make utility stateless.

* Repot filter stack impl into macro

* Fix wasm build

* Tests

* Final test.

* Tests for the macro

* Fix test

* Line width

* Fix

* Update frame/multisig/src/benchmarking.rs

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>

* Update primitives/std/with_std.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Grumble

* Update frame/support/src/traits.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/support/src/traits.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/support/src/traits.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/support/src/traits.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/support/src/traits.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/multisig/src/tests.rs

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>

* Update frame/multisig/src/tests.rs

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>

* Grumble

* Migration

* Grumble

* Comments

* Migration

* Fix

* Fix

* Line width

* Allow unused

* Update frame/multisig/src/lib.rs

Co-authored-by: Alexander Popiak <alexander.popiak@parity.io>

* Fix up grumble.

* Remove Utility constraint in NonTransfer

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Alexander Popiak <alexander.popiak@parity.io>
This commit is contained in:
Gavin Wood
2020-06-08 13:09:12 +02:00
committed by GitHub
parent 663cd09be9
commit 15ecac5cb6
19 changed files with 1630 additions and 890 deletions
+6 -106
View File
@@ -23,26 +23,10 @@ use super::*;
use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks, account};
use sp_runtime::traits::Saturating;
use crate::Module as Utility;
const SEED: u32 = 0;
fn setup_multi<T: Trait>(s: u32, z: u32) -> Result<(Vec<T::AccountId>, Box<<T as Trait>::Call>), &'static str>{
let mut signatories: Vec<T::AccountId> = Vec::new();
for i in 0 .. s {
let signatory = account("signatory", i, SEED);
// Give them some balance for a possible deposit
let deposit = T::MultisigDepositBase::get() + T::MultisigDepositFactor::get() * s.into();
let balance = T::Currency::minimum_balance().saturating_mul(100.into()) + deposit;
T::Currency::make_free_balance_be(&signatory, balance);
signatories.push(signatory);
}
signatories.sort();
let call: Box<<T as Trait>::Call> = Box::new(frame_system::Call::remark(vec![0; z as usize]).into());
return Ok((signatories, call))
}
benchmarks! {
_ { }
@@ -62,90 +46,11 @@ benchmarks! {
let call = Box::new(frame_system::Call::remark(vec![]).into());
}: _(RawOrigin::Signed(caller), u as u16, call)
as_multi_create {
// Signatories, need at least 2 total people
let s in 2 .. T::MaxSignatories::get() as u32;
// Transaction Length
let z in 0 .. 10_000;
let (mut signatories, call) = setup_multi::<T>(s, z)?;
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
}: as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call)
as_multi_approve {
// Signatories, need at least 2 people
let s in 2 .. T::MaxSignatories::get() as u32;
// Transaction Length
let z in 0 .. 10_000;
let (mut signatories, call) = setup_multi::<T>(s, z)?;
let mut signatories2 = signatories.clone();
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
// before the call, get the timepoint
let timepoint = Utility::<T>::timepoint();
// Create the multi
Utility::<T>::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone())?;
let caller2 = signatories2.remove(0);
}: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call)
as_multi_complete {
// Signatories, need at least 2 people
let s in 2 .. T::MaxSignatories::get() as u32;
// Transaction Length
let z in 0 .. 10_000;
let (mut signatories, call) = setup_multi::<T>(s, z)?;
let mut signatories2 = signatories.clone();
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
// before the call, get the timepoint
let timepoint = Utility::<T>::timepoint();
// Create the multi
Utility::<T>::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone())?;
// Everyone except the first person approves
for i in 1 .. s - 1 {
let mut signatories_loop = signatories2.clone();
let caller_loop = signatories_loop.remove(i as usize);
Utility::<T>::as_multi(RawOrigin::Signed(caller_loop).into(), s as u16, signatories_loop, Some(timepoint), call.clone())?;
}
let caller2 = signatories2.remove(0);
}: as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call)
approve_as_multi_create {
// Signatories, need at least 2 people
let s in 2 .. T::MaxSignatories::get() as u32;
// Transaction Length
let z in 0 .. 10_000;
let (mut signatories, call) = setup_multi::<T>(s, z)?;
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
let call_hash = call.using_encoded(blake2_256);
// Create the multi
}: approve_as_multi(RawOrigin::Signed(caller), s as u16, signatories, None, call_hash)
approve_as_multi_approve {
// Signatories, need at least 2 people
let s in 2 .. T::MaxSignatories::get() as u32;
// Transaction Length
let z in 0 .. 10_000;
let (mut signatories, call) = setup_multi::<T>(s, z)?;
let mut signatories2 = signatories.clone();
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
let call_hash = call.using_encoded(blake2_256);
// before the call, get the timepoint
let timepoint = Utility::<T>::timepoint();
// Create the multi
Utility::<T>::as_multi(RawOrigin::Signed(caller).into(), s as u16, signatories, None, call.clone())?;
let caller2 = signatories2.remove(0);
}: approve_as_multi(RawOrigin::Signed(caller2), s as u16, signatories2, Some(timepoint), call_hash)
cancel_as_multi {
// Signatories, need at least 2 people
let s in 2 .. T::MaxSignatories::get() as u32;
// Transaction Length
let z in 0 .. 10_000;
let (mut signatories, call) = setup_multi::<T>(s, z)?;
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
let call_hash = call.using_encoded(blake2_256);
let timepoint = Utility::<T>::timepoint();
// Create the multi
Utility::<T>::as_multi(RawOrigin::Signed(caller.clone()).into(), s as u16, signatories.clone(), None, call.clone())?;
}: _(RawOrigin::Signed(caller), s as u16, signatories, timepoint, call_hash)
as_limited_sub {
let u in 0 .. 1000;
let caller = account("caller", u, SEED);
let call = Box::new(frame_system::Call::remark(vec![]).into());
}: _(RawOrigin::Signed(caller), u as u16, call)
}
#[cfg(test)]
@@ -159,12 +64,7 @@ mod tests {
new_test_ext().execute_with(|| {
assert_ok!(test_benchmark_batch::<Test>());
assert_ok!(test_benchmark_as_sub::<Test>());
assert_ok!(test_benchmark_as_multi_create::<Test>());
assert_ok!(test_benchmark_as_multi_approve::<Test>());
assert_ok!(test_benchmark_as_multi_complete::<Test>());
assert_ok!(test_benchmark_approve_as_multi_create::<Test>());
assert_ok!(test_benchmark_approve_as_multi_approve::<Test>());
assert_ok!(test_benchmark_cancel_as_multi::<Test>());
assert_ok!(test_benchmark_as_limited_sub::<Test>());
});
}
}
+36 -457
View File
@@ -16,14 +16,14 @@
// limitations under the License.
//! # Utility Module
//! A module with helpers for dispatch management.
//! A stateless module with helpers for dispatch management.
//!
//! - [`utility::Trait`](./trait.Trait.html)
//! - [`Call`](./enum.Call.html)
//!
//! ## Overview
//!
//! This module contains three basic pieces of functionality, two of which are stateless:
//! This module contains two basic pieces of functionality:
//! - Batch dispatch: A stateless operation, allowing any origin to execute multiple calls in a
//! single dispatch. This can be useful to amalgamate proposals, combining `set_code` with
//! corresponding `set_storage`s, for efficient multiple payouts with just a single signature
@@ -33,12 +33,6 @@
//! account IDs) and these can be stacked. This can be useful as a key management tool, where you
//! need multiple distinct accounts (e.g. as controllers for many staking accounts), but where
//! it's perfectly fine to have each of them controlled by the same underlying keypair.
//! - Multisig dispatch (stateful): A potentially stateful operation, allowing multiple signed
//! origins (accounts) to coordinate and dispatch a call from a well-known origin, derivable
//! deterministically from the set of account IDs and the threshold number of accounts from the
//! set that must approve it. In the case that the threshold is just one then this is a stateless
//! operation. This is useful for multisig wallets where cryptographic threshold signatures are
//! not available or desired.
//!
//! ## Interface
//!
@@ -50,12 +44,6 @@
//! #### For pseudonymal dispatch
//! * `as_sub` - Dispatch a call from a secondary ("sub") signed origin.
//!
//! #### For multisig dispatch
//! * `as_multi` - Approve and if possible dispatch a call from a composite origin formed from a
//! number of signed origins.
//! * `approve_as_multi` - Approve a call from a composite origin.
//! * `cancel_as_multi` - Cancel a call from a composite origin.
//!
//! [`Call`]: ./enum.Call.html
//! [`Trait`]: ./trait.Trait.html
@@ -66,10 +54,9 @@ use sp_std::prelude::*;
use codec::{Encode, Decode};
use sp_core::TypeId;
use sp_io::hashing::blake2_256;
use frame_support::{decl_module, decl_event, decl_error, decl_storage, Parameter, ensure, RuntimeDebug};
use frame_support::{traits::{Get, ReservableCurrency, Currency, Filter},
weights::{Weight, GetDispatchInfo, DispatchClass, FunctionOf, Pays},
dispatch::{DispatchResultWithPostInfo, DispatchErrorWithPostInfo, PostDispatchInfo},
use frame_support::{decl_module, decl_event, decl_error, decl_storage, Parameter, ensure};
use frame_support::{traits::{Filter, FilterStack, ClearFilterGuard},
weights::{Weight, GetDispatchInfo, DispatchClass, FunctionOf, Pays}, dispatch::PostDispatchInfo,
};
use frame_system::{self as system, ensure_signed, ensure_root};
use sp_runtime::{DispatchError, DispatchResult, traits::Dispatchable};
@@ -77,97 +64,25 @@ use sp_runtime::{DispatchError, DispatchResult, traits::Dispatchable};
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<Self>> + Into<<Self as frame_system::Trait>::Event>;
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>>;
/// The currency mechanism.
type Currency: ReservableCurrency<Self::AccountId>;
/// The base amount of currency needed to reserve for creating a multisig execution.
///
/// This is held for an additional storage item whose value size is
/// `4 + sizeof((BlockNumber, Balance, AccountId))` bytes.
type MultisigDepositBase: Get<BalanceOf<Self>>;
/// The amount of currency needed per unit threshold when creating a multisig execution.
///
/// This is held for adding 32 bytes more into a pre-existing storage value.
type MultisigDepositFactor: Get<BalanceOf<Self>>;
/// The maximum amount of signatories allowed in the multisig.
type MaxSignatories: Get<u16>;
/// Is a given call compatible with the proxying subsystem?
type IsCallable: Filter<<Self as Trait>::Call>;
}
/// A global extrinsic index, formed as the extrinsic index within a block, together with that
/// block's height. This allows a transaction in which a multisig operation of a particular
/// composite was created to be uniquely identified.
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug)]
pub struct Timepoint<BlockNumber> {
/// The height of the chain at the point in time.
height: BlockNumber,
/// The index of the extrinsic at the point in time.
index: u32,
}
/// An open multisig operation.
#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug)]
pub struct Multisig<BlockNumber, Balance, AccountId> {
/// The extrinsic when the multisig operation was opened.
when: Timepoint<BlockNumber>,
/// The amount held in reserve of the `depositor`, to be returned once the operation ends.
deposit: Balance,
/// The account who opened it (i.e. the first to approve it).
depositor: AccountId,
/// The approvals achieved so far, including the depositor. Always sorted.
approvals: Vec<AccountId>,
type IsCallable: FilterStack<<Self as Trait>::Call>;
}
decl_storage! {
trait Store for Module<T: Trait> as Utility {
/// The set of open multisig operations.
pub Multisigs: double_map
hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) [u8; 32]
=> Option<Multisig<T::BlockNumber, BalanceOf<T>, T::AccountId>>;
}
trait Store for Module<T: Trait> as Utility {}
}
decl_error! {
pub enum Error for Module<T: Trait> {
/// Threshold is too low (zero).
ZeroThreshold,
/// Call is already approved by this signatory.
AlreadyApproved,
/// Call doesn't need any (more) approvals.
NoApprovalsNeeded,
/// There are too few signatories in the list.
TooFewSignatories,
/// There are too many signatories in the list.
TooManySignatories,
/// The signatories were provided out of order; they should be ordered.
SignatoriesOutOfOrder,
/// The sender was contained in the other signatories; it shouldn't be.
SenderInSignatories,
/// Multisig operation not found when attempting to cancel.
NotFound,
/// Only the account that originally created the multisig is able to cancel it.
NotOwner,
/// No timepoint was given, yet the multisig operation is already underway.
NoTimepoint,
/// A different timepoint was given to the multisig operation that is underway.
WrongTimepoint,
/// A timepoint was given, yet no multisig operation is underway.
UnexpectedTimepoint,
/// A call with a `false` `IsCallable` filter was attempted.
Uncallable,
}
@@ -175,28 +90,12 @@ decl_error! {
decl_event! {
/// Events type.
pub enum Event<T> where
AccountId = <T as system::Trait>::AccountId,
BlockNumber = <T as system::Trait>::BlockNumber,
CallHash = [u8; 32]
{
pub enum Event {
/// Batch of dispatches did not complete fully. Index of first failing dispatch given, as
/// well as the error.
BatchInterrupted(u32, DispatchError),
/// Batch of dispatches completed fully with no error.
BatchCompleted,
/// A new multisig operation has begun. First param is the account that is approving,
/// second is the multisig account, third is hash of the call.
NewMultisig(AccountId, AccountId, CallHash),
/// A multisig operation has been approved by someone. First param is the account that is
/// approving, third is the multisig account, fourth is hash of the call.
MultisigApproval(AccountId, Timepoint<BlockNumber>, AccountId, CallHash),
/// A multisig operation has been executed. First param is the account that is
/// approving, third is the multisig account, fourth is hash of the call to be executed.
MultisigExecuted(AccountId, Timepoint<BlockNumber>, AccountId, CallHash, DispatchResult),
/// A multisig operation has been cancelled. First param is the account that is
/// cancelling, third is the multisig account, fourth is hash of the call.
MultisigCancelled(AccountId, Timepoint<BlockNumber>, AccountId, CallHash),
/// A call with a `false` IsCallable filter was attempted.
Uncallable(u32),
}
@@ -210,25 +109,6 @@ impl TypeId for IndexedUtilityModuleId {
const TYPE_ID: [u8; 4] = *b"suba";
}
mod weight_of {
use super::*;
/// - Base Weight:
/// - Create: 46.55 + 0.089 * S µs
/// - Approve: 34.03 + .112 * S µs
/// - Complete: 40.36 + .225 * S µs
/// - DB Weight:
/// - Reads: Multisig Storage, [Caller Account]
/// - Writes: Multisig Storage, [Caller Account]
/// - Plus Call Weight
pub fn as_multi<T: Trait>(other_sig_len: usize, call_weight: Weight) -> Weight {
call_weight
.saturating_add(45_000_000)
.saturating_add((other_sig_len as Weight).saturating_mul(250_000))
.saturating_add(T::DbWeight::get().reads_writes(1, 1))
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
type Error = Error<T>;
@@ -278,21 +158,26 @@ decl_module! {
let is_root = ensure_root(origin.clone()).is_ok();
for (index, call) in calls.into_iter().enumerate() {
if !is_root && !T::IsCallable::filter(&call) {
Self::deposit_event(Event::<T>::Uncallable(index as u32));
Self::deposit_event(Event::Uncallable(index as u32));
return Ok(())
}
let result = call.dispatch(origin.clone());
if let Err(e) = result {
Self::deposit_event(Event::<T>::BatchInterrupted(index as u32, e.error));
Self::deposit_event(Event::BatchInterrupted(index as u32, e.error));
return Ok(());
}
}
Self::deposit_event(Event::<T>::BatchCompleted);
Self::deposit_event(Event::BatchCompleted);
}
/// Send a call through an indexed pseudonym of the sender.
///
/// Calls must each fulfil the `IsCallable` filter.
/// The call must fulfil only the pre-cleared `IsCallable` filter (i.e. only the level of
/// filtering that remains after calling `take()`).
///
/// NOTE: If you need to ensure that any account-based filtering is honored (i.e. because
/// you expect `proxy` to have been used prior in the call stack and you want it to apply to
/// any sub-accounts), then use `as_limited_sub` instead.
///
/// The dispatch origin for this call must be _Signed_.
///
@@ -309,310 +194,42 @@ decl_module! {
)]
fn as_sub(origin, index: u16, call: Box<<T as Trait>::Call>) -> DispatchResult {
let who = ensure_signed(origin)?;
// We're now executing as a freshly authenticated new account, so the previous call
// restrictions no longer apply.
let _guard = ClearFilterGuard::<T::IsCallable, <T as Trait>::Call>::new();
ensure!(T::IsCallable::filter(&call), Error::<T>::Uncallable);
let pseudonym = Self::sub_account_id(who, index);
call.dispatch(frame_system::RawOrigin::Signed(pseudonym).into())
.map(|_| ()).map_err(|e| e.error)
}
/// Register approval for a dispatch to be made from a deterministic composite account if
/// approved by a total of `threshold - 1` of `other_signatories`.
/// Send a call through an indexed pseudonym of the sender.
///
/// If there are enough, then dispatch the call. Calls must each fulfil the `IsCallable`
/// filter.
/// Calls must each fulfil the `IsCallable` filter; it is not cleared before.
///
/// Payment: `MultisigDepositBase` will be reserved if this is the first approval, plus
/// `threshold` times `MultisigDepositFactor`. It is returned once this dispatch happens or
/// is cancelled.
/// NOTE: If you need to ensure that any account-based filtering is not honored (i.e.
/// because you expect `proxy` to have been used prior in the call stack and you do not want
/// the call restrictions to apply to any sub-accounts), then use `as_sub` instead.
///
/// The dispatch origin for this call must be _Signed_.
///
/// - `threshold`: The total number of approvals for this dispatch before it is executed.
/// - `other_signatories`: The accounts (other than the sender) who can approve this
/// dispatch. May not be empty.
/// - `maybe_timepoint`: If this is the first approval, then this must be `None`. If it is
/// not the first approval, then it must be `Some`, with the timepoint (block number and
/// transaction index) of the first approval transaction.
/// - `call`: The call to be executed.
///
/// NOTE: Unless this is the final approval, you will generally want to use
/// `approve_as_multi` instead, since it only requires a hash of the call.
///
/// Result is equivalent to the dispatched result if `threshold` is exactly `1`. Otherwise
/// on success, result is `Ok` and the result from the interior call, if it was executed,
/// may be found in the deposited `MultisigExecuted` event.
///
/// # <weight>
/// - `O(S + Z + Call)`.
/// - Up to one balance-reserve or unreserve operation.
/// - One passthrough operation, one insert, both `O(S)` where `S` is the number of
/// signatories. `S` is capped by `MaxSignatories`, with weight being proportional.
/// - One call encode & hash, both of complexity `O(Z)` where `Z` is tx-len.
/// - One encode & hash, both of complexity `O(S)`.
/// - Up to one binary search and insert (`O(logS + S)`).
/// - I/O: 1 read `O(S)`, up to 1 mutate `O(S)`. Up to one remove.
/// - One event.
/// - The weight of the `call`.
/// - Storage: inserts one item, value size bounded by `MaxSignatories`, with a
/// deposit taken for its lifetime of
/// `MultisigDepositBase + threshold * MultisigDepositFactor`.
/// -------------------------------
/// - Base Weight:
/// - Create: 46.55 + 0.089 * S µs
/// - Approve: 34.03 + .112 * S µs
/// - Complete: 40.36 + .225 * S µs
/// - DB Weight:
/// - Reads: Multisig Storage, [Caller Account]
/// - Writes: Multisig Storage, [Caller Account]
/// - Plus Call Weight
/// - Base weight: 2.861 µs
/// - Plus the weight of the `call`
/// # </weight>
#[weight = FunctionOf(
|args: (&u16, &Vec<T::AccountId>, &Option<Timepoint<T::BlockNumber>>, &Box<<T as Trait>::Call>)| {
weight_of::as_multi::<T>(args.1.len(),args.3.get_dispatch_info().weight)
},
|args: (&u16, &Vec<T::AccountId>, &Option<Timepoint<T::BlockNumber>>, &Box<<T as Trait>::Call>)| {
args.3.get_dispatch_info().class
|args: (&u16, &Box<<T as Trait>::Call>)| {
args.1.get_dispatch_info().weight.saturating_add(3_000_000)
},
|args: (&u16, &Box<<T as Trait>::Call>)| args.1.get_dispatch_info().class,
Pays::Yes,
)]
fn as_multi(origin,
threshold: u16,
other_signatories: Vec<T::AccountId>,
maybe_timepoint: Option<Timepoint<T::BlockNumber>>,
call: Box<<T as Trait>::Call>,
) -> DispatchResultWithPostInfo {
fn as_limited_sub(origin, index: u16, call: Box<<T as Trait>::Call>) -> DispatchResult {
let who = ensure_signed(origin)?;
ensure!(T::IsCallable::filter(call.as_ref()), Error::<T>::Uncallable);
ensure!(threshold >= 1, Error::<T>::ZeroThreshold);
let max_sigs = T::MaxSignatories::get() as usize;
ensure!(!other_signatories.is_empty(), Error::<T>::TooFewSignatories);
let other_signatories_len = other_signatories.len();
ensure!(other_signatories_len < max_sigs, Error::<T>::TooManySignatories);
let signatories = Self::ensure_sorted_and_insert(other_signatories, who.clone())?;
let id = Self::multi_account_id(&signatories, threshold);
let call_hash = call.using_encoded(blake2_256);
if let Some(mut m) = <Multisigs<T>>::get(&id, call_hash) {
let timepoint = maybe_timepoint.ok_or(Error::<T>::NoTimepoint)?;
ensure!(m.when == timepoint, Error::<T>::WrongTimepoint);
if let Err(pos) = m.approvals.binary_search(&who) {
// we know threshold is greater than zero from the above ensure.
if (m.approvals.len() as u16) < threshold - 1 {
m.approvals.insert(pos, who.clone());
<Multisigs<T>>::insert(&id, call_hash, m);
Self::deposit_event(RawEvent::MultisigApproval(who, timepoint, id, call_hash));
// Call is not made, so the actual weight does not include call
return Ok(Some(weight_of::as_multi::<T>(other_signatories_len, 0)).into())
}
} else {
if (m.approvals.len() as u16) < threshold {
Err(Error::<T>::AlreadyApproved)?
}
}
let result = call.dispatch(frame_system::RawOrigin::Signed(id.clone()).into());
let _ = T::Currency::unreserve(&m.depositor, m.deposit);
<Multisigs<T>>::remove(&id, call_hash);
Self::deposit_event(RawEvent::MultisigExecuted(
who, timepoint, id, call_hash, result.map(|_| ()).map_err(|e| e.error)
));
return Ok(None.into())
} else {
ensure!(maybe_timepoint.is_none(), Error::<T>::UnexpectedTimepoint);
if threshold > 1 {
let deposit = T::MultisigDepositBase::get()
+ T::MultisigDepositFactor::get() * threshold.into();
T::Currency::reserve(&who, deposit)?;
<Multisigs<T>>::insert(&id, call_hash, Multisig {
when: Self::timepoint(),
deposit,
depositor: who.clone(),
approvals: vec![who.clone()],
});
Self::deposit_event(RawEvent::NewMultisig(who, id, call_hash));
// Call is not made, so we can return that weight
return Ok(Some(weight_of::as_multi::<T>(other_signatories_len, 0)).into())
} else {
let result = call.dispatch(frame_system::RawOrigin::Signed(id).into());
match result {
Ok(post_dispatch_info) => {
match post_dispatch_info.actual_weight {
Some(actual_weight) => return Ok(Some(weight_of::as_multi::<T>(other_signatories_len, actual_weight)).into()),
None => return Ok(None.into()),
}
},
Err(err) => {
match err.post_info.actual_weight {
Some(actual_weight) => {
let weight_used = weight_of::as_multi::<T>(other_signatories_len, actual_weight);
return Err(DispatchErrorWithPostInfo { post_info: Some(weight_used).into(), error: err.error.into() })
},
None => {
return Err(err)
}
}
}
}
}
}
}
/// Register approval for a dispatch to be made from a deterministic composite account if
/// approved by a total of `threshold - 1` of `other_signatories`.
///
/// Payment: `MultisigDepositBase` will be reserved if this is the first approval, plus
/// `threshold` times `MultisigDepositFactor`. It is returned once this dispatch happens or
/// is cancelled.
///
/// The dispatch origin for this call must be _Signed_.
///
/// - `threshold`: The total number of approvals for this dispatch before it is executed.
/// - `other_signatories`: The accounts (other than the sender) who can approve this
/// dispatch. May not be empty.
/// - `maybe_timepoint`: If this is the first approval, then this must be `None`. If it is
/// not the first approval, then it must be `Some`, with the timepoint (block number and
/// transaction index) of the first approval transaction.
/// - `call_hash`: The hash of the call to be executed.
///
/// NOTE: If this is the final approval, you will want to use `as_multi` instead.
///
/// # <weight>
/// - `O(S)`.
/// - Up to one balance-reserve or unreserve operation.
/// - One passthrough operation, one insert, both `O(S)` where `S` is the number of
/// signatories. `S` is capped by `MaxSignatories`, with weight being proportional.
/// - One encode & hash, both of complexity `O(S)`.
/// - Up to one binary search and insert (`O(logS + S)`).
/// - I/O: 1 read `O(S)`, up to 1 mutate `O(S)`. Up to one remove.
/// - One event.
/// - Storage: inserts one item, value size bounded by `MaxSignatories`, with a
/// deposit taken for its lifetime of
/// `MultisigDepositBase + threshold * MultisigDepositFactor`.
/// ----------------------------------
/// - Base Weight:
/// - Create: 44.71 + 0.088 * S
/// - Approve: 31.48 + 0.116 * S
/// - DB Weight:
/// - Read: Multisig Storage, [Caller Account]
/// - Write: Multisig Storage, [Caller Account]
/// # </weight>
#[weight = FunctionOf(
|args: (&u16, &Vec<T::AccountId>, &Option<Timepoint<T::BlockNumber>>, &[u8; 32])| {
T::DbWeight::get().reads_writes(1, 1)
.saturating_add(45_000_000)
.saturating_add((args.1.len() as Weight).saturating_mul(120_000))
},
DispatchClass::Normal,
Pays::Yes,
)]
fn approve_as_multi(origin,
threshold: u16,
other_signatories: Vec<T::AccountId>,
maybe_timepoint: Option<Timepoint<T::BlockNumber>>,
call_hash: [u8; 32],
) -> DispatchResult {
let who = ensure_signed(origin)?;
ensure!(threshold >= 1, Error::<T>::ZeroThreshold);
let max_sigs = T::MaxSignatories::get() as usize;
ensure!(!other_signatories.is_empty(), Error::<T>::TooFewSignatories);
ensure!(other_signatories.len() < max_sigs, Error::<T>::TooManySignatories);
let signatories = Self::ensure_sorted_and_insert(other_signatories, who.clone())?;
let id = Self::multi_account_id(&signatories, threshold);
if let Some(mut m) = <Multisigs<T>>::get(&id, call_hash) {
let timepoint = maybe_timepoint.ok_or(Error::<T>::NoTimepoint)?;
ensure!(m.when == timepoint, Error::<T>::WrongTimepoint);
ensure!(m.approvals.len() < threshold as usize, Error::<T>::NoApprovalsNeeded);
if let Err(pos) = m.approvals.binary_search(&who) {
m.approvals.insert(pos, who.clone());
<Multisigs<T>>::insert(&id, call_hash, m);
Self::deposit_event(RawEvent::MultisigApproval(who, timepoint, id, call_hash));
} else {
Err(Error::<T>::AlreadyApproved)?
}
} else {
if threshold > 1 {
ensure!(maybe_timepoint.is_none(), Error::<T>::UnexpectedTimepoint);
let deposit = T::MultisigDepositBase::get()
+ T::MultisigDepositFactor::get() * threshold.into();
T::Currency::reserve(&who, deposit)?;
<Multisigs<T>>::insert(&id, call_hash, Multisig {
when: Self::timepoint(),
deposit,
depositor: who.clone(),
approvals: vec![who.clone()],
});
Self::deposit_event(RawEvent::NewMultisig(who, id, call_hash));
} else {
Err(Error::<T>::NoApprovalsNeeded)?
}
}
Ok(())
}
/// Cancel a pre-existing, on-going multisig transaction. Any deposit reserved previously
/// for this operation will be unreserved on success.
///
/// The dispatch origin for this call must be _Signed_.
///
/// - `threshold`: The total number of approvals for this dispatch before it is executed.
/// - `other_signatories`: The accounts (other than the sender) who can approve this
/// dispatch. May not be empty.
/// - `timepoint`: The timepoint (block number and transaction index) of the first approval
/// transaction for this dispatch.
/// - `call_hash`: The hash of the call to be executed.
///
/// # <weight>
/// - `O(S)`.
/// - Up to one balance-reserve or unreserve operation.
/// - One passthrough operation, one insert, both `O(S)` where `S` is the number of
/// signatories. `S` is capped by `MaxSignatories`, with weight being proportional.
/// - One encode & hash, both of complexity `O(S)`.
/// - One event.
/// - I/O: 1 read `O(S)`, one remove.
/// - Storage: removes one item.
/// ----------------------------------
/// - Base Weight: 37.6 + 0.084 * S
/// - DB Weight:
/// - Read: Multisig Storage, [Caller Account]
/// - Write: Multisig Storage, [Caller Account]
/// # </weight>
#[weight = FunctionOf(
|args: (&u16, &Vec<T::AccountId>, &Timepoint<T::BlockNumber>, &[u8; 32])| {
T::DbWeight::get().reads_writes(1, 1)
.saturating_add(40_000_000)
.saturating_add((args.1.len() as Weight).saturating_mul(100_000))
},
DispatchClass::Normal,
Pays::Yes,
)]
fn cancel_as_multi(origin,
threshold: u16,
other_signatories: Vec<T::AccountId>,
timepoint: Timepoint<T::BlockNumber>,
call_hash: [u8; 32],
) -> DispatchResult {
let who = ensure_signed(origin)?;
ensure!(threshold >= 1, Error::<T>::ZeroThreshold);
let max_sigs = T::MaxSignatories::get() as usize;
ensure!(!other_signatories.is_empty(), Error::<T>::TooFewSignatories);
ensure!(other_signatories.len() < max_sigs, Error::<T>::TooManySignatories);
let signatories = Self::ensure_sorted_and_insert(other_signatories, who.clone())?;
let id = Self::multi_account_id(&signatories, threshold);
let m = <Multisigs<T>>::get(&id, call_hash)
.ok_or(Error::<T>::NotFound)?;
ensure!(m.when == timepoint, Error::<T>::WrongTimepoint);
ensure!(m.depositor == who, Error::<T>::NotOwner);
let _ = T::Currency::unreserve(&m.depositor, m.deposit);
<Multisigs<T>>::remove(&id, call_hash);
Self::deposit_event(RawEvent::MultisigCancelled(who, timepoint, id, call_hash));
Ok(())
ensure!(T::IsCallable::filter(&call), Error::<T>::Uncallable);
let pseudonym = Self::sub_account_id(who, index);
call.dispatch(frame_system::RawOrigin::Signed(pseudonym).into())
.map(|_| ()).map_err(|e| e.error)
}
}
}
@@ -623,42 +240,4 @@ impl<T: Trait> Module<T> {
let entropy = (b"modlpy/utilisuba", who, index).using_encoded(blake2_256);
T::AccountId::decode(&mut &entropy[..]).unwrap_or_default()
}
/// Derive a multi-account ID from the sorted list of accounts and the threshold that are
/// required.
///
/// NOTE: `who` must be sorted. If it is not, then you'll get the wrong answer.
pub fn multi_account_id(who: &[T::AccountId], threshold: u16) -> T::AccountId {
let entropy = (b"modlpy/utilisuba", who, threshold).using_encoded(blake2_256);
T::AccountId::decode(&mut &entropy[..]).unwrap_or_default()
}
/// The current `Timepoint`.
pub fn timepoint() -> Timepoint<T::BlockNumber> {
Timepoint {
height: <system::Module<T>>::block_number(),
index: <system::Module<T>>::extrinsic_index().unwrap_or_default(),
}
}
/// Check that signatories is sorted and doesn't contain sender, then insert sender.
fn ensure_sorted_and_insert(other_signatories: Vec<T::AccountId>, who: T::AccountId)
-> Result<Vec<T::AccountId>, DispatchError>
{
let mut signatories = other_signatories;
let mut maybe_last = None;
let mut index = 0;
for item in signatories.iter() {
if let Some(last) = maybe_last {
ensure!(last < item, Error::<T>::SignatoriesOutOfOrder);
}
if item <= &who {
ensure!(item != &who, Error::<T>::SenderInSignatories);
index += 1;
}
maybe_last = Some(item);
}
signatories.insert(index, who);
Ok(signatories)
}
}
+10 -266
View File
@@ -32,12 +32,11 @@ use crate as utility;
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>,
utility<T>,
utility,
}
}
impl_outer_dispatch! {
@@ -89,8 +88,8 @@ parameter_types! {
}
impl pallet_balances::Trait for Test {
type Balance = u64;
type Event = TestEvent;
type DustRemoval = ();
type Event = TestEvent;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
@@ -108,13 +107,16 @@ impl Filter<Call> for TestIsCallable {
}
}
}
impl FilterStack<Call> for TestIsCallable {
type Stack = ();
fn push(_: impl Fn(&Call) -> bool + 'static) {}
fn pop() {}
fn take() -> Self::Stack { () }
fn restore(_: Self::Stack) {}
}
impl Trait for Test {
type Event = TestEvent;
type Call = Call;
type Currency = Balances;
type MultisigDepositBase = MultisigDepositBase;
type MultisigDepositFactor = MultisigDepositFactor;
type MaxSignatories = MaxSignatories;
type IsCallable = TestIsCallable;
}
type System = frame_system::Module<Test>;
@@ -142,264 +144,6 @@ fn expect_event<E: Into<TestEvent>>(e: E) {
assert_eq!(last_event(), e.into());
}
fn now() -> Timepoint<u64> {
Utility::timepoint()
}
#[test]
fn multisig_deposit_is_taken_and_returned() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 2);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
assert_ok!(Utility::as_multi(Origin::signed(1), 2, vec![2, 3], None, call.clone()));
assert_eq!(Balances::free_balance(1), 2);
assert_eq!(Balances::reserved_balance(1), 3);
assert_ok!(Utility::as_multi(Origin::signed(2), 2, vec![1, 3], Some(now()), call));
assert_eq!(Balances::free_balance(1), 5);
assert_eq!(Balances::reserved_balance(1), 0);
});
}
#[test]
fn cancel_multisig_returns_deposit() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_ok!(Utility::approve_as_multi(Origin::signed(1), 3, vec![2, 3], None, hash.clone()));
assert_ok!(Utility::approve_as_multi(Origin::signed(2), 3, vec![1, 3], Some(now()), hash.clone()));
assert_eq!(Balances::free_balance(1), 6);
assert_eq!(Balances::reserved_balance(1), 4);
assert_ok!(
Utility::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash.clone()),
);
assert_eq!(Balances::free_balance(1), 10);
assert_eq!(Balances::reserved_balance(1), 0);
});
}
#[test]
fn timepoint_checking_works() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 2);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_noop!(
Utility::approve_as_multi(Origin::signed(2), 2, vec![1, 3], Some(now()), hash.clone()),
Error::<Test>::UnexpectedTimepoint,
);
assert_ok!(Utility::approve_as_multi(Origin::signed(1), 2, vec![2, 3], None, hash));
assert_noop!(
Utility::as_multi(Origin::signed(2), 2, vec![1, 3], None, call.clone()),
Error::<Test>::NoTimepoint,
);
let later = Timepoint { index: 1, .. now() };
assert_noop!(
Utility::as_multi(Origin::signed(2), 2, vec![1, 3], Some(later), call.clone()),
Error::<Test>::WrongTimepoint,
);
});
}
#[test]
fn multisig_2_of_3_works() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 2);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_ok!(Utility::approve_as_multi(Origin::signed(1), 2, vec![2, 3], None, hash));
assert_eq!(Balances::free_balance(6), 0);
assert_ok!(Utility::as_multi(Origin::signed(2), 2, vec![1, 3], Some(now()), call));
assert_eq!(Balances::free_balance(6), 15);
});
}
#[test]
fn multisig_3_of_3_works() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 3);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_ok!(Utility::approve_as_multi(Origin::signed(1), 3, vec![2, 3], None, hash.clone()));
assert_ok!(Utility::approve_as_multi(Origin::signed(2), 3, vec![1, 3], Some(now()), hash.clone()));
assert_eq!(Balances::free_balance(6), 0);
assert_ok!(Utility::as_multi(Origin::signed(3), 3, vec![1, 2], Some(now()), call));
assert_eq!(Balances::free_balance(6), 15);
});
}
#[test]
fn cancel_multisig_works() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_ok!(Utility::approve_as_multi(Origin::signed(1), 3, vec![2, 3], None, hash.clone()));
assert_ok!(Utility::approve_as_multi(Origin::signed(2), 3, vec![1, 3], Some(now()), hash.clone()));
assert_noop!(
Utility::cancel_as_multi(Origin::signed(2), 3, vec![1, 3], now(), hash.clone()),
Error::<Test>::NotOwner,
);
assert_ok!(
Utility::cancel_as_multi(Origin::signed(1), 3, vec![2, 3], now(), hash.clone()),
);
});
}
#[test]
fn multisig_2_of_3_as_multi_works() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 2);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
assert_ok!(Utility::as_multi(Origin::signed(1), 2, vec![2, 3], None, call.clone()));
assert_eq!(Balances::free_balance(6), 0);
assert_ok!(Utility::as_multi(Origin::signed(2), 2, vec![1, 3], Some(now()), call));
assert_eq!(Balances::free_balance(6), 15);
});
}
#[test]
fn multisig_2_of_3_as_multi_with_many_calls_works() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 2);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call1 = Box::new(Call::Balances(BalancesCall::transfer(6, 10)));
let call2 = Box::new(Call::Balances(BalancesCall::transfer(7, 5)));
assert_ok!(Utility::as_multi(Origin::signed(1), 2, vec![2, 3], None, call1.clone()));
assert_ok!(Utility::as_multi(Origin::signed(2), 2, vec![1, 3], None, call2.clone()));
assert_ok!(Utility::as_multi(Origin::signed(3), 2, vec![1, 2], Some(now()), call2));
assert_ok!(Utility::as_multi(Origin::signed(3), 2, vec![1, 2], Some(now()), call1));
assert_eq!(Balances::free_balance(6), 10);
assert_eq!(Balances::free_balance(7), 5);
});
}
#[test]
fn multisig_2_of_3_cannot_reissue_same_call() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 2);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 10)));
assert_ok!(Utility::as_multi(Origin::signed(1), 2, vec![2, 3], None, call.clone()));
assert_ok!(Utility::as_multi(Origin::signed(2), 2, vec![1, 3], Some(now()), call.clone()));
assert_eq!(Balances::free_balance(multi), 5);
assert_ok!(Utility::as_multi(Origin::signed(1), 2, vec![2, 3], None, call.clone()));
assert_ok!(Utility::as_multi(Origin::signed(3), 2, vec![1, 2], Some(now()), call.clone()));
let err = DispatchError::from(BalancesError::<Test, _>::InsufficientBalance).stripped();
expect_event(RawEvent::MultisigExecuted(3, now(), multi, call.using_encoded(blake2_256), Err(err)));
});
}
#[test]
fn zero_threshold_fails() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
assert_noop!(
Utility::as_multi(Origin::signed(1), 0, vec![2], None, call),
Error::<Test>::ZeroThreshold,
);
});
}
#[test]
fn too_many_signatories_fails() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
assert_noop!(
Utility::as_multi(Origin::signed(1), 2, vec![2, 3, 4], None, call.clone()),
Error::<Test>::TooManySignatories,
);
});
}
#[test]
fn duplicate_approvals_are_ignored() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_ok!(Utility::approve_as_multi(Origin::signed(1), 2, vec![2, 3], None, hash.clone()));
assert_noop!(
Utility::approve_as_multi(Origin::signed(1), 2, vec![2, 3], Some(now()), hash.clone()),
Error::<Test>::AlreadyApproved,
);
assert_ok!(Utility::approve_as_multi(Origin::signed(2), 2, vec![1, 3], Some(now()), hash.clone()));
assert_noop!(
Utility::approve_as_multi(Origin::signed(3), 2, vec![1, 2], Some(now()), hash.clone()),
Error::<Test>::NoApprovalsNeeded,
);
});
}
#[test]
fn multisig_1_of_3_works() {
new_test_ext().execute_with(|| {
let multi = Utility::multi_account_id(&[1, 2, 3][..], 1);
assert_ok!(Balances::transfer(Origin::signed(1), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let hash = call.using_encoded(blake2_256);
assert_noop!(
Utility::approve_as_multi(Origin::signed(1), 1, vec![2, 3], None, hash.clone()),
Error::<Test>::NoApprovalsNeeded,
);
assert_noop!(
Utility::as_multi(Origin::signed(4), 1, vec![2, 3], None, call.clone()),
BalancesError::<Test, _>::InsufficientBalance,
);
assert_ok!(Utility::as_multi(Origin::signed(1), 1, vec![2, 3], None, call));
assert_eq!(Balances::free_balance(6), 15);
});
}
#[test]
fn multisig_filters() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::System(frame_system::Call::remark(vec![])));
assert_noop!(
Utility::as_multi(Origin::signed(1), 1, vec![], None, call.clone()),
Error::<Test>::Uncallable,
);
});
}
#[test]
fn as_sub_works() {
new_test_ext().execute_with(|| {
@@ -469,7 +213,7 @@ fn batch_with_signed_filters() {
Call::System(frame_system::Call::remark(vec![]))
]),
);
expect_event(RawEvent::Uncallable(0));
expect_event(Event::Uncallable(0));
});
}