referrerpolicy=no-referrer-when-downgrade

pallet_staking_async/
ledger.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//! A Ledger implementation for stakers.
19//!
20//! A [`StakingLedger`] encapsulates all the state and logic related to the stake of bonded
21//! stakers, namely, it handles the following storage items:
22//! * [`Bonded`]: mutates and reads the state of the controller <> stash bond map (to be deprecated
23//! soon);
24//! * [`Ledger`]: mutates and reads the state of all the stakers. The [`Ledger`] storage item stores
25//!   instances of [`StakingLedger`] keyed by the staker's controller account and should be mutated
26//!   and read through the [`StakingLedger`] API;
27//! * [`Payee`]: mutates and reads the reward destination preferences for a bonded stash.
28//! * Staking locks: mutates the locks for staking.
29//!
30//! NOTE: All the storage operations related to the staking ledger (both reads and writes) *MUST* be
31//! performed through the methods exposed by the [`StakingLedger`] implementation in order to ensure
32//! state consistency.
33
34use crate::{
35	asset, log, BalanceOf, Bonded, Config, DecodeWithMemTracking, Error, Ledger, Pallet, Payee,
36	RewardDestination, Vec, VirtualStakers,
37};
38use alloc::{collections::BTreeMap, fmt::Debug};
39use codec::{Decode, Encode, HasCompact, MaxEncodedLen};
40use frame_support::{
41	defensive, ensure,
42	traits::{Defensive, DefensiveSaturating, Get},
43	BoundedVec, CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound,
44};
45use scale_info::TypeInfo;
46use sp_runtime::{traits::Zero, DispatchResult, Perquintill, Rounding, Saturating};
47use sp_staking::{EraIndex, OnStakingUpdate, StakingAccount, StakingInterface};
48
49/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
50#[derive(
51	PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo, MaxEncodedLen,
52)]
53pub struct UnlockChunk<Balance: HasCompact + MaxEncodedLen> {
54	/// Amount of funds to be unlocked.
55	#[codec(compact)]
56	pub value: Balance,
57	/// Era number at which point it'll be unlocked.
58	#[codec(compact)]
59	pub era: EraIndex,
60}
61
62/// The ledger of a (bonded) stash.
63///
64/// Note: All the reads and mutations to the [`Ledger`], [`Bonded`] and [`Payee`] storage items
65/// *MUST* be performed through the methods exposed by this struct, to ensure the consistency of
66/// ledger's data and corresponding staking lock
67///
68/// TODO: move struct definition and full implementation into `/src/ledger.rs`. Currently
69/// leaving here to enforce a clean PR diff, given how critical this logic is. Tracking issue
70/// <https://github.com/paritytech/substrate/issues/14749>.
71#[derive(
72	PartialEqNoBound,
73	EqNoBound,
74	CloneNoBound,
75	Encode,
76	Decode,
77	DebugNoBound,
78	TypeInfo,
79	MaxEncodedLen,
80	DecodeWithMemTracking,
81)]
82#[scale_info(skip_type_params(T))]
83pub struct StakingLedger<T: Config> {
84	/// The stash account whose balance is actually locked and at stake.
85	pub stash: T::AccountId,
86
87	/// The total amount of the stash's balance that we are currently accounting for.
88	/// It's just `active` plus all the `unlocking` balances.
89	#[codec(compact)]
90	pub total: BalanceOf<T>,
91
92	/// The total amount of the stash's balance that will be at stake in any forthcoming
93	/// rounds.
94	#[codec(compact)]
95	pub active: BalanceOf<T>,
96
97	/// Any balance that is becoming free, which may eventually be transferred out of the stash
98	/// (assuming it doesn't get slashed first). It is assumed that this will be treated as a first
99	/// in, first out queue where the new (higher value) eras get pushed on the back.
100	pub unlocking: BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
101
102	/// The controller associated with this ledger's stash.
103	///
104	/// This is not stored on-chain, and is only bundled when the ledger is read from storage.
105	/// Use [`Self::controller()`] function to get the controller associated with the ledger.
106	#[codec(skip)]
107	pub controller: Option<T::AccountId>,
108}
109
110impl<T: Config> StakingLedger<T> {
111	#[cfg(any(feature = "runtime-benchmarks", test))]
112	pub fn default_from(stash: T::AccountId) -> Self {
113		Self {
114			stash: stash.clone(),
115			total: Zero::zero(),
116			active: Zero::zero(),
117			unlocking: Default::default(),
118			controller: Some(stash),
119		}
120	}
121
122	/// Returns a new instance of a staking ledger.
123	///
124	/// The [`Ledger`] storage is not mutated. In order to store, `StakingLedger::update` must be
125	/// called on the returned staking ledger.
126	///
127	/// Note: as the controller accounts are being deprecated, the stash account is the same as the
128	/// controller account.
129	pub fn new(stash: T::AccountId, stake: BalanceOf<T>) -> Self {
130		Self {
131			stash: stash.clone(),
132			active: stake,
133			total: stake,
134			unlocking: Default::default(),
135			// controllers are deprecated and mapped 1-1 to stashes.
136			controller: Some(stash),
137		}
138	}
139
140	/// Returns the paired account, if any.
141	///
142	/// A "pair" refers to the tuple (stash, controller). If the input is a
143	/// [`StakingAccount::Stash`] variant, its pair account will be of type
144	/// [`StakingAccount::Controller`] and vice-versa.
145	///
146	/// This method is meant to abstract from the runtime development the difference between stash
147	/// and controller. This will be deprecated once the controller is fully deprecated as well.
148	pub(crate) fn paired_account(account: StakingAccount<T::AccountId>) -> Option<T::AccountId> {
149		match account {
150			StakingAccount::Stash(stash) => <Bonded<T>>::get(stash),
151			StakingAccount::Controller(controller) =>
152				<Ledger<T>>::get(&controller).map(|ledger| ledger.stash),
153		}
154	}
155
156	/// Returns whether a given account is bonded.
157	pub(crate) fn is_bonded(account: StakingAccount<T::AccountId>) -> bool {
158		match account {
159			StakingAccount::Stash(stash) => <Bonded<T>>::contains_key(stash),
160			StakingAccount::Controller(controller) => <Ledger<T>>::contains_key(controller),
161		}
162	}
163
164	/// Returns a staking ledger, if it is bonded and it exists in storage.
165	///
166	/// This getter can be called with either a controller or stash account, provided that the
167	/// account is properly wrapped in the respective [`StakingAccount`] variant. This is meant to
168	/// abstract the concept of controller/stash accounts from the caller.
169	///
170	/// Returns [`Error::BadState`] when a bond is in "bad state". A bond is in a bad state when a
171	/// stash has a controller which is bonding a ledger associated with another stash.
172	pub(crate) fn get(account: StakingAccount<T::AccountId>) -> Result<StakingLedger<T>, Error<T>> {
173		let (stash, controller) = match account {
174			StakingAccount::Stash(stash) =>
175				(stash.clone(), <Bonded<T>>::get(&stash).ok_or(Error::<T>::NotStash)?),
176			StakingAccount::Controller(controller) => (
177				Ledger::<T>::get(&controller)
178					.map(|l| l.stash)
179					.ok_or(Error::<T>::NotController)?,
180				controller,
181			),
182		};
183
184		let ledger = <Ledger<T>>::get(&controller)
185			.map(|mut ledger| {
186				ledger.controller = Some(controller.clone());
187				ledger
188			})
189			.ok_or(Error::<T>::NotController)?;
190
191		// if ledger bond is in a bad state, return error to prevent applying operations that may
192		// further spoil the ledger's state. A bond is in bad state when the bonded controller is
193		// associated with a different ledger (i.e. a ledger with a different stash).
194		//
195		// See <https://github.com/paritytech/polkadot-sdk/issues/3245> for more details.
196		ensure!(
197			Bonded::<T>::get(&stash) == Some(controller) && ledger.stash == stash,
198			Error::<T>::BadState
199		);
200
201		Ok(ledger)
202	}
203
204	/// Returns the reward destination of a staking ledger, stored in [`Payee`].
205	///
206	/// Note: if the stash is not bonded and/or does not have an entry in [`Payee`], it returns the
207	/// default reward destination.
208	pub(crate) fn reward_destination(
209		account: StakingAccount<T::AccountId>,
210	) -> Option<RewardDestination<T::AccountId>> {
211		let stash = match account {
212			StakingAccount::Stash(stash) => Some(stash),
213			StakingAccount::Controller(controller) =>
214				Self::paired_account(StakingAccount::Controller(controller)),
215		};
216
217		if let Some(stash) = stash {
218			<Payee<T>>::get(stash)
219		} else {
220			defensive!("fetched reward destination from unbonded stash {}", stash);
221			None
222		}
223	}
224
225	/// Returns the controller account of a staking ledger.
226	///
227	/// Note: it will fallback into querying the [`Bonded`] storage with the ledger stash if the
228	/// controller is not set in `self`, which most likely means that self was fetched directly from
229	/// [`Ledger`] instead of through the methods exposed in [`StakingLedger`]. If the ledger does
230	/// not exist in storage, it returns `None`.
231	pub fn controller(&self) -> Option<T::AccountId> {
232		self.controller.clone().or_else(|| {
233			defensive!("fetched a controller on a ledger instance without it.");
234			Self::paired_account(StakingAccount::Stash(self.stash.clone()))
235		})
236	}
237
238	/// Inserts/updates a staking ledger account.
239	///
240	/// Bonds the ledger if it is not bonded yet, signalling that this is a new ledger. The staking
241	/// lock/hold of the stash account are updated accordingly.
242	///
243	/// Note: To ensure lock consistency, all the [`Ledger`] storage updates should be made through
244	/// this helper function.
245	pub(crate) fn update(self) -> Result<(), Error<T>> {
246		if !<Bonded<T>>::contains_key(&self.stash) {
247			return Err(Error::<T>::NotStash)
248		}
249
250		// We skip locking virtual stakers.
251		if !Pallet::<T>::is_virtual_staker(&self.stash) {
252			// for direct stakers, update lock on stash based on ledger.
253			asset::update_stake::<T>(&self.stash, self.total)
254				.map_err(|_| Error::<T>::NotEnoughFunds)?;
255		}
256
257		Ledger::<T>::insert(
258			&self.controller().ok_or_else(|| {
259				defensive!("update called on a ledger that is not bonded.");
260				Error::<T>::NotController
261			})?,
262			&self,
263		);
264
265		Ok(())
266	}
267
268	/// Bonds a ledger.
269	///
270	/// It sets the reward preferences for the bonded stash.
271	pub(crate) fn bond(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
272		if <Bonded<T>>::contains_key(&self.stash) {
273			return Err(Error::<T>::AlreadyBonded)
274		}
275
276		<Payee<T>>::insert(&self.stash, payee);
277		<Bonded<T>>::insert(&self.stash, &self.stash);
278		self.update()
279	}
280
281	/// Sets the ledger Payee.
282	pub(crate) fn set_payee(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
283		if !<Bonded<T>>::contains_key(&self.stash) {
284			return Err(Error::<T>::NotStash)
285		}
286
287		<Payee<T>>::insert(&self.stash, payee);
288		Ok(())
289	}
290
291	/// Sets the ledger controller to its stash.
292	pub(crate) fn set_controller_to_stash(self) -> Result<(), Error<T>> {
293		let controller = self.controller.as_ref()
294            .defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.")
295            .ok_or(Error::<T>::NotController)?;
296
297		ensure!(self.stash != *controller, Error::<T>::AlreadyPaired);
298
299		// check if the ledger's stash is a controller of another ledger.
300		if let Some(bonded_ledger) = Ledger::<T>::get(&self.stash) {
301			// there is a ledger bonded by the stash. In this case, the stash of the bonded ledger
302			// should be the same as the ledger's stash. Otherwise fail to prevent data
303			// inconsistencies. See <https://github.com/paritytech/polkadot-sdk/pull/3639> for more
304			// details.
305			ensure!(bonded_ledger.stash == self.stash, Error::<T>::BadState);
306		}
307
308		<Ledger<T>>::remove(&controller);
309		<Ledger<T>>::insert(&self.stash, &self);
310		<Bonded<T>>::insert(&self.stash, &self.stash);
311
312		Ok(())
313	}
314
315	/// Clears all data related to a staking ledger and its bond in both [`Ledger`] and [`Bonded`]
316	/// storage items and updates the stash staking lock.
317	pub(crate) fn kill(stash: &T::AccountId) -> DispatchResult {
318		let controller = <Bonded<T>>::get(stash).ok_or(Error::<T>::NotStash)?;
319
320		<Ledger<T>>::get(&controller).ok_or(Error::<T>::NotController).map(|ledger| {
321			Ledger::<T>::remove(controller);
322			<Bonded<T>>::remove(&stash);
323			<Payee<T>>::remove(&stash);
324
325			// kill virtual staker if it exists.
326			if <VirtualStakers<T>>::take(&ledger.stash).is_none() {
327				// if not virtual staker, clear locks.
328				asset::kill_stake::<T>(&ledger.stash)?;
329			}
330			Pallet::<T>::deposit_event(crate::Event::<T>::StakerRemoved {
331				stash: ledger.stash.clone(),
332			});
333			Ok(())
334		})?
335	}
336
337	#[cfg(test)]
338	pub(crate) fn assert_stash_killed(stash: T::AccountId) {
339		assert!(!Ledger::<T>::contains_key(&stash));
340		assert!(!Bonded::<T>::contains_key(&stash));
341		assert!(!Payee::<T>::contains_key(&stash));
342		assert!(!VirtualStakers::<T>::contains_key(&stash));
343	}
344
345	/// Remove entries from `unlocking` that are sufficiently old and reduce the
346	/// total by the sum of their balances.
347	pub(crate) fn consolidate_unlocked(self, current_era: EraIndex) -> Self {
348		let mut total = self.total;
349		let unlocking: BoundedVec<_, _> = self
350			.unlocking
351			.into_iter()
352			.filter(|chunk| {
353				if chunk.era > current_era {
354					true
355				} else {
356					total = total.saturating_sub(chunk.value);
357					false
358				}
359			})
360			.collect::<Vec<_>>()
361			.try_into()
362			.expect(
363				"filtering items from a bounded vec always leaves length less than bounds. qed",
364			);
365
366		Self {
367			stash: self.stash,
368			total,
369			active: self.active,
370			unlocking,
371			controller: self.controller,
372		}
373	}
374
375	/// Re-bond funds that were scheduled for unlocking.
376	///
377	/// Returns the updated ledger, and the amount actually rebonded.
378	pub(crate) fn rebond(mut self, value: BalanceOf<T>) -> (Self, BalanceOf<T>) {
379		let mut unlocking_balance = BalanceOf::<T>::zero();
380
381		while let Some(last) = self.unlocking.last_mut() {
382			if unlocking_balance.defensive_saturating_add(last.value) <= value {
383				unlocking_balance += last.value;
384				self.active += last.value;
385				self.unlocking.pop();
386			} else {
387				let diff = value.defensive_saturating_sub(unlocking_balance);
388
389				unlocking_balance += diff;
390				self.active += diff;
391				last.value -= diff;
392			}
393
394			if unlocking_balance >= value {
395				break
396			}
397		}
398
399		(self, unlocking_balance)
400	}
401
402	/// Slash the staker for a given amount of balance.
403	///
404	/// This implements a proportional slashing system, whereby we set our preference to slash as
405	/// such:
406	///
407	/// - If any unlocking chunks exist that are scheduled to be unlocked at `slash_era +
408	///   bonding_duration` and onwards, the slash is divided equally between the active ledger and
409	///   the unlocking chunks.
410	/// - If no such chunks exist, then only the active balance is slashed.
411	///
412	/// Note that the above is only a *preference*. If for any reason the active ledger, with or
413	/// without some portion of the unlocking chunks that are more justified to be slashed are not
414	/// enough, then the slashing will continue and will consume as much of the active and unlocking
415	/// chunks as needed.
416	///
417	/// This will never slash more than the given amount. If any of the chunks become dusted, the
418	/// last chunk is slashed slightly less to compensate. Returns the amount of funds actually
419	/// slashed.
420	///
421	/// `slash_era` is the era in which the slash (which is being enacted now) actually happened.
422	///
423	/// This calls `Config::OnStakingUpdate::on_slash` with information as to how the slash was
424	/// applied.
425	pub fn slash(
426		&mut self,
427		slash_amount: BalanceOf<T>,
428		minimum_balance: BalanceOf<T>,
429		slash_era: EraIndex,
430	) -> BalanceOf<T> {
431		if slash_amount.is_zero() {
432			return Zero::zero()
433		}
434
435		use sp_runtime::PerThing as _;
436		let mut remaining_slash = slash_amount;
437		let pre_slash_total = self.total;
438
439		// for a `slash_era = x`, any chunk that is scheduled to be unlocked at era `x + 28`
440		// (assuming 28 is the bonding duration) onwards should be slashed.
441		let slashable_chunks_start = slash_era.saturating_add(T::BondingDuration::get());
442
443		// `Some(ratio)` if this is proportional, with `ratio`, `None` otherwise. In both cases, we
444		// slash first the active chunk, and then `slash_chunks_priority`.
445		let (maybe_proportional, slash_chunks_priority) = {
446			if let Some(first_slashable_index) =
447				self.unlocking.iter().position(|c| c.era >= slashable_chunks_start)
448			{
449				// If there exists a chunk who's after the first_slashable_start, then this is a
450				// proportional slash, because we want to slash active and these chunks
451				// proportionally.
452
453				// The indices of the first chunk after the slash up through the most recent chunk.
454				// (The most recent chunk is at greatest from this era)
455				let affected_indices = first_slashable_index..self.unlocking.len();
456				let unbonding_affected_balance =
457					affected_indices.clone().fold(BalanceOf::<T>::zero(), |sum, i| {
458						if let Some(chunk) = self.unlocking.get(i).defensive() {
459							sum.saturating_add(chunk.value)
460						} else {
461							sum
462						}
463					});
464				let affected_balance = self.active.saturating_add(unbonding_affected_balance);
465				let ratio = Perquintill::from_rational_with_rounding(
466					slash_amount,
467					affected_balance,
468					Rounding::Up,
469				)
470				.unwrap_or_else(|_| Perquintill::one());
471				(
472					Some(ratio),
473					affected_indices.chain((0..first_slashable_index).rev()).collect::<Vec<_>>(),
474				)
475			} else {
476				// We just slash from the last chunk to the most recent one, if need be.
477				(None, (0..self.unlocking.len()).rev().collect::<Vec<_>>())
478			}
479		};
480
481		// Helper to update `target` and the ledgers total after accounting for slashing `target`.
482		log!(
483			trace,
484			"slashing {:?} for era {:?} out of {:?}, priority: {:?}, proportional = {:?}",
485			slash_amount,
486			slash_era,
487			self,
488			slash_chunks_priority,
489			maybe_proportional,
490		);
491
492		let mut slash_out_of = |target: &mut BalanceOf<T>, slash_remaining: &mut BalanceOf<T>| {
493			let mut slash_from_target = if let Some(ratio) = maybe_proportional {
494				ratio.mul_ceil(*target)
495			} else {
496				*slash_remaining
497			}
498			// this is the total that that the slash target has. We can't slash more than
499			// this anyhow!
500			.min(*target)
501			// this is the total amount that we would have wanted to slash
502			// non-proportionally, a proportional slash should never exceed this either!
503			.min(*slash_remaining);
504
505			// slash out from *target exactly `slash_from_target`.
506			*target = *target - slash_from_target;
507			if *target < minimum_balance {
508				// Slash the rest of the target if it's dust. This might cause the last chunk to be
509				// slightly under-slashed, by at most `MaxUnlockingChunks * ED`, which is not a big
510				// deal.
511				slash_from_target =
512					core::mem::replace(target, Zero::zero()).saturating_add(slash_from_target)
513			}
514
515			self.total = self.total.saturating_sub(slash_from_target);
516			*slash_remaining = slash_remaining.saturating_sub(slash_from_target);
517		};
518
519		// If this is *not* a proportional slash, the active will always wiped to 0.
520		slash_out_of(&mut self.active, &mut remaining_slash);
521
522		let mut slashed_unlocking = BTreeMap::<_, _>::new();
523		for i in slash_chunks_priority {
524			if remaining_slash.is_zero() {
525				break
526			}
527
528			if let Some(chunk) = self.unlocking.get_mut(i).defensive() {
529				slash_out_of(&mut chunk.value, &mut remaining_slash);
530				// write the new slashed value of this chunk to the map.
531				slashed_unlocking.insert(chunk.era, chunk.value);
532			} else {
533				break
534			}
535		}
536
537		// clean unlocking chunks that are set to zero.
538		self.unlocking.retain(|c| !c.value.is_zero());
539
540		let final_slashed_amount = pre_slash_total.saturating_sub(self.total);
541		T::EventListeners::on_slash(
542			&self.stash,
543			self.active,
544			&slashed_unlocking,
545			final_slashed_amount,
546		);
547		final_slashed_amount
548	}
549}
550
551/// State of a ledger with regards with its data and metadata integrity.
552#[derive(PartialEq, Debug)]
553pub(crate) enum LedgerIntegrityState {
554	/// Ledger, bond and corresponding staking lock is OK.
555	Ok,
556	/// Ledger and/or bond is corrupted. This means that the bond has a ledger with a different
557	/// stash than the bonded stash.
558	Corrupted,
559	/// Ledger was corrupted and it has been killed.
560	CorruptedKilled,
561	/// Ledger and bond are OK, however the ledger's stash lock is out of sync.
562	LockCorrupted,
563}
564
565// This structs makes it easy to write tests to compare staking ledgers fetched from storage. This
566// is required because the controller field is not stored in storage and it is private.
567#[cfg(test)]
568#[derive(frame_support::DebugNoBound, Clone, Encode, Decode, TypeInfo, MaxEncodedLen)]
569pub struct StakingLedgerInspect<T: Config> {
570	pub stash: T::AccountId,
571	#[codec(compact)]
572	pub total: BalanceOf<T>,
573	#[codec(compact)]
574	pub active: BalanceOf<T>,
575	pub unlocking:
576		frame_support::BoundedVec<crate::UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
577}
578
579#[cfg(test)]
580impl<T: Config> PartialEq<StakingLedgerInspect<T>> for StakingLedger<T> {
581	fn eq(&self, other: &StakingLedgerInspect<T>) -> bool {
582		self.stash == other.stash &&
583			self.total == other.total &&
584			self.active == other.active &&
585			self.unlocking == other.unlocking
586	}
587}
588
589#[cfg(test)]
590impl<T: Config> codec::EncodeLike<StakingLedger<T>> for StakingLedgerInspect<T> {}