mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-18 07:11:03 +00:00
Stored call in multisig (#6319)
* Stored call in multisig * Docs. * Benchmarks. * Fix * Update frame/multisig/src/lib.rs Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * patch benchmarks * Minor grumbles. * Update as_multi weight * Fixes and refactoring. * Split out threshold=1 and opaquify Call. * Compiles, tests pass, weights are broken * Update benchmarks, add working tests * Add benchmark to threshold 1, add event too * suppress warning for now * @xlc improvment nit * Update weight and tests * Test for weight check * Fix line width * one more line width error * Apply suggestions from code review Co-authored-by: Alexander Popiak <alexander.popiak@parity.io> * fix merge * more @apopiak feedback * Multisig handles no preimage * Optimize return weight after dispatch * Error on failed deposit. Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> Co-authored-by: Alexander Popiak <alexander.popiak@parity.io>
This commit is contained in:
+323
-158
@@ -51,11 +51,11 @@ 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},
|
||||
weights::{Weight, GetDispatchInfo, DispatchClass, Pays},
|
||||
weights::{Weight, GetDispatchInfo, constants::{WEIGHT_PER_NANOS, WEIGHT_PER_MICROS}},
|
||||
dispatch::{DispatchResultWithPostInfo, DispatchErrorWithPostInfo, PostDispatchInfo},
|
||||
};
|
||||
use frame_system::{self as system, ensure_signed};
|
||||
use sp_runtime::{DispatchError, DispatchResult, traits::Dispatchable};
|
||||
use frame_system::{self as system, ensure_signed, RawOrigin};
|
||||
use sp_runtime::{DispatchError, DispatchResult, traits::{Dispatchable, Zero}};
|
||||
|
||||
mod tests;
|
||||
mod benchmarking;
|
||||
@@ -74,10 +74,12 @@ pub trait Trait: frame_system::Trait {
|
||||
/// The currency mechanism.
|
||||
type Currency: ReservableCurrency<Self::AccountId>;
|
||||
|
||||
/// The base amount of currency needed to reserve for creating a multisig execution.
|
||||
/// The base amount of currency needed to reserve for creating a multisig execution or to store
|
||||
/// a dispatch call for later.
|
||||
///
|
||||
/// This is held for an additional storage item whose value size is
|
||||
/// `4 + sizeof((BlockNumber, Balance, AccountId))` bytes.
|
||||
/// `4 + sizeof((BlockNumber, Balance, AccountId))` bytes and whose key size is
|
||||
/// `32 + sizeof(AccountId)` bytes.
|
||||
type DepositBase: Get<BalanceOf<Self>>;
|
||||
|
||||
/// The amount of currency needed per unit threshold when creating a multisig execution.
|
||||
@@ -119,13 +121,15 @@ decl_storage! {
|
||||
pub Multisigs: double_map
|
||||
hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) [u8; 32]
|
||||
=> Option<Multisig<T::BlockNumber, BalanceOf<T>, T::AccountId>>;
|
||||
|
||||
pub Calls: map hasher(identity) [u8; 32] => Option<(Vec<u8>, T::AccountId, BalanceOf<T>)>;
|
||||
}
|
||||
}
|
||||
|
||||
decl_error! {
|
||||
pub enum Error for Module<T: Trait> {
|
||||
/// Threshold is too low (zero).
|
||||
ZeroThreshold,
|
||||
/// Threshold must be 2 or greater.
|
||||
MinimumThreshold,
|
||||
/// Call is already approved by this signatory.
|
||||
AlreadyApproved,
|
||||
/// Call doesn't need any (more) approvals.
|
||||
@@ -148,6 +152,10 @@ decl_error! {
|
||||
WrongTimepoint,
|
||||
/// A timepoint was given, yet no multisig operation is underway.
|
||||
UnexpectedTimepoint,
|
||||
/// The maximum weight information provided was too low.
|
||||
WeightTooLow,
|
||||
/// The data to be stored is already stored.
|
||||
AlreadyStored,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,20 +184,48 @@ decl_event! {
|
||||
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]
|
||||
/// - Base Weight: 33.72 + 0.002 * Z µs
|
||||
/// - DB Weight: None
|
||||
/// - 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))
|
||||
pub fn as_multi_threshold_1<T: Trait>(
|
||||
call_len: usize,
|
||||
call_weight: Weight,
|
||||
) -> Weight {
|
||||
(34 * WEIGHT_PER_MICROS)
|
||||
.saturating_add((2 * WEIGHT_PER_NANOS).saturating_mul(call_len as Weight))
|
||||
.saturating_add(call_weight)
|
||||
}
|
||||
|
||||
/// - Base Weight:
|
||||
/// - Create: 38.82 + 0.121 * S + .001 * Z µs
|
||||
/// - Create w/ Store: 54.22 + 0.120 * S + .003 * Z µs
|
||||
/// - Approve: 29.86 + 0.143 * S + .001 * Z µs
|
||||
/// - Complete: 39.55 + 0.267 * S + .002 * Z µs
|
||||
/// - DB Weight:
|
||||
/// - Reads: Multisig Storage, [Caller Account], Calls, Depositor Account
|
||||
/// - Writes: Multisig Storage, [Caller Account], Calls, Depositor Account
|
||||
/// - Plus Call Weight
|
||||
pub fn as_multi<T: Trait>(
|
||||
sig_len: usize,
|
||||
call_len: usize,
|
||||
call_weight: Weight,
|
||||
calls_write: bool,
|
||||
refunded: bool,
|
||||
) -> Weight {
|
||||
call_weight
|
||||
.saturating_add(55 * WEIGHT_PER_MICROS)
|
||||
.saturating_add((250 * WEIGHT_PER_NANOS).saturating_mul(sig_len as Weight))
|
||||
.saturating_add((3 * WEIGHT_PER_NANOS).saturating_mul(call_len as Weight))
|
||||
.saturating_add(T::DbWeight::get().reads_writes(1, 1)) // Multisig read/write
|
||||
.saturating_add(T::DbWeight::get().reads(1)) // Calls read
|
||||
.saturating_add(T::DbWeight::get().writes(calls_write.into())) // Calls write
|
||||
.saturating_add(T::DbWeight::get().reads_writes(refunded.into(), refunded.into())) // Deposit refunded
|
||||
}
|
||||
}
|
||||
|
||||
enum CallOrHash {
|
||||
Call(Vec<u8>, bool),
|
||||
Hash([u8; 32]),
|
||||
}
|
||||
|
||||
decl_module! {
|
||||
@@ -210,6 +246,66 @@ decl_module! {
|
||||
1_000_000_000
|
||||
}
|
||||
|
||||
/// Immediately dispatch a multi-signature call using a single approval from the caller.
|
||||
///
|
||||
/// The dispatch origin for this call must be _Signed_.
|
||||
///
|
||||
/// - `other_signatories`: The accounts (other than the sender) who are part of the
|
||||
/// multi-signature, but do not participate in the approval process.
|
||||
/// - `call`: The call to be executed.
|
||||
///
|
||||
/// Result is equivalent to the dispatched result.
|
||||
///
|
||||
/// # <weight>
|
||||
/// O(Z + C) where Z is the length of the call and C its execution weight.
|
||||
/// -------------------------------
|
||||
/// - Base Weight: 33.72 + 0.002 * Z µs
|
||||
/// - DB Weight: None
|
||||
/// - Plus Call Weight
|
||||
/// # </weight>
|
||||
#[weight = (
|
||||
weight_of::as_multi_threshold_1::<T>(
|
||||
call.using_encoded(|c| c.len()),
|
||||
call.get_dispatch_info().weight
|
||||
),
|
||||
call.get_dispatch_info().class,
|
||||
)]
|
||||
fn as_multi_threshold_1(origin,
|
||||
other_signatories: Vec<T::AccountId>,
|
||||
call: Box<<T as Trait>::Call>,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
let who = ensure_signed(origin)?;
|
||||
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, 1);
|
||||
|
||||
let call_len = call.using_encoded(|c| c.len());
|
||||
let result = call.dispatch(RawOrigin::Signed(id.clone()).into());
|
||||
|
||||
result.map(|post_dispatch_info| post_dispatch_info.actual_weight
|
||||
.map(|actual_weight| weight_of::as_multi_threshold_1::<T>(
|
||||
call_len,
|
||||
actual_weight,
|
||||
))
|
||||
.into()
|
||||
).map_err(|err| match err.post_info.actual_weight {
|
||||
Some(actual_weight) => {
|
||||
let weight_used = weight_of::as_multi_threshold_1::<T>(
|
||||
call_len,
|
||||
actual_weight,
|
||||
);
|
||||
let post_info = Some(weight_used).into();
|
||||
let error = err.error.into();
|
||||
DispatchErrorWithPostInfo { post_info, error }
|
||||
},
|
||||
None => 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`.
|
||||
///
|
||||
@@ -252,99 +348,32 @@ decl_module! {
|
||||
/// `DepositBase + threshold * DepositFactor`.
|
||||
/// -------------------------------
|
||||
/// - Base Weight:
|
||||
/// - Create: 46.55 + 0.089 * S µs
|
||||
/// - Approve: 34.03 + .112 * S µs
|
||||
/// - Complete: 40.36 + .225 * S µs
|
||||
/// - Create: 41.89 + 0.118 * S + .002 * Z µs
|
||||
/// - Create w/ Store: 53.57 + 0.119 * S + .003 * Z µs
|
||||
/// - Approve: 31.39 + 0.136 * S + .002 * Z µs
|
||||
/// - Complete: 39.94 + 0.26 * S + .002 * Z µs
|
||||
/// - DB Weight:
|
||||
/// - Reads: Multisig Storage, [Caller Account]
|
||||
/// - Writes: Multisig Storage, [Caller Account]
|
||||
/// - Reads: Multisig Storage, [Caller Account], Calls (if `store_call`)
|
||||
/// - Writes: Multisig Storage, [Caller Account], Calls (if `store_call`)
|
||||
/// - Plus Call Weight
|
||||
/// # </weight>
|
||||
#[weight = (
|
||||
weight_of::as_multi::<T>(other_signatories.len(), call.get_dispatch_info().weight),
|
||||
call.get_dispatch_info().class,
|
||||
Pays::Yes,
|
||||
#[weight = weight_of::as_multi::<T>(
|
||||
other_signatories.len(),
|
||||
call.len(),
|
||||
*max_weight,
|
||||
true, // assume worst case: calls write
|
||||
true, // assume worst case: refunded
|
||||
)]
|
||||
fn as_multi(origin,
|
||||
threshold: u16,
|
||||
other_signatories: Vec<T::AccountId>,
|
||||
maybe_timepoint: Option<Timepoint<T::BlockNumber>>,
|
||||
call: Box<<T as Trait>::Call>,
|
||||
call: Vec<u8>,
|
||||
store_call: bool,
|
||||
max_weight: Weight,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
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);
|
||||
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::DepositBase::get()
|
||||
+ T::DepositFactor::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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::operate(who, threshold, other_signatories, maybe_timepoint, CallOrHash::Call(call, store_call), max_weight)
|
||||
}
|
||||
|
||||
/// Register approval for a dispatch to be made from a deterministic composite account if
|
||||
@@ -386,57 +415,22 @@ decl_module! {
|
||||
/// - Read: Multisig Storage, [Caller Account]
|
||||
/// - Write: Multisig Storage, [Caller Account]
|
||||
/// # </weight>
|
||||
#[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,
|
||||
#[weight = weight_of::as_multi::<T>(
|
||||
other_signatories.len(),
|
||||
0, // call_len is zero in this case
|
||||
*max_weight,
|
||||
true, // assume worst case: calls write
|
||||
true, // assume worst case: refunded
|
||||
)]
|
||||
fn approve_as_multi(origin,
|
||||
threshold: u16,
|
||||
other_signatories: Vec<T::AccountId>,
|
||||
maybe_timepoint: Option<Timepoint<T::BlockNumber>>,
|
||||
call_hash: [u8; 32],
|
||||
) -> DispatchResult {
|
||||
max_weight: Weight,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
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::DepositBase::get()
|
||||
+ T::DepositFactor::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(())
|
||||
Self::operate(who, threshold, other_signatories, maybe_timepoint, CallOrHash::Hash(call_hash), max_weight)
|
||||
}
|
||||
|
||||
/// Cancel a pre-existing, on-going multisig transaction. Any deposit reserved previously
|
||||
@@ -461,18 +455,15 @@ decl_module! {
|
||||
/// - I/O: 1 read `O(S)`, one remove.
|
||||
/// - Storage: removes one item.
|
||||
/// ----------------------------------
|
||||
/// - Base Weight: 37.6 + 0.084 * S
|
||||
/// - Base Weight: 36.07 + 0.124 * S
|
||||
/// - DB Weight:
|
||||
/// - Read: Multisig Storage, [Caller Account]
|
||||
/// - Write: Multisig Storage, [Caller Account]
|
||||
/// - Read: Multisig Storage, [Caller Account], Refund Account, Calls
|
||||
/// - Write: Multisig Storage, [Caller Account], Refund Account, Calls
|
||||
/// # </weight>
|
||||
#[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,
|
||||
)]
|
||||
#[weight = T::DbWeight::get().reads_writes(3, 3)
|
||||
.saturating_add(36 * WEIGHT_PER_MICROS)
|
||||
.saturating_add((other_signatories.len() as Weight).saturating_mul(100 * WEIGHT_PER_NANOS))
|
||||
]
|
||||
fn cancel_as_multi(origin,
|
||||
threshold: u16,
|
||||
other_signatories: Vec<T::AccountId>,
|
||||
@@ -480,7 +471,7 @@ decl_module! {
|
||||
call_hash: [u8; 32],
|
||||
) -> DispatchResult {
|
||||
let who = ensure_signed(origin)?;
|
||||
ensure!(threshold >= 1, Error::<T>::ZeroThreshold);
|
||||
ensure!(threshold >= 2, Error::<T>::MinimumThreshold);
|
||||
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);
|
||||
@@ -494,7 +485,8 @@ decl_module! {
|
||||
ensure!(m.depositor == who, Error::<T>::NotOwner);
|
||||
|
||||
let _ = T::Currency::unreserve(&m.depositor, m.deposit);
|
||||
<Multisigs<T>>::remove(&id, call_hash);
|
||||
<Multisigs<T>>::remove(&id, &call_hash);
|
||||
Self::clear_call(&call_hash);
|
||||
|
||||
Self::deposit_event(RawEvent::MultisigCancelled(who, timepoint, id, call_hash));
|
||||
Ok(())
|
||||
@@ -512,6 +504,169 @@ impl<T: Trait> Module<T> {
|
||||
T::AccountId::decode(&mut &entropy[..]).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn operate(
|
||||
who: T::AccountId,
|
||||
threshold: u16,
|
||||
other_signatories: Vec<T::AccountId>,
|
||||
maybe_timepoint: Option<Timepoint<T::BlockNumber>>,
|
||||
call_or_hash: CallOrHash,
|
||||
max_weight: Weight,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
ensure!(threshold >= 2, Error::<T>::MinimumThreshold);
|
||||
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);
|
||||
|
||||
// Threshold > 1; this means it's a multi-step operation. We extract the `call_hash`.
|
||||
let (call_hash, call_len, maybe_call, store) = match call_or_hash {
|
||||
CallOrHash::Call(call, should_store) => {
|
||||
let call_hash = blake2_256(&call);
|
||||
let call_len = call.len();
|
||||
(call_hash, call_len, Some(call), should_store)
|
||||
}
|
||||
CallOrHash::Hash(h) => (h, 0, None, false),
|
||||
};
|
||||
|
||||
// Branch on whether the operation has already started or not.
|
||||
if let Some(mut m) = <Multisigs<T>>::get(&id, call_hash) {
|
||||
// Yes; ensure that the timepoint exists and agrees.
|
||||
let timepoint = maybe_timepoint.ok_or(Error::<T>::NoTimepoint)?;
|
||||
ensure!(m.when == timepoint, Error::<T>::WrongTimepoint);
|
||||
|
||||
// Ensure that either we have not yet signed or that it is at threshold.
|
||||
let mut approvals = m.approvals.len() as u16;
|
||||
// We only bother with the approval if we're below threshold.
|
||||
let maybe_pos = m.approvals.binary_search(&who).err().filter(|_| approvals < threshold);
|
||||
// Bump approvals if not yet voted and the vote is needed.
|
||||
if maybe_pos.is_some() { approvals += 1; }
|
||||
|
||||
// We only bother fetching/decoding call if we know that we're ready to execute.
|
||||
let maybe_approved_call = if approvals >= threshold {
|
||||
Self::get_call(&call_hash, maybe_call.as_ref().map(|c| c.as_ref()))
|
||||
} else { None };
|
||||
|
||||
if let Some(call) = maybe_approved_call {
|
||||
// verify weight
|
||||
ensure!(call.get_dispatch_info().weight <= max_weight, Error::<T>::WeightTooLow);
|
||||
|
||||
let result = call.dispatch(RawOrigin::Signed(id.clone()).into());
|
||||
T::Currency::unreserve(&m.depositor, m.deposit);
|
||||
<Multisigs<T>>::remove(&id, call_hash);
|
||||
Self::clear_call(&call_hash);
|
||||
Self::deposit_event(RawEvent::MultisigExecuted(
|
||||
who, timepoint, id, call_hash, result.map(|_| ()).map_err(|e| e.error)
|
||||
));
|
||||
Ok(get_result_weight(result).map(|actual_weight| weight_of::as_multi::<T>(
|
||||
other_signatories_len,
|
||||
call_len,
|
||||
actual_weight,
|
||||
true, // Call is removed
|
||||
true, // User is refunded
|
||||
)).into())
|
||||
} else {
|
||||
// We cannot dispatch the call now; either it isn't available, or it is, but we
|
||||
// don't have threshold approvals even with our signature.
|
||||
|
||||
// Store the call if desired.
|
||||
let stored = if let Some(data) = maybe_call.filter(|_| store) {
|
||||
Self::store_call_and_reserve(who.clone(), &call_hash, data, BalanceOf::<T>::zero())?;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if let Some(pos) = maybe_pos {
|
||||
// Record approval.
|
||||
m.approvals.insert(pos, who.clone());
|
||||
<Multisigs<T>>::insert(&id, call_hash, m);
|
||||
Self::deposit_event(RawEvent::MultisigApproval(who, timepoint, id, call_hash));
|
||||
} else {
|
||||
// If we already approved and didn't store the Call, then this was useless and
|
||||
// we report an error.
|
||||
ensure!(stored, Error::<T>::AlreadyApproved);
|
||||
}
|
||||
|
||||
// Call is not made, so the actual weight does not include call
|
||||
Ok(Some(weight_of::as_multi::<T>(
|
||||
other_signatories_len,
|
||||
call_len,
|
||||
0,
|
||||
stored, // Call stored?
|
||||
false, // No refund
|
||||
)).into())
|
||||
}
|
||||
} else {
|
||||
// Not yet started; there should be no timepoint given.
|
||||
ensure!(maybe_timepoint.is_none(), Error::<T>::UnexpectedTimepoint);
|
||||
|
||||
// Just start the operation by recording it in storage.
|
||||
let deposit = T::DepositBase::get() + T::DepositFactor::get() * threshold.into();
|
||||
|
||||
// Store the call if desired.
|
||||
let stored = if let Some(data) = maybe_call.filter(|_| store) {
|
||||
Self::store_call_and_reserve(who.clone(), &call_hash, data, deposit)?;
|
||||
true
|
||||
} else {
|
||||
T::Currency::reserve(&who, deposit)?;
|
||||
false
|
||||
};
|
||||
|
||||
<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,
|
||||
call_len,
|
||||
0,
|
||||
stored, // Call stored?
|
||||
false, // No refund
|
||||
)).into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Place a call's encoded data in storage, reserving funds as appropriate.
|
||||
///
|
||||
/// We store `data` here because storing `call` would result in needing another `.encode`.
|
||||
///
|
||||
/// Returns a `bool` indicating whether the data did end up being stored.
|
||||
fn store_call_and_reserve(who: T::AccountId, hash: &[u8; 32], data: Vec<u8>, other_deposit: BalanceOf<T>)
|
||||
-> DispatchResult
|
||||
{
|
||||
ensure!(!Calls::<T>::contains_key(hash), Error::<T>::AlreadyStored);
|
||||
let deposit = other_deposit + T::DepositBase::get()
|
||||
+ T::DepositFactor::get() * BalanceOf::<T>::from(((data.len() + 31) / 32) as u32);
|
||||
T::Currency::reserve(&who, deposit)?;
|
||||
Calls::<T>::insert(&hash, (data, who, deposit));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Attempt to decode and return the call, provided by the user or from storage.
|
||||
fn get_call(hash: &[u8; 32], maybe_known: Option<&[u8]>) -> Option<<T as Trait>::Call> {
|
||||
maybe_known.map_or_else(|| {
|
||||
Calls::<T>::get(hash).and_then(|(data, ..)| {
|
||||
Decode::decode(&mut &data[..]).ok()
|
||||
})
|
||||
}, |data| {
|
||||
Decode::decode(&mut &data[..]).ok()
|
||||
})
|
||||
}
|
||||
|
||||
/// Attempt to remove a call from storage, returning any deposit on it to the owner.
|
||||
fn clear_call(hash: &[u8; 32]) {
|
||||
if let Some((_, who, deposit)) = Calls::<T>::take(hash) {
|
||||
T::Currency::unreserve(&who, deposit);
|
||||
}
|
||||
}
|
||||
|
||||
/// The current `Timepoint`.
|
||||
pub fn timepoint() -> Timepoint<T::BlockNumber> {
|
||||
Timepoint {
|
||||
@@ -541,3 +696,13 @@ impl<T: Trait> Module<T> {
|
||||
Ok(signatories)
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the weight of a dispatch call result as an `Option`.
|
||||
///
|
||||
/// Will return the weight regardless of what the state of the result is.
|
||||
fn get_result_weight(result: DispatchResultWithPostInfo) -> Option<Weight> {
|
||||
match result {
|
||||
Ok(post_info) => post_info.actual_weight,
|
||||
Err(err) => err.post_info.actual_weight,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user