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