Skip to content

Commit 8935549

Browse files
Allow "anonymous" proxied accounts (#6236)
* Anonymous proxiers * More testing * More testing * Build fix * Build fix * Benchmarks. * fix benchmarking * add weights * fix line width Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
1 parent 83a01e9 commit 8935549

File tree

4 files changed

+202
-27
lines changed

4 files changed

+202
-27
lines changed

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ codec = { package = "parity-scale-codec", version = "1.3.0", default-features =
1717
frame-support = { version = "2.0.0-rc2", default-features = false, path = "../support" }
1818
frame-system = { version = "2.0.0-rc2", default-features = false, path = "../system" }
1919
sp-core = { version = "2.0.0-rc2", default-features = false, path = "../../primitives/core" }
20+
sp-io = { version = "2.0.0-rc2", default-features = false, path = "../../primitives/io" }
2021
sp-runtime = { version = "2.0.0-rc2", default-features = false, path = "../../primitives/runtime" }
2122
sp-std = { version = "2.0.0-rc2", default-features = false, path = "../../primitives/std" }
2223

@@ -25,7 +26,6 @@ frame-benchmarking = { version = "2.0.0-rc2", default-features = false, path = "
2526
[dev-dependencies]
2627
sp-core = { version = "2.0.0-rc2", path = "../../primitives/core" }
2728
pallet-balances = { version = "2.0.0-rc2", path = "../balances" }
28-
sp-io = { version = "2.0.0-rc2", path = "../../primitives/io" }
2929

3030
[features]
3131
default = ["std"]
@@ -35,7 +35,8 @@ std = [
3535
"sp-runtime/std",
3636
"frame-support/std",
3737
"frame-system/std",
38-
"sp-std/std"
38+
"sp-std/std",
39+
"sp-io/std"
3940
]
4041
runtime-benchmarks = [
4142
"frame-benchmarking",

src/benchmarking.rs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ use crate::Module as Proxy;
2727

2828
const SEED: u32 = 0;
2929

30-
fn add_proxies<T: Trait>(n: u32) -> Result<(), &'static str> {
31-
let caller: T::AccountId = account("caller", 0, SEED);
30+
fn add_proxies<T: Trait>(n: u32, maybe_who: Option<T::AccountId>) -> Result<(), &'static str> {
31+
let caller = maybe_who.unwrap_or_else(|| account("caller", 0, SEED));
3232
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
3333
for i in 0..n {
3434
Proxy::<T>::add_proxy(
@@ -42,7 +42,7 @@ fn add_proxies<T: Trait>(n: u32) -> Result<(), &'static str> {
4242

4343
benchmarks! {
4444
_ {
45-
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p)?;
45+
let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::<T>(p, None)?;
4646
}
4747

4848
proxy {
@@ -68,6 +68,24 @@ benchmarks! {
6868
let p in ...;
6969
let caller: T::AccountId = account("caller", 0, SEED);
7070
}: _(RawOrigin::Signed(caller))
71+
72+
anonymous {
73+
let p in ...;
74+
}: _(RawOrigin::Signed(account("caller", 0, SEED)), T::ProxyType::default(), 0)
75+
76+
kill_anonymous {
77+
let p in 0 .. (T::MaxProxies::get() - 2).into();
78+
79+
let caller: T::AccountId = account("caller", 0, SEED);
80+
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
81+
Module::<T>::anonymous(RawOrigin::Signed(account("caller", 0, SEED)).into(), T::ProxyType::default(), 0)?;
82+
let height = system::Module::<T>::block_number();
83+
let ext_index = system::Module::<T>::extrinsic_index().unwrap_or(0);
84+
let anon = Module::<T>::anonymous_account(&caller, &T::ProxyType::default(), 0, None);
85+
86+
add_proxies::<T>(p, Some(anon.clone()))?;
87+
88+
}: _(RawOrigin::Signed(anon), caller, T::ProxyType::default(), 0, height, ext_index)
7189
}
7290

7391
#[cfg(test)]
@@ -83,6 +101,8 @@ mod tests {
83101
assert_ok!(test_benchmark_add_proxy::<Test>());
84102
assert_ok!(test_benchmark_remove_proxy::<Test>());
85103
assert_ok!(test_benchmark_remove_proxies::<Test>());
104+
assert_ok!(test_benchmark_anonymous::<Test>());
105+
assert_ok!(test_benchmark_kill_anonymous::<Test>());
86106
});
87107
}
88108
}

src/lib.rs

Lines changed: 121 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,17 @@
3535
#![cfg_attr(not(feature = "std"), no_std)]
3636

3737
use sp_std::prelude::*;
38-
use frame_support::{decl_module, decl_event, decl_error, decl_storage, Parameter, ensure};
38+
use codec::{Encode, Decode};
39+
use sp_io::hashing::blake2_256;
40+
use sp_runtime::{DispatchResult, traits::{Dispatchable, Zero}};
41+
use sp_runtime::traits::Member;
3942
use frame_support::{
43+
decl_module, decl_event, decl_error, decl_storage, Parameter, ensure,
4044
traits::{Get, ReservableCurrency, Currency, Filter, InstanceFilter},
4145
weights::{GetDispatchInfo, constants::{WEIGHT_PER_MICROS, WEIGHT_PER_NANOS}},
4246
dispatch::{PostDispatchInfo, IsSubType},
4347
};
4448
use frame_system::{self as system, ensure_signed};
45-
use sp_runtime::{DispatchResult, traits::{Dispatchable, Zero}};
46-
use sp_runtime::traits::Member;
4749

4850
mod tests;
4951
mod benchmarking;
@@ -53,7 +55,7 @@ type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as frame_system::Trai
5355
/// Configuration trait.
5456
pub trait Trait: frame_system::Trait {
5557
/// The overarching event type.
56-
type Event: From<Event> + Into<<Self as frame_system::Trait>::Event>;
58+
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
5759

5860
/// The overarching call type.
5961
type Call: Parameter + Dispatchable<Origin=Self::Origin, PostInfo=PostDispatchInfo>
@@ -115,9 +117,15 @@ decl_error! {
115117

116118
decl_event! {
117119
/// Events type.
118-
pub enum Event {
120+
pub enum Event<T> where
121+
AccountId = <T as frame_system::Trait>::AccountId,
122+
ProxyType = <T as Trait>::ProxyType
123+
{
119124
/// A proxy was executed correctly, with the given result.
120125
ProxyExecuted(DispatchResult),
126+
/// Anonymous account (first parameter) has been created by new proxy (second) with given
127+
/// disambiguation index and proxy type.
128+
AnonymousCreated(AccountId, AccountId, ProxyType, u16),
121129
}
122130
}
123131

@@ -164,12 +172,12 @@ decl_module! {
164172
.ok_or(Error::<T>::NotProxy)?;
165173
match call.is_sub_type() {
166174
Some(Call::add_proxy(_, ref pt)) | Some(Call::remove_proxy(_, ref pt)) =>
167-
ensure!(&proxy_type == pt, Error::<T>::NoPermission),
175+
ensure!(pt.is_no_more_permissive(&proxy_type), Error::<T>::NoPermission),
168176
_ => (),
169177
}
170178
ensure!(proxy_type.filter(&call), Error::<T>::Unproxyable);
171179
let e = call.dispatch(frame_system::RawOrigin::Signed(real).into());
172-
Self::deposit_event(Event::ProxyExecuted(e.map(|_| ()).map_err(|e| e.error)));
180+
Self::deposit_event(RawEvent::ProxyExecuted(e.map(|_| ()).map_err(|e| e.error)));
173181
}
174182

175183
/// Register a proxy account for the sender that is able to make calls on its behalf.
@@ -186,8 +194,8 @@ decl_module! {
186194
/// - DB weight: 1 storage read and write.
187195
/// # </weight>
188196
#[weight = T::DbWeight::get().reads_writes(1, 1)
189-
.saturating_add(18 * WEIGHT_PER_MICROS)
190-
.saturating_add((200 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
197+
.saturating_add(18 * WEIGHT_PER_MICROS)
198+
.saturating_add((200 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
191199
]
192200
fn add_proxy(origin, proxy: T::AccountId, proxy_type: T::ProxyType) -> DispatchResult {
193201
let who = ensure_signed(origin)?;
@@ -222,8 +230,8 @@ decl_module! {
222230
/// - DB weight: 1 storage read and write.
223231
/// # </weight>
224232
#[weight = T::DbWeight::get().reads_writes(1, 1)
225-
.saturating_add(14 * WEIGHT_PER_MICROS)
226-
.saturating_add((160 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
233+
.saturating_add(14 * WEIGHT_PER_MICROS)
234+
.saturating_add((160 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
227235
]
228236
fn remove_proxy(origin, proxy: T::AccountId, proxy_type: T::ProxyType) -> DispatchResult {
229237
let who = ensure_signed(origin)?;
@@ -253,19 +261,119 @@ decl_module! {
253261
///
254262
/// The dispatch origin for this call must be _Signed_.
255263
///
264+
/// WARNING: This may be called on accounts created by `anonymous`, however if done, then
265+
/// the unreserved fees will be inaccessible. **All access to this account will be lost.**
266+
///
256267
/// # <weight>
257268
/// P is the number of proxies the user has
258269
/// - Base weight: 13.73 + .129 * P µs
259270
/// - DB weight: 1 storage read and write.
260271
/// # </weight>
261272
#[weight = T::DbWeight::get().reads_writes(1, 1)
262-
.saturating_add(14 * WEIGHT_PER_MICROS)
263-
.saturating_add((130 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
273+
.saturating_add(14 * WEIGHT_PER_MICROS)
274+
.saturating_add((130 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
264275
]
265276
fn remove_proxies(origin) {
266277
let who = ensure_signed(origin)?;
267278
let (_, old_deposit) = Proxies::<T>::take(&who);
268279
T::Currency::unreserve(&who, old_deposit);
269280
}
281+
282+
/// Spawn a fresh new account that is guaranteed to be otherwise inaccessible, and
283+
/// initialize it with a proxy of `proxy_type` for `origin` sender.
284+
///
285+
/// Requires a `Signed` origin.
286+
///
287+
/// - `proxy_type`: The type of the proxy that the sender will be registered as over the
288+
/// new account. This will almost always be the most permissive `ProxyType` possible to
289+
/// allow for maximum flexibility.
290+
/// - `index`: A disambiguation index, in case this is called multiple times in the same
291+
/// transaction (e.g. with `utility::batch`). Unless you're using `batch` you probably just
292+
/// want to use `0`.
293+
///
294+
/// Fails with `Duplicate` if this has already been called in this transaction, from the
295+
/// same sender, with the same parameters.
296+
///
297+
/// Fails if there are insufficient funds to pay for deposit.
298+
///
299+
/// # <weight>
300+
/// P is the number of proxies the user has
301+
/// - Base weight: 36.48 + .039 * P µs
302+
/// - DB weight: 1 storage read and write.
303+
/// # </weight>
304+
#[weight = T::DbWeight::get().reads_writes(1, 1)
305+
.saturating_add(36 * WEIGHT_PER_MICROS)
306+
.saturating_add((40 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
307+
]
308+
fn anonymous(origin, proxy_type: T::ProxyType, index: u16) {
309+
let who = ensure_signed(origin)?;
310+
311+
let anonymous = Self::anonymous_account(&who, &proxy_type, index, None);
312+
ensure!(!Proxies::<T>::contains_key(&anonymous), Error::<T>::Duplicate);
313+
let deposit = T::ProxyDepositBase::get() + T::ProxyDepositFactor::get();
314+
T::Currency::reserve(&who, deposit)?;
315+
Proxies::<T>::insert(&anonymous, (vec![(who.clone(), proxy_type.clone())], deposit));
316+
Self::deposit_event(RawEvent::AnonymousCreated(anonymous, who, proxy_type, index));
317+
}
318+
319+
/// Removes a previously spawned anonymous proxy.
320+
///
321+
/// WARNING: **All access to this account will be lost.** Any funds held in it will be
322+
/// inaccessible.
323+
///
324+
/// Requires a `Signed` origin, and the sender account must have been created by a call to
325+
/// `anonymous` with corresponding parameters.
326+
///
327+
/// - `spawner`: The account that originally called `anonymous` to create this account.
328+
/// - `index`: The disambiguation index originally passed to `anonymous`. Probably `0`.
329+
/// - `proxy_type`: The proxy type originally passed to `anonymous`.
330+
/// - `height`: The height of the chain when the call to `anonymous` was processed.
331+
/// - `ext_index`: The extrinsic index in which the call to `anonymous` was processed.
332+
///
333+
/// Fails with `NoPermission` in case the caller is not a previously created anonymous
334+
/// account whose `anonymous` call has corresponding parameters.
335+
///
336+
/// # <weight>
337+
/// P is the number of proxies the user has
338+
/// - Base weight: 15.65 + .137 * P µs
339+
/// - DB weight: 1 storage read and write.
340+
/// # </weight>
341+
#[weight = T::DbWeight::get().reads_writes(1, 1)
342+
.saturating_add(15 * WEIGHT_PER_MICROS)
343+
.saturating_add((140 * WEIGHT_PER_NANOS).saturating_mul(T::MaxProxies::get().into()))
344+
]
345+
fn kill_anonymous(origin,
346+
spawner: T::AccountId,
347+
proxy_type: T::ProxyType,
348+
index: u16,
349+
#[compact] height: T::BlockNumber,
350+
#[compact] ext_index: u32,
351+
) {
352+
let who = ensure_signed(origin)?;
353+
354+
let when = (height, ext_index);
355+
let proxy = Self::anonymous_account(&spawner, &proxy_type, index, Some(when));
356+
ensure!(proxy == who, Error::<T>::NoPermission);
357+
358+
let (_, deposit) = Proxies::<T>::take(&who);
359+
T::Currency::unreserve(&spawner, deposit);
360+
}
361+
}
362+
}
363+
364+
impl<T: Trait> Module<T> {
365+
pub fn anonymous_account(
366+
who: &T::AccountId,
367+
proxy_type: &T::ProxyType,
368+
index: u16,
369+
maybe_when: Option<(T::BlockNumber, u32)>,
370+
) -> T::AccountId {
371+
let (height, ext_index) = maybe_when.unwrap_or_else(|| (
372+
system::Module::<T>::block_number(),
373+
system::Module::<T>::extrinsic_index().unwrap_or_default()
374+
));
375+
let entropy = (b"modlpy/proxy____", who, height, ext_index, proxy_type, index)
376+
.using_encoded(blake2_256);
377+
T::AccountId::decode(&mut &entropy[..]).unwrap_or_default()
270378
}
271379
}

src/tests.rs

Lines changed: 55 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use super::*;
2323

2424
use frame_support::{
2525
assert_ok, assert_noop, impl_outer_origin, parameter_types, impl_outer_dispatch,
26-
weights::Weight, impl_outer_event, RuntimeDebug
26+
weights::Weight, impl_outer_event, RuntimeDebug, dispatch::DispatchError
2727
};
2828
use codec::{Encode, Decode};
2929
use sp_core::H256;
@@ -37,7 +37,7 @@ impl_outer_event! {
3737
pub enum TestEvent for Test {
3838
system<T>,
3939
pallet_balances<T>,
40-
proxy,
40+
proxy<T>,
4141
}
4242
}
4343
impl_outer_dispatch! {
@@ -120,8 +120,10 @@ pub struct TestIsCallable;
120120
impl Filter<Call> for TestIsCallable {
121121
fn filter(c: &Call) -> bool {
122122
match *c {
123-
Call::Balances(_) => true,
124-
_ => false,
123+
// Remark is used as a no-op call in the benchmarking
124+
Call::System(SystemCall::remark(_)) => true,
125+
Call::System(_) => false,
126+
_ => true,
125127
}
126128
}
127129
}
@@ -143,6 +145,7 @@ type Proxy = Module<Test>;
143145
use frame_system::Call as SystemCall;
144146
use pallet_balances::Call as BalancesCall;
145147
use pallet_balances::Error as BalancesError;
148+
use super::Call as ProxyCall;
146149

147150
pub fn new_test_ext() -> sp_io::TestExternalities {
148151
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
@@ -155,7 +158,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
155158
}
156159

157160
fn last_event() -> TestEvent {
158-
system::Module::<Test>::events().pop().map(|e| e.event).expect("Event expected")
161+
system::Module::<Test>::events().pop().expect("Event expected").event
159162
}
160163

161164
fn expect_event<E: Into<TestEvent>>(e: E) {
@@ -203,18 +206,61 @@ fn proxying_works() {
203206

204207
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 1)));
205208
assert_noop!(Proxy::proxy(Origin::signed(4), 1, None, call.clone()), Error::<Test>::NotProxy);
206-
assert_noop!(Proxy::proxy(Origin::signed(2), 1, Some(ProxyType::Any), call.clone()), Error::<Test>::NotProxy);
209+
assert_noop!(
210+
Proxy::proxy(Origin::signed(2), 1, Some(ProxyType::Any), call.clone()),
211+
Error::<Test>::NotProxy
212+
);
207213
assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone()));
208-
expect_event(Event::ProxyExecuted(Ok(())));
214+
expect_event(RawEvent::ProxyExecuted(Ok(())));
209215
assert_eq!(Balances::free_balance(6), 1);
210216

211-
let call = Box::new(Call::System(SystemCall::remark(vec![])));
217+
let call = Box::new(Call::System(SystemCall::set_code(vec![])));
212218
assert_noop!(Proxy::proxy(Origin::signed(3), 1, None, call.clone()), Error::<Test>::Uncallable);
213219

214220
let call = Box::new(Call::Balances(BalancesCall::transfer_keep_alive(6, 1)));
215221
assert_noop!(Proxy::proxy(Origin::signed(2), 1, None, call.clone()), Error::<Test>::Unproxyable);
216222
assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone()));
217-
expect_event(Event::ProxyExecuted(Ok(())));
223+
expect_event(RawEvent::ProxyExecuted(Ok(())));
218224
assert_eq!(Balances::free_balance(6), 2);
219225
});
220226
}
227+
228+
#[test]
229+
fn anonymous_works() {
230+
new_test_ext().execute_with(|| {
231+
assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0));
232+
let anon = Proxy::anonymous_account(&1, &ProxyType::Any, 0, None);
233+
expect_event(RawEvent::AnonymousCreated(anon.clone(), 1, ProxyType::Any, 0));
234+
235+
// other calls to anonymous allowed as long as they're not exactly the same.
236+
assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::JustTransfer, 0));
237+
assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 1));
238+
let anon2 = Proxy::anonymous_account(&2, &ProxyType::Any, 0, None);
239+
assert_ok!(Proxy::anonymous(Origin::signed(2), ProxyType::Any, 0));
240+
assert_noop!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0), Error::<Test>::Duplicate);
241+
System::set_extrinsic_index(1);
242+
assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0));
243+
System::set_extrinsic_index(0);
244+
System::set_block_number(2);
245+
assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0));
246+
247+
let call = Box::new(Call::Balances(BalancesCall::transfer(6, 1)));
248+
assert_ok!(Balances::transfer(Origin::signed(3), anon, 5));
249+
assert_ok!(Proxy::proxy(Origin::signed(1), anon, None, call));
250+
expect_event(RawEvent::ProxyExecuted(Ok(())));
251+
assert_eq!(Balances::free_balance(6), 1);
252+
253+
let call = Box::new(Call::Proxy(ProxyCall::kill_anonymous(1, ProxyType::Any, 0, 1, 0)));
254+
assert_ok!(Proxy::proxy(Origin::signed(2), anon2, None, call.clone()));
255+
let de = DispatchError::from(Error::<Test>::NoPermission).stripped();
256+
expect_event(RawEvent::ProxyExecuted(Err(de)));
257+
assert_noop!(
258+
Proxy::kill_anonymous(Origin::signed(1), 1, ProxyType::Any, 0, 1, 0),
259+
Error::<Test>::NoPermission
260+
);
261+
assert_eq!(Balances::free_balance(1), 0);
262+
assert_ok!(Proxy::proxy(Origin::signed(1), anon, None, call.clone()));
263+
assert_eq!(Balances::free_balance(1), 2);
264+
assert_noop!(Proxy::proxy(Origin::signed(1), anon, None, call.clone()), Error::<Test>::NotProxy);
265+
});
266+
}

0 commit comments

Comments
 (0)