// 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. //! # Multisig Module //! A module for doing multisig dispatch. //! //! - [`multisig::Trait`](./trait.Trait.html) //! - [`Call`](./enum.Call.html) //! //! ## Overview //! //! This module contains functionality for multi-signature dispatch, 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 //! //! ### Dispatchable Functions //! //! * `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 // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] use sp_std::prelude::*; use codec::{Encode, Decode}; 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, FilterStack, ClearFilterGuard}, weights::{Weight, GetDispatchInfo, DispatchClass, Pays}, dispatch::{DispatchResultWithPostInfo, DispatchErrorWithPostInfo, PostDispatchInfo}, }; use frame_system::{self as system, ensure_signed}; use sp_runtime::{DispatchError, DispatchResult, traits::Dispatchable}; mod tests; mod benchmarking; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; /// Configuration trait. pub trait Trait: frame_system::Trait { /// The overarching event type. type Event: From> + Into<::Event>; /// The overarching call type. type Call: Parameter + Dispatchable + GetDispatchInfo + From>; /// The currency mechanism. type Currency: ReservableCurrency; /// 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 DepositBase: Get>; /// 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 DepositFactor: Get>; /// The maximum amount of signatories allowed in the multisig. type MaxSignatories: Get; /// Is a given call compatible with the proxying subsystem? type IsCallable: FilterStack<::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 { /// 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 { /// The extrinsic when the multisig operation was opened. when: Timepoint, /// 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, } decl_storage! { trait Store for Module as Multisig { /// The set of open multisig operations. pub Multisigs: double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) [u8; 32] => Option, T::AccountId>>; } } decl_error! { pub enum Error for Module { /// 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, } } decl_event! { /// Events type. pub enum Event where AccountId = ::AccountId, BlockNumber = ::BlockNumber, CallHash = [u8; 32] { /// 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, 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, 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, AccountId, CallHash), /// A call with a `false` IsCallable filter was attempted. Uncallable(u32), } } 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(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 for enum Call where origin: T::Origin { type Error = Error; /// Deposit one of this module's events by using the default implementation. fn deposit_event() = default; fn on_runtime_upgrade() -> Weight { // Utility.Multisigs -> Multisig.Multisigs use frame_support::migration::{StorageIterator, put_storage_value}; for (key, value) in StorageIterator::< Multisig, T::AccountId> >::new(b"Utility", b"Multisigs").drain() { put_storage_value(b"Multisig", b"Multisigs", &key, value); } 1_000_000_000 } /// Register approval for a dispatch to be made from a deterministic composite account if /// approved by a total of `threshold - 1` of `other_signatories`. /// /// If there are enough, then dispatch the call. Calls must each fulfil the `IsCallable` /// filter. /// /// Payment: `DepositBase` will be reserved if this is the first approval, plus /// `threshold` times `DepositFactor`. 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`: 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. /// /// # /// - `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 /// `DepositBase + threshold * DepositFactor`. /// ------------------------------- /// - 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 /// # #[weight = ( weight_of::as_multi::(other_signatories.len(), call.get_dispatch_info().weight), call.get_dispatch_info().class, Pays::Yes, )] fn as_multi(origin, threshold: u16, other_signatories: Vec, maybe_timepoint: Option>, call: Box<::Call>, ) -> DispatchResultWithPostInfo { 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::::Call>::new(); ensure!(T::IsCallable::filter(call.as_ref()), Error::::Uncallable); ensure!(threshold >= 1, Error::::ZeroThreshold); let max_sigs = T::MaxSignatories::get() as usize; ensure!(!other_signatories.is_empty(), Error::::TooFewSignatories); let other_signatories_len = other_signatories.len(); ensure!(other_signatories_len < max_sigs, Error::::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) = >::get(&id, call_hash) { let timepoint = maybe_timepoint.ok_or(Error::::NoTimepoint)?; ensure!(m.when == timepoint, Error::::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()); >::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::(other_signatories_len, 0)).into()) } } else { if (m.approvals.len() as u16) < threshold { Err(Error::::AlreadyApproved)? } } let result = call.dispatch(frame_system::RawOrigin::Signed(id.clone()).into()); let _ = T::Currency::unreserve(&m.depositor, m.deposit); >::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::::UnexpectedTimepoint); if threshold > 1 { let deposit = T::DepositBase::get() + T::DepositFactor::get() * threshold.into(); T::Currency::reserve(&who, deposit)?; >::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::(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::(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::(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: `DepositBase` will be reserved if this is the first approval, plus /// `threshold` times `DepositFactor`. 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. /// /// # /// - `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 /// `DepositBase + threshold * DepositFactor`. /// ---------------------------------- /// - 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 = ( T::DbWeight::get().reads_writes(1, 1) .saturating_add(45_000_000) .saturating_add((other_signatories.len() as Weight).saturating_mul(120_000)), DispatchClass::Normal, Pays::Yes, )] fn approve_as_multi(origin, threshold: u16, other_signatories: Vec, maybe_timepoint: Option>, call_hash: [u8; 32], ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(threshold >= 1, Error::::ZeroThreshold); let max_sigs = T::MaxSignatories::get() as usize; ensure!(!other_signatories.is_empty(), Error::::TooFewSignatories); ensure!(other_signatories.len() < max_sigs, Error::::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) = >::get(&id, call_hash) { let timepoint = maybe_timepoint.ok_or(Error::::NoTimepoint)?; ensure!(m.when == timepoint, Error::::WrongTimepoint); ensure!(m.approvals.len() < threshold as usize, Error::::NoApprovalsNeeded); if let Err(pos) = m.approvals.binary_search(&who) { m.approvals.insert(pos, who.clone()); >::insert(&id, call_hash, m); Self::deposit_event(RawEvent::MultisigApproval(who, timepoint, id, call_hash)); } else { Err(Error::::AlreadyApproved)? } } else { if threshold > 1 { ensure!(maybe_timepoint.is_none(), Error::::UnexpectedTimepoint); let deposit = T::DepositBase::get() + T::DepositFactor::get() * threshold.into(); T::Currency::reserve(&who, deposit)?; >::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::::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. /// /// # /// - `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 = ( T::DbWeight::get().reads_writes(1, 1) .saturating_add(40_000_000) .saturating_add((other_signatories.len() as Weight).saturating_mul(100_000)), DispatchClass::Normal, Pays::Yes, )] fn cancel_as_multi(origin, threshold: u16, other_signatories: Vec, timepoint: Timepoint, call_hash: [u8; 32], ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(threshold >= 1, Error::::ZeroThreshold); let max_sigs = T::MaxSignatories::get() as usize; ensure!(!other_signatories.is_empty(), Error::::TooFewSignatories); ensure!(other_signatories.len() < max_sigs, Error::::TooManySignatories); let signatories = Self::ensure_sorted_and_insert(other_signatories, who.clone())?; let id = Self::multi_account_id(&signatories, threshold); let m = >::get(&id, call_hash) .ok_or(Error::::NotFound)?; ensure!(m.when == timepoint, Error::::WrongTimepoint); ensure!(m.depositor == who, Error::::NotOwner); let _ = T::Currency::unreserve(&m.depositor, m.deposit); >::remove(&id, call_hash); Self::deposit_event(RawEvent::MultisigCancelled(who, timepoint, id, call_hash)); Ok(()) } } } impl Module { /// 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 { Timepoint { height: >::block_number(), index: >::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, who: T::AccountId) -> Result, 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::::SignatoriesOutOfOrder); } if item <= &who { ensure!(item != &who, Error::::SenderInSignatories); index += 1; } maybe_last = Some(item); } signatories.insert(index, who); Ok(signatories) } }