referrerpolicy=no-referrer-when-downgrade

pallet_election_provider_e2e_test/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#![cfg(test)]
19
20// We do not declare all features used by `construct_runtime`
21#[allow(unexpected_cfgs)]
22mod mock;
23
24pub(crate) const LOG_TARGET: &str = "tests::e2e-epm";
25
26use frame_support::{assert_err, assert_ok};
27use mock::*;
28use pallet_timestamp::Now;
29use sp_core::Get;
30use sp_runtime::Perbill;
31
32use crate::mock::RuntimeOrigin;
33
34use pallet_election_provider_multi_phase::CurrentPhase;
35
36// syntactic sugar for logging.
37#[macro_export]
38macro_rules! log {
39	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
40		log::$level!(
41			target: crate::LOG_TARGET,
42			concat!("🛠️  ", $patter)  $(, $values)*
43		)
44	};
45}
46
47fn log_current_time() {
48	log!(
49		trace,
50		"block: {:?}, session: {:?}, era: {:?}, EPM phase: {:?} ts: {:?}",
51		System::block_number(),
52		Session::current_index(),
53		pallet_staking::CurrentEra::<Runtime>::get(),
54		CurrentPhase::<Runtime>::get(),
55		Now::<Runtime>::get()
56	);
57}
58
59#[test]
60fn block_progression_works() {
61	let (ext, pool_state, _) = ExtBuilder::default().build_offchainify();
62
63	execute_with(ext, || {
64		assert_eq!(active_era(), 0);
65		assert_eq!(Session::current_index(), 0);
66		assert!(CurrentPhase::<Runtime>::get().is_off());
67
68		assert!(start_next_active_era(pool_state.clone()).is_ok());
69		assert_eq!(active_era(), 1);
70		assert_eq!(Session::current_index(), <SessionsPerEra as Get<u32>>::get());
71
72		assert!(CurrentPhase::<Runtime>::get().is_off());
73
74		roll_to_epm_signed();
75		assert!(CurrentPhase::<Runtime>::get().is_signed());
76	});
77
78	let (ext, pool_state, _) = ExtBuilder::default().build_offchainify();
79
80	execute_with(ext, || {
81		assert_eq!(active_era(), 0);
82		assert_eq!(Session::current_index(), 0);
83		assert!(CurrentPhase::<Runtime>::get().is_off());
84
85		assert!(start_next_active_era_delayed_solution(pool_state).is_ok());
86		// if the solution is delayed, EPM will end up in emergency mode..
87		assert!(CurrentPhase::<Runtime>::get().is_emergency());
88		// .. era won't progress..
89		assert_eq!(active_era(), 0);
90		// .. but session does.
91		assert_eq!(Session::current_index(), 2);
92	})
93}
94
95#[test]
96fn offchainify_works() {
97	use pallet_election_provider_multi_phase::QueuedSolution;
98
99	let staking_builder = StakingExtBuilder::default();
100	let epm_builder = EpmExtBuilder::default();
101	let (ext, pool_state, _) = ExtBuilder::default()
102		.epm(epm_builder)
103		.staking(staking_builder)
104		.build_offchainify();
105
106	execute_with(ext, || {
107		// test ocw progression and solution queue if submission when unsigned phase submission is
108		// not delayed.
109		for _ in 0..100 {
110			roll_one(pool_state.clone(), false);
111			let current_phase = CurrentPhase::<Runtime>::get();
112
113			assert!(
114				match QueuedSolution::<Runtime>::get() {
115					Some(_) => current_phase.is_unsigned(),
116					None => !current_phase.is_unsigned(),
117				},
118				"solution must be queued *only* in unsigned phase"
119			);
120		}
121
122		// test ocw solution queue if submission in unsigned phase is delayed.
123		for _ in 0..100 {
124			roll_one(pool_state.clone(), true);
125			assert_eq!(
126				QueuedSolution::<Runtime>::get(),
127				None,
128				"solution must never be submitted and stored since it is delayed"
129			);
130		}
131	})
132}
133
134#[test]
135/// Inspired by the Kusama incident of 8th Dec 2022 and its resolution through the governance
136/// fallback.
137///
138/// Mass slash of validators shouldn't disable more than 1/3 of them (the byzantine threshold). Also
139/// no new era should be forced which could lead to EPM entering emergency mode.
140fn mass_slash_doesnt_enter_emergency_phase() {
141	let epm_builder = EpmExtBuilder::default().disable_emergency_throttling();
142	let staking_builder = StakingExtBuilder::default().validator_count(7);
143	let (mut ext, _, _) = ExtBuilder::default()
144		.epm(epm_builder)
145		.staking(staking_builder)
146		.build_offchainify();
147
148	ext.execute_with(|| {
149		assert_eq!(pallet_staking::ForceEra::<Runtime>::get(), pallet_staking::Forcing::NotForcing);
150
151		let active_set_size_before_slash = Session::validators().len();
152
153		// assuming half is above the disabling limit (default 1/3), otherwise test will break
154		let slashed = slash_half_the_active_set();
155
156		let active_set_size_after_slash = Session::validators().len();
157
158		// active set should stay the same before and after the slash
159		assert_eq!(active_set_size_before_slash, active_set_size_after_slash);
160
161		// Find the indices of the disabled validators
162		let active_set = Session::validators();
163		let potentially_disabled = slashed
164			.into_iter()
165			.map(|d| active_set.iter().position(|a| *a == d).unwrap() as u32)
166			.collect::<Vec<_>>();
167
168		// Ensure that every actually disabled validator is also in the potentially disabled set
169		// (not necessarily the other way around)
170		let disabled = Session::disabled_validators();
171		for d in disabled.iter() {
172			assert!(potentially_disabled.contains(d));
173		}
174
175		// Ensure no more than disabling limit of validators (default 1/3) is disabled
176		let disabling_limit = pallet_session::disabling::UpToLimitWithReEnablingDisablingStrategy::<
177			SLASHING_DISABLING_FACTOR,
178		>::disable_limit(active_set_size_before_slash);
179		assert!(disabled.len() == disabling_limit);
180
181		assert_eq!(pallet_staking::ForceEra::<Runtime>::get(), pallet_staking::Forcing::NotForcing);
182	});
183}
184
185#[test]
186/// Continuously slash 10% of the active validators per era.
187///
188/// Since the `OffendingValidatorsThreshold` is only checked per era staking does not force a new
189/// era even as the number of active validators is decreasing across eras. When processing a new
190/// slash, staking calculates the offending threshold based on the length of the current list of
191/// active validators. Thus, slashing a percentage of the current validators that is lower than
192/// `OffendingValidatorsThreshold` will never force a new era. However, as the slashes progress, if
193/// the subsequent elections do not meet the minimum election untrusted score, the election will
194/// fail and enter in emergency mode.
195fn continuous_slashes_below_offending_threshold() {
196	let staking_builder = StakingExtBuilder::default().validator_count(10);
197	let epm_builder = EpmExtBuilder::default().disable_emergency_throttling();
198
199	let (ext, pool_state, _) = ExtBuilder::default()
200		.epm(epm_builder)
201		.staking(staking_builder)
202		.build_offchainify();
203
204	execute_with(ext, || {
205		assert_eq!(Session::validators().len(), 10);
206		let mut active_validator_set = Session::validators();
207
208		roll_to_epm_signed();
209
210		// set a minimum election score.
211		assert!(set_minimum_election_score(500, 1000, 500).is_ok());
212
213		// slash 10% of the active validators and progress era until the minimum trusted score
214		// is reached.
215		while active_validator_set.len() > 0 {
216			let slashed = slash_percentage(Perbill::from_percent(10));
217			assert_eq!(slashed.len(), 1);
218
219			// break loop when era does not progress; EPM is in emergency phase as election
220			// failed due to election minimum score.
221			if start_next_active_era(pool_state.clone()).is_err() {
222				assert!(CurrentPhase::<Runtime>::get().is_emergency());
223				break;
224			}
225
226			active_validator_set = Session::validators();
227
228			log!(
229				trace,
230				"slashed 10% of active validators ({:?}). After slash: {:?}",
231				slashed,
232				active_validator_set
233			);
234		}
235	});
236}
237
238#[test]
239/// Active ledger balance may fall below ED if account chills before unbounding.
240///
241/// Unbonding call fails if the remaining ledger's stash balance falls below the existential
242/// deposit. However, if the stash is chilled before unbonding, the ledger's active balance may
243/// be below ED. In that case, only the stash (or root) can kill the ledger entry by calling
244/// `withdraw_unbonded` after the bonding period has passed.
245///
246/// Related to <https://github.com/paritytech/substrate/issues/14246>.
247fn ledger_consistency_active_balance_below_ed() {
248	use pallet_staking::{Error, Event};
249
250	let (ext, pool_state, _) =
251		ExtBuilder::default().staking(StakingExtBuilder::default()).build_offchainify();
252
253	execute_with(ext, || {
254		assert_eq!(Staking::ledger(11.into()).unwrap().active, 1000);
255
256		// unbonding total of active stake passes because chill occurs implicitly when unbonding
257		// full amount.
258		assert_ok!(Staking::unbond(RuntimeOrigin::signed(11), 1000));
259
260		// the active balance of the ledger entry is 0, while total balance is 1000 until
261		// `withdraw_unbonded` is called.
262		assert_eq!(Staking::ledger(11.into()).unwrap().active, 0);
263		assert_eq!(Staking::ledger(11.into()).unwrap().total, 1000);
264
265		// trying to withdraw the unbonded balance won't work yet because not enough bonding
266		// eras have passed.
267		assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(11), 0));
268		assert_eq!(Staking::ledger(11.into()).unwrap().total, 1000);
269
270		// tries to reap stash after chilling, which fails since the stash total balance is
271		// above ED.
272		assert_err!(
273			Staking::reap_stash(RuntimeOrigin::signed(11), 21, 0),
274			Error::<Runtime>::FundedTarget,
275		);
276
277		// check the events so far: 1x Chilled and 1x Unbounded
278		assert_eq!(
279			staking_events(),
280			[Event::Chilled { stash: 11 }, Event::Unbonded { stash: 11, amount: 1000 }]
281		);
282
283		// after advancing `BondingDuration` eras, the `withdraw_unbonded` will unlock the
284		// chunks and the ledger entry will be cleared, since the ledger active balance is 0.
285		advance_eras(
286			<Runtime as pallet_staking::Config>::BondingDuration::get() as usize,
287			pool_state,
288		);
289		assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(11), 0));
290		assert!(Staking::ledger(11.into()).is_err());
291	});
292}
293
294#[test]
295/// Automatic withdrawal of unlocking funds in staking propagates to the nomination pools and its
296/// state correctly.
297///
298/// The staking pallet may withdraw unlocking funds from a pool's bonded account without a pool
299/// member or operator calling explicitly `Call::withdraw*`. This test verifies that the member's
300/// are eventually paid and the `TotalValueLocked` is kept in sync in those cases.
301fn automatic_unbonding_pools() {
302	use pallet_nomination_pools::TotalValueLocked;
303
304	// closure to fetch the staking unlocking chunks of an account.
305	let unlocking_chunks_of = |account: AccountId| -> usize {
306		Staking::ledger(sp_staking::StakingAccount::Controller(account))
307			.unwrap()
308			.unlocking
309			.len()
310	};
311
312	let (ext, pool_state, _) = ExtBuilder::default()
313		.pools(PoolsExtBuilder::default().max_unbonding(1))
314		.staking(StakingExtBuilder::default().max_unlocking(1).bonding_duration(2))
315		.build_offchainify();
316
317	execute_with(ext, || {
318		assert_eq!(<Runtime as pallet_staking::Config>::MaxUnlockingChunks::get(), 1);
319		assert_eq!(<Runtime as pallet_staking::Config>::BondingDuration::get(), 2);
320		assert_eq!(<Runtime as pallet_nomination_pools::Config>::MaxUnbonding::get(), 1);
321
322		// init state of pool members.
323		let init_free_balance_2 = Balances::free_balance(2);
324		let init_free_balance_3 = Balances::free_balance(3);
325
326		let pool_bonded_account = Pools::generate_bonded_account(1);
327
328		// creates a pool with 5 bonded, owned by 1.
329		assert_ok!(Pools::create(RuntimeOrigin::signed(1), 5, 1, 1, 1));
330		assert_eq!(staked_amount_for(pool_bonded_account), 5);
331
332		let init_tvl = TotalValueLocked::<Runtime>::get();
333
334		// 2 joins the pool.
335		assert_ok!(Pools::join(RuntimeOrigin::signed(2), 10, 1));
336		assert_eq!(staked_amount_for(pool_bonded_account), 15);
337
338		// 3 joins the pool.
339		assert_ok!(Pools::join(RuntimeOrigin::signed(3), 10, 1));
340		assert_eq!(staked_amount_for(pool_bonded_account), 25);
341
342		assert_eq!(TotalValueLocked::<Runtime>::get(), 25);
343
344		// currently unlocking 0 chunks in the bonded pools ledger.
345		assert_eq!(unlocking_chunks_of(pool_bonded_account), 0);
346
347		// unbond 2 from pool.
348		assert_ok!(Pools::unbond(RuntimeOrigin::signed(2), 2, 10));
349
350		// amount is still locked in the pool, needs to wait for unbonding period.
351		assert_eq!(staked_amount_for(pool_bonded_account), 25);
352
353		// max chunks in the ledger are now filled up (`MaxUnlockingChunks == 1`).
354		assert_eq!(unlocking_chunks_of(pool_bonded_account), 1);
355
356		// tries to unbond 3 from pool. it will fail since there are no unlocking chunks left
357		// available and the current in the queue haven't been there for more than bonding
358		// duration.
359		assert_err!(
360			Pools::unbond(RuntimeOrigin::signed(3), 3, 10),
361			pallet_staking::Error::<Runtime>::NoMoreChunks
362		);
363
364		assert_eq!(current_era(), 0);
365
366		// progress over bonding duration.
367		for _ in 0..=<Runtime as pallet_staking::Config>::BondingDuration::get() {
368			start_next_active_era(pool_state.clone()).unwrap();
369		}
370		assert_eq!(current_era(), 3);
371		System::reset_events();
372
373		let staked_before_withdraw_pool = staked_amount_for(pool_bonded_account);
374		assert_eq!(delegated_balance_for(pool_bonded_account), 5 + 10 + 10);
375
376		// now unbonding 3 will work, although the pool's ledger still has the unlocking chunks
377		// filled up.
378		assert_ok!(Pools::unbond(RuntimeOrigin::signed(3), 3, 10));
379		assert_eq!(unlocking_chunks_of(pool_bonded_account), 1);
380
381		assert_eq!(
382			staking_events(),
383			[
384				// auto-withdraw happened as expected to release 2's unbonding funds, but the funds
385				// were not transferred to 2 and stay in the pool's transferrable balance instead.
386				pallet_staking::Event::Withdrawn { stash: pool_bonded_account, amount: 10 },
387				pallet_staking::Event::Unbonded { stash: pool_bonded_account, amount: 10 }
388			]
389		);
390
391		// balance of the pool remains the same, it hasn't withdraw explicitly from the pool yet.
392		assert_eq!(delegated_balance_for(pool_bonded_account), 25);
393		// but the locked amount in the pool's account decreases due to the auto-withdraw:
394		assert_eq!(staked_before_withdraw_pool - 10, staked_amount_for(pool_bonded_account));
395
396		// TVL correctly updated.
397		assert_eq!(TotalValueLocked::<Runtime>::get(), 25 - 10);
398
399		// however, note that the withdrawing from the pool still works for 2, the funds are taken
400		// from the pool's non staked balance.
401		assert_eq!(delegated_balance_for(pool_bonded_account), 25);
402		assert_eq!(staked_amount_for(pool_bonded_account), 15);
403		assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(2), 2, 10));
404		assert_eq!(delegated_balance_for(pool_bonded_account), 15);
405
406		assert_eq!(Balances::free_balance(2), 20);
407		assert_eq!(TotalValueLocked::<Runtime>::get(), 15);
408
409		// 3 cannot withdraw yet.
410		assert_err!(
411			Pools::withdraw_unbonded(RuntimeOrigin::signed(3), 3, 10),
412			pallet_nomination_pools::Error::<Runtime>::CannotWithdrawAny
413		);
414
415		// progress over bonding duration.
416		for _ in 0..=<Runtime as pallet_staking::Config>::BondingDuration::get() {
417			start_next_active_era(pool_state.clone()).unwrap();
418		}
419		assert_eq!(current_era(), 6);
420		System::reset_events();
421
422		assert_ok!(Pools::withdraw_unbonded(RuntimeOrigin::signed(3), 3, 10));
423
424		// final conditions are the expected.
425		assert_eq!(delegated_balance_for(pool_bonded_account), 5); // 5 init bonded
426		assert_eq!(Balances::free_balance(2), init_free_balance_2);
427		assert_eq!(Balances::free_balance(3), init_free_balance_3);
428
429		assert_eq!(TotalValueLocked::<Runtime>::get(), init_tvl);
430	});
431}