referrerpolicy=no-referrer-when-downgrade

pallet_bags_list/
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//! > Made with *Substrate*, for *Polkadot*.
19//!
20//! [![github]](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/bags-list) -
21//! [![polkadot]](https://polkadot.com)
22//!
23//! [polkadot]:
24//!     https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white
25//! [github]:
26//!     https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
27//!
28//!  # Bags-List Pallet
29//!
30//! An onchain implementation of a semi-sorted linked list, with permissionless sorting and update
31//! operations.
32//!
33//! ## Pallet API
34//!
35//! See the [`pallet`] module for more information about the interfaces this pallet exposes,
36//! including its configuration trait, dispatchables, storage items, events and errors.
37//!
38//! This pallet provides an implementation of
39//! [`frame_election_provider_support::SortedListProvider`] and it can typically be used by another
40//! pallet via this API.
41//!
42//! ## Overview
43//!
44//! This pallet splits `AccountId`s into different bags. Within a bag, these `AccountId`s are stored
45//! as nodes in a linked-list manner. This pallet then provides iteration over all bags, which
46//! basically allows an infinitely large list of items to be kept in a sorted manner.
47//!
48//! Each bags has a upper and lower range of scores, denoted by [`Config::BagThresholds`]. All nodes
49//! within a bag must be within the range of the bag. If not, the permissionless [`Pallet::rebag`]
50//! can be used to move any node to the right bag.
51//!
52//! Once a `rebag` happens, the order within a node is still not enforced. To move a node to the
53//! optimal position in a bag, the [`Pallet::put_in_front_of`] or [`Pallet::put_in_front_of_other`]
54//! can be used.
55//!
56//! Additional reading, about how this pallet is used in the context of Polkadot's staking system:
57//! <https://polkadot.com/blog/staking-update-september-2021/#bags-list-in-depth>
58//!
59//! ## Examples
60//!
61//! See [`example`] for a diagram of `rebag` and `put_in_front_of` operations.
62//!
63//! ## Low Level / Implementation Details
64//!
65//! The data structure exposed by this pallet aims to be optimized for:
66//!
67//! - insertions and removals.
68//! - iteration over the top* N items by score, where the precise ordering of items doesn't
69//!   particularly matter.
70//!
71//! ### Further Details
72//!
73//! - items are kept in bags, which are delineated by their range of score (See
74//!   [`Config::BagThresholds`]).
75//! - for iteration, bags are chained together from highest to lowest and elements within the bag
76//!   are iterated from head to tail.
77//! - items within a bag are iterated in order of insertion. Thus removing an item and re-inserting
78//!   it will worsen its position in list iteration; this reduces incentives for some types of spam
79//!   that involve consistently removing and inserting for better position. Further, ordering
80//!   granularity is thus dictated by range between each bag threshold.
81//! - if an item's score changes to a value no longer within the range of its current bag the item's
82//!   position will need to be updated by an external actor with rebag (update), or removal and
83//!   insertion.
84
85#![cfg_attr(not(feature = "std"), no_std)]
86
87extern crate alloc;
88#[cfg(doc)]
89#[cfg_attr(doc, aquamarine::aquamarine)]
90///
91/// In this example, assuming each node has an equal id and score (eg. node 21 has a score of 21),
92/// the node 22 can be moved from bag 1 to bag 0 with the `rebag` operation.
93///
94/// Once the whole list is iterated, assuming the above above rebag happens, the order of iteration
95/// would be: `25, 21, 22, 12, 22, 5, 7, 3`.
96///
97/// Moreover, in bag2, node 7 can be moved to the front of node 5 with the `put_in_front_of`, as it
98/// has a higher score.
99///
100/// ```mermaid
101/// graph LR
102/// 	Bag0 --> Bag1 --> Bag2
103///
104/// 	subgraph Bag0[Bag 0: 21-30 DOT]
105/// 		direction LR
106/// 		25 --> 21 --> 22X[22]
107/// 	end
108///
109/// 	subgraph Bag1[Bag 1: 11-20 DOT]
110/// 		direction LR
111/// 		12 --> 22
112/// 	end
113///
114/// 	subgraph Bag2[Bag 2: 0-10 DOT]
115/// 		direction LR
116/// 		5 --> 7 --> 3
117/// 	end
118///
119/// 	style 22X stroke-dasharray: 5 5,opacity:50%
120/// ```
121///
122/// The equivalent of this in code would be:
123#[doc = docify::embed!("src/tests.rs", examples_work)]
124pub mod example {}
125
126use alloc::{boxed::Box, vec::Vec};
127use codec::FullCodec;
128use frame_election_provider_support::{ScoreProvider, SortedListProvider};
129use frame_support::{
130	traits::Get,
131	weights::{Weight, WeightMeter},
132};
133use frame_system::ensure_signed;
134use sp_runtime::traits::{AtLeast32BitUnsigned, Bounded, StaticLookup};
135
136#[cfg(any(test, feature = "try-runtime", feature = "fuzz"))]
137use sp_runtime::TryRuntimeError;
138
139#[cfg(any(feature = "runtime-benchmarks", test))]
140mod benchmarks;
141
142pub mod list;
143pub mod migrations;
144#[cfg(any(test, feature = "fuzz"))]
145pub mod mock;
146#[cfg(test)]
147mod tests;
148pub mod weights;
149
150pub use list::{notional_bag_for, Bag, List, ListError, Node};
151pub use pallet::*;
152pub use weights::WeightInfo;
153
154pub(crate) const LOG_TARGET: &str = "runtime::bags-list";
155
156// syntactic sugar for logging.
157#[macro_export]
158macro_rules! log {
159	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
160		log::$level!(
161			target: crate::LOG_TARGET,
162			concat!("[{:?}] ๐Ÿ‘œ [{}]", $patter),
163			<frame_system::Pallet<T>>::block_number(),
164			<crate::Pallet::<T, I> as frame_support::traits::PalletInfoAccess>::name()
165			$(, $values)*
166		)
167	};
168}
169
170type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
171
172#[frame_support::pallet]
173pub mod pallet {
174	use super::*;
175	use frame_support::pallet_prelude::*;
176	use frame_system::pallet_prelude::*;
177
178	#[pallet::pallet]
179	pub struct Pallet<T, I = ()>(_);
180
181	#[pallet::config]
182	pub trait Config<I: 'static = ()>: frame_system::Config {
183		/// The overarching event type.
184		#[allow(deprecated)]
185		type RuntimeEvent: From<Event<Self, I>>
186			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
187
188		/// Weight information for extrinsics in this pallet.
189		type WeightInfo: weights::WeightInfo;
190
191		/// Something that provides the scores of ids.
192		type ScoreProvider: ScoreProvider<Self::AccountId, Score = Self::Score>;
193
194		/// The list of thresholds separating the various bags.
195		///
196		/// Ids are separated into unsorted bags according to their score. This specifies the
197		/// thresholds separating the bags. An id's bag is the largest bag for which the id's score
198		/// is less than or equal to its upper threshold.
199		///
200		/// When ids are iterated, higher bags are iterated completely before lower bags. This means
201		/// that iteration is _semi-sorted_: ids of higher score tend to come before ids of lower
202		/// score, but peer ids within a particular bag are sorted in insertion order.
203		///
204		/// # Expressing the constant
205		///
206		/// This constant must be sorted in strictly increasing order. Duplicate items are not
207		/// permitted.
208		///
209		/// There is an implied upper limit of `Score::MAX`; that value does not need to be
210		/// specified within the bag. For any two threshold lists, if one ends with
211		/// `Score::MAX`, the other one does not, and they are otherwise equal, the two
212		/// lists will behave identically.
213		///
214		/// # Calculation
215		///
216		/// It is recommended to generate the set of thresholds in a geometric series, such that
217		/// there exists some constant ratio such that `threshold[k + 1] == (threshold[k] *
218		/// constant_ratio).max(threshold[k] + 1)` for all `k`.
219		///
220		/// The helpers in the `/utils/frame/generate-bags` module can simplify this calculation.
221		///
222		/// # Examples
223		///
224		/// - If `BagThresholds::get().is_empty()`, then all ids are put into the same bag, and
225		///   iteration is strictly in insertion order.
226		/// - If `BagThresholds::get().len() == 64`, and the thresholds are determined according to
227		///   the procedure given above, then the constant ratio is equal to 2.
228		/// - If `BagThresholds::get().len() == 200`, and the thresholds are determined according to
229		///   the procedure given above, then the constant ratio is approximately equal to 1.248.
230		/// - If the threshold list begins `[1, 2, 3, ...]`, then an id with score 0 or 1 will fall
231		///   into bag 0, an id with score 2 will fall into bag 1, etc.
232		///
233		/// # Migration
234		///
235		/// In the event that this list ever changes, a copy of the old bags list must be retained.
236		/// With that `List::migrate` can be called, which will perform the appropriate migration.
237		#[pallet::constant]
238		type BagThresholds: Get<&'static [Self::Score]>;
239
240		/// Maximum number of accounts that may be re-bagged automatically in `on_idle`.
241		///
242		/// A value of `0` (obtained by configuring `type MaxAutoRebagPerBlock = ();`) disables
243		/// the feature.
244		#[pallet::constant]
245		type MaxAutoRebagPerBlock: Get<u32>;
246
247		/// The type used to dictate a node position relative to other nodes.
248		type Score: Clone
249			+ Default
250			+ PartialEq
251			+ Eq
252			+ Ord
253			+ PartialOrd
254			+ core::fmt::Debug
255			+ Copy
256			+ AtLeast32BitUnsigned
257			+ Bounded
258			+ TypeInfo
259			+ FullCodec
260			+ MaxEncodedLen;
261	}
262
263	/// A single node, within some bag.
264	///
265	/// Nodes store links forward and back within their respective bags.
266	#[pallet::storage]
267	pub type ListNodes<T: Config<I>, I: 'static = ()> =
268		CountedStorageMap<_, Twox64Concat, T::AccountId, list::Node<T, I>>;
269
270	/// A bag stored in storage.
271	///
272	/// Stores a `Bag` struct, which stores head and tail pointers to itself.
273	#[pallet::storage]
274	pub type ListBags<T: Config<I>, I: 'static = ()> =
275		StorageMap<_, Twox64Concat, T::Score, list::Bag<T, I>>;
276
277	/// Pointer that remembers the next node that will be auto-rebagged.
278	/// When `None`, the next scan will start from the list head again.
279	#[pallet::storage]
280	pub type NextNodeAutoRebagged<T: Config<I>, I: 'static = ()> =
281		StorageValue<_, T::AccountId, OptionQuery>;
282
283	/// Lock all updates to this pallet.
284	///
285	/// If any nodes needs updating, removal or addition due to a temporary lock, the
286	/// [`Call::rebag`] can be used.
287	#[pallet::storage]
288	pub type Lock<T: Config<I>, I: 'static = ()> = StorageValue<_, (), OptionQuery>;
289
290	/// Accounts that failed to be inserted into the bags-list due to locking.
291	/// These accounts will be processed with priority in `on_idle` or via `rebag` extrinsic.
292	///
293	/// Note: This storage is intentionally unbounded. The following factors make bounding
294	/// unnecessary:
295	/// 1. The storage usage is temporary - accounts are processed and removed in `on_idle`
296	/// 2. The pallet is only locked during snapshot generation, which is weight-limited
297	/// 3. Processing happens at multiple accounts per block, clearing even large backlogs quickly
298	/// 4. An artificial limit could be exhausted by an attacker, preventing legitimate
299	///    auto-rebagging from putting accounts in the correct position
300	///
301	/// We don't store the score here - it's always fetched from `ScoreProvider` when processing,
302	/// ensuring we use the most up-to-date score (accounts may have been slashed, rewarded, etc.
303	/// while waiting in the queue).
304	#[pallet::storage]
305	pub type PendingRebag<T: Config<I>, I: 'static = ()> =
306		CountedStorageMap<_, Twox64Concat, T::AccountId, ()>;
307
308	#[pallet::event]
309	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
310	pub enum Event<T: Config<I>, I: 'static = ()> {
311		/// Moved an account from one bag to another.
312		Rebagged { who: T::AccountId, from: T::Score, to: T::Score },
313		/// Updated the score of some account to the given amount.
314		ScoreUpdated { who: T::AccountId, new_score: T::Score },
315	}
316
317	#[pallet::error]
318	pub enum Error<T, I = ()> {
319		/// A error in the list interface implementation.
320		List(ListError),
321		/// Could not update a node, because the pallet is locked.
322		Locked,
323	}
324
325	impl<T, I> From<ListError> for Error<T, I> {
326		fn from(t: ListError) -> Self {
327			Error::<T, I>::List(t)
328		}
329	}
330
331	#[pallet::view_functions]
332	impl<T: Config<I>, I: 'static> Pallet<T, I> {
333		/// Get the current `score` of a given account.
334		///
335		/// Returns `(current, real_score)`, the former being the current score that this pallet is
336		/// aware of, which may or may not be up to date, and the latter being the real score, as
337		/// provided by
338		// [`Config::ScoreProvider`].
339		///
340		/// If the two differ, it means this node is eligible for [`Call::rebag`].
341		pub fn scores(who: T::AccountId) -> (Option<T::Score>, Option<T::Score>) {
342			(ListNodes::<T, I>::get(&who).map(|node| node.score), T::ScoreProvider::score(&who))
343		}
344	}
345
346	#[pallet::call]
347	impl<T: Config<I>, I: 'static> Pallet<T, I> {
348		/// Declare that some `dislocated` account has, through rewards or penalties, sufficiently
349		/// changed its score that it should properly fall into a different bag than its current
350		/// one.
351		///
352		/// Anyone can call this function about any potentially dislocated account.
353		///
354		/// Will always update the stored score of `dislocated` to the correct score, based on
355		/// `ScoreProvider`.
356		///
357		/// If `dislocated` does not exists, it returns an error.
358		#[pallet::call_index(0)]
359		#[pallet::weight(T::WeightInfo::rebag_non_terminal().max(T::WeightInfo::rebag_terminal()))]
360		pub fn rebag(origin: OriginFor<T>, dislocated: AccountIdLookupOf<T>) -> DispatchResult {
361			ensure_signed(origin)?;
362			let dislocated = T::Lookup::lookup(dislocated)?;
363			Self::ensure_unlocked().map_err(|_| Error::<T, I>::Locked)?;
364
365			Self::rebag_internal(&dislocated).map_err::<DispatchError, _>(Into::into)?;
366
367			Ok(())
368		}
369
370		/// Move the caller's Id directly in front of `lighter`.
371		///
372		/// The dispatch origin for this call must be _Signed_ and can only be called by the Id of
373		/// the account going in front of `lighter`. Fee is payed by the origin under all
374		/// circumstances.
375		///
376		/// Only works if:
377		///
378		/// - both nodes are within the same bag,
379		/// - and `origin` has a greater `Score` than `lighter`.
380		#[pallet::call_index(1)]
381		#[pallet::weight(T::WeightInfo::put_in_front_of())]
382		pub fn put_in_front_of(
383			origin: OriginFor<T>,
384			lighter: AccountIdLookupOf<T>,
385		) -> DispatchResult {
386			let heavier = ensure_signed(origin)?;
387			let lighter = T::Lookup::lookup(lighter)?;
388			Self::ensure_unlocked().map_err(|_| Error::<T, I>::Locked)?;
389			List::<T, I>::put_in_front_of(&lighter, &heavier)
390				.map_err::<Error<T, I>, _>(Into::into)
391				.map_err::<DispatchError, _>(Into::into)
392		}
393
394		/// Same as [`Pallet::put_in_front_of`], but it can be called by anyone.
395		///
396		/// Fee is paid by the origin under all circumstances.
397		#[pallet::call_index(2)]
398		#[pallet::weight(T::WeightInfo::put_in_front_of())]
399		pub fn put_in_front_of_other(
400			origin: OriginFor<T>,
401			heavier: AccountIdLookupOf<T>,
402			lighter: AccountIdLookupOf<T>,
403		) -> DispatchResult {
404			ensure_signed(origin)?;
405			let lighter = T::Lookup::lookup(lighter)?;
406			let heavier = T::Lookup::lookup(heavier)?;
407			Self::ensure_unlocked().map_err(|_| Error::<T, I>::Locked)?;
408			List::<T, I>::put_in_front_of(&lighter, &heavier)
409				.map_err::<Error<T, I>, _>(Into::into)
410				.map_err::<DispatchError, _>(Into::into)
411		}
412	}
413
414	#[pallet::hooks]
415	impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
416		fn integrity_test() {
417			// to ensure they are strictly increasing, this also implies that duplicates are
418			// detected.
419			assert!(
420				T::BagThresholds::get().windows(2).all(|window| window[1] > window[0]),
421				"thresholds must strictly increase, and have no duplicates",
422			);
423		}
424
425		#[cfg(feature = "try-runtime")]
426		fn try_state(_: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
427			<Self as SortedListProvider<T::AccountId>>::try_state()
428		}
429
430		/// Called during the idle phase of block execution.
431		/// Automatically performs a limited number of `rebag` operations each block,
432		/// incrementally correcting the position of accounts within the bags-list.
433		///
434		/// Processes accounts in the following priority order:
435		/// 1. Pending accounts that failed to be inserted due to locking
436		/// 2. Regular accounts that need rebagging
437		///
438		/// Guarantees processing as many nodes as possible without failing on errors.
439		/// It stores a persistent cursor to continue across blocks.
440		fn on_idle(_n: BlockNumberFor<T>, limit: Weight) -> Weight {
441			let mut meter = WeightMeter::with_limit(limit);
442			// This weight assumes worst-case usage of `MaxAutoRebagPerBlock`.
443			// Changing the runtime value requires re-running the benchmarks.
444			if meter.try_consume(T::WeightInfo::on_idle()).is_err() {
445				log!(debug, "Not enough Weight for on_idle. Skipping rebugging.");
446				return Weight::zero();
447			}
448
449			let rebag_budget = T::MaxAutoRebagPerBlock::get();
450			if rebag_budget == 0 {
451				log!(debug, "Auto-rebag skipped: rebag_budget=0");
452				return meter.consumed();
453			}
454
455			let total_nodes = ListNodes::<T, I>::count();
456			let pending_count = PendingRebag::<T, I>::count();
457
458			if total_nodes == 0 && pending_count == 0 {
459				log!(debug, "Auto-rebag skipped: total_nodes=0 and pending_count=0");
460				return meter.consumed();
461			}
462
463			if Self::ensure_unlocked().is_err() {
464				log!(debug, "Auto-rebag skipped: pallet is locked");
465				return meter.consumed();
466			}
467
468			log!(
469				debug,
470				"Starting auto-rebag. Budget: {} accounts/block, total_nodes={}, pending_count={}.",
471				rebag_budget,
472				total_nodes,
473				pending_count
474			);
475
476			let cursor = NextNodeAutoRebagged::<T, I>::get();
477			let regular_iter = match cursor {
478				Some(ref last) => {
479					log!(debug, "Next node from previous block: {:?}", last);
480
481					// Build an iterator that yields `last` first, then everything *after* it.
482					let tail = Self::iter_from(last).unwrap_or_else(|_| Self::iter());
483					let head_and_tail = core::iter::once(last.clone()).chain(tail);
484					Box::new(head_and_tail) as Box<dyn Iterator<Item = T::AccountId>>
485				},
486				None => {
487					log!(debug, "No NextNodeAutoRebagged found. Starting from head of the list");
488					Self::iter()
489				},
490			};
491
492			// Chain PendingRebag accounts with regular ListNodes.
493			// PendingRebag comes first for priority processing
494			let combined_iter = PendingRebag::<T, I>::iter_keys().chain(regular_iter);
495
496			let accounts: Vec<_> = combined_iter.take((rebag_budget + 1) as usize).collect();
497
498			// Safe split: if we reached (or passed) the tail of the list, we don't want to panic.
499			let (to_process, next_cursor) = if accounts.len() <= rebag_budget as usize {
500				// This guarantees we either get the next account to process
501				// or gracefully receive None.
502				(accounts.as_slice(), &[][..])
503			} else {
504				accounts.split_at(rebag_budget as usize)
505			};
506
507			let mut processed = 0u32;
508			let mut successful_rebags = 0u32;
509			let mut failed_rebags = 0u32;
510			let mut pending_processed = 0u32;
511
512			for account in to_process {
513				let pending_value =
514					if PendingRebag::<T, I>::contains_key(&account) { 1 } else { 0 };
515
516				match Self::rebag_internal(&account) {
517					Err(Error::<T, I>::Locked) => {
518						defensive!("Pallet became locked during auto-rebag, stopping");
519						break;
520					},
521					Err(e) => {
522						log!(warn, "Error during rebagging: {:?}", e);
523						failed_rebags += 1;
524					},
525					Ok(Some((from, to))) => {
526						log!(debug, "Rebagged {:?}: moved from {:?} to {:?}", account, from, to);
527						successful_rebags += 1;
528						pending_processed += pending_value;
529					},
530					Ok(None) => {
531						log!(debug, "Rebagging not needed for {:?}", account);
532						pending_processed += pending_value;
533					},
534				}
535
536				processed += 1;
537				if processed == rebag_budget {
538					break;
539				}
540			}
541
542			// Update cursor - only track regular ListNodes accounts, not PendingRebag
543			let next_regular_account =
544				next_cursor.iter().find(|account| !PendingRebag::<T, I>::contains_key(account));
545
546			match next_regular_account {
547				// Defensive check: prevents re-processing the same node multiple times within a
548				// single block. This situation should not occur during normal execution, but
549				// can happen in test environments or if `on_idle()` is invoked more than once
550				// per block (e.g. via custom test harnesses or manual calls).
551				Some(next) if to_process.contains(next) => {
552					NextNodeAutoRebagged::<T, I>::kill();
553					defensive!("Loop detected: {:?} already processed โ€” cursor killed", next);
554				},
555				// Normal case: save the next regular node as a cursor for the following block.
556				Some(next) => {
557					NextNodeAutoRebagged::<T, I>::put(next);
558					log!(debug, "Saved next node to be processed in rebag cursor: {:?}", next);
559				},
560				// End of regular list reached: no cursor needed.
561				// This happens when either:
562				// 1. We've processed all regular accounts in the list, OR
563				// 2. We've collected fewer than budget+1 accounts (meaning the iterator was
564				//    exhausted)
565				// Since pending accounts are processed first and not tracked in the cursor,
566				// this simply means there are no more regular accounts to process.
567				None => {
568					NextNodeAutoRebagged::<T, I>::kill();
569					log!(debug, "End of regular list reached โ€” cursor killed");
570				},
571			}
572
573			let weight_used = meter.consumed();
574			log!(
575				debug,
576				"Auto-rebag finished: processed={}, successful_rebags={}, errors={}, pending_processed={}, weight_used={:?}",
577				processed,
578				successful_rebags,
579				failed_rebags,
580				pending_processed,
581				weight_used
582			);
583
584			weight_used
585		}
586	}
587}
588
589#[cfg(any(test, feature = "try-runtime", feature = "fuzz"))]
590impl<T: Config<I>, I: 'static> Pallet<T, I> {
591	pub fn do_try_state() -> Result<(), TryRuntimeError> {
592		List::<T, I>::do_try_state()
593	}
594}
595
596impl<T: Config<I>, I: 'static> Pallet<T, I> {
597	/// Move an account from one bag to another, depositing an event on success.
598	///
599	/// If the account changed bags, returns `Ok(Some((from, to)))`.
600	pub fn do_rebag(
601		account: &T::AccountId,
602		new_score: T::Score,
603	) -> Result<Option<(T::Score, T::Score)>, ListError> {
604		// If no voter at that node, don't do anything. the caller just wasted the fee to call this.
605		let node = list::Node::<T, I>::get(&account).ok_or(ListError::NodeNotFound)?;
606		if node.score != new_score {
607			Self::deposit_event(Event::<T, I>::ScoreUpdated { who: account.clone(), new_score });
608		}
609		let maybe_movement = List::update_position_for(node, new_score);
610		if let Some((from, to)) = maybe_movement {
611			Self::deposit_event(Event::<T, I>::Rebagged { who: account.clone(), from, to });
612		};
613		Ok(maybe_movement)
614	}
615
616	fn ensure_unlocked() -> Result<(), ListError> {
617		match Lock::<T, I>::get() {
618			None => Ok(()),
619			Some(()) => Err(ListError::Locked),
620		}
621	}
622
623	/// Equivalent to `ListBags::get`, but public. Useful for tests in outside of this crate.
624	#[cfg(feature = "std")]
625	pub fn list_bags_get(score: T::Score) -> Option<list::Bag<T, I>> {
626		ListBags::get(score)
627	}
628
629	/// Perform the internal rebagging logic for an account based on its updated score.
630	/// This function does not handle origin checks or higher-level dispatch logic.
631	///
632	/// Returns `Ok(Some((from, to)))` if rebagging occurred, or `Ok(None)` if nothing changed.
633	fn rebag_internal(account: &T::AccountId) -> Result<Option<(T::Score, T::Score)>, Error<T, I>> {
634		// Ensure the pallet is not locked
635		Self::ensure_unlocked().map_err(|_| Error::<T, I>::Locked)?;
636
637		PendingRebag::<T, I>::remove(account);
638
639		// Check if the account exists and retrieve its current score
640		let existed = ListNodes::<T, I>::contains_key(account);
641		let maybe_score = T::ScoreProvider::score(account);
642
643		match (existed, maybe_score) {
644			(true, Some(current_score)) => {
645				// The account exists and has a valid score, so try to rebag
646				log!(debug, "Attempting to rebag node {:?}", account);
647				Pallet::<T, I>::do_rebag(account, current_score)
648					.map_err::<Error<T, I>, _>(Into::into)
649			},
650			(false, Some(current_score)) => {
651				// The account doesn't exist, but it has a valid score - insert it
652				log!(debug, "Inserting node {:?} with score {:?}", account, current_score);
653				List::<T, I>::insert(account.clone(), current_score)
654					.map_err::<Error<T, I>, _>(Into::into)?;
655				Ok(None)
656			},
657			(true, None) => {
658				// The account exists but no longer has a valid score, so remove it
659				log!(debug, "Removing node {:?}", account);
660				List::<T, I>::remove(account).map_err::<Error<T, I>, _>(Into::into)?;
661				Ok(None)
662			},
663			(false, None) => {
664				// The account doesn't exist and has no valid score - do nothing
665				Err(Error::<T, I>::List(ListError::NodeNotFound))
666			},
667		}
668	}
669}
670
671impl<T: Config<I>, I: 'static> SortedListProvider<T::AccountId> for Pallet<T, I> {
672	type Error = ListError;
673	type Score = T::Score;
674
675	fn range() -> (Self::Score, Self::Score) {
676		use frame_support::traits::Get;
677		(
678			T::BagThresholds::get().first().cloned().unwrap_or_default(),
679			T::BagThresholds::get().last().cloned().unwrap_or_default(),
680		)
681	}
682
683	fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
684		Box::new(List::<T, I>::iter().map(|n| n.id().clone()))
685	}
686
687	fn lock() {
688		Lock::<T, I>::put(())
689	}
690
691	fn unlock() {
692		Lock::<T, I>::kill()
693	}
694
695	fn iter_from(
696		start: &T::AccountId,
697	) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
698		let iter = List::<T, I>::iter_from(start)?;
699		Ok(Box::new(iter.map(|n| n.id().clone())))
700	}
701
702	fn count() -> u32 {
703		ListNodes::<T, I>::count()
704	}
705
706	fn contains(id: &T::AccountId) -> bool {
707		List::<T, I>::contains(id)
708	}
709
710	fn on_insert(id: T::AccountId, score: T::Score) -> Result<(), ListError> {
711		Pallet::<T, I>::ensure_unlocked().inspect_err(|_| {
712			// Pallet is locked - store in PendingRebag for later processing
713			// Only queue if auto-rebagging is enabled
714			if T::MaxAutoRebagPerBlock::get() > 0u32 {
715				PendingRebag::<T, I>::insert(&id, ());
716			}
717		})?;
718		List::<T, I>::insert(id, score)
719	}
720
721	fn on_update(id: &T::AccountId, new_score: T::Score) -> Result<(), ListError> {
722		Pallet::<T, I>::ensure_unlocked()?;
723		Pallet::<T, I>::do_rebag(id, new_score).map(|_| ())
724	}
725
726	fn get_score(id: &T::AccountId) -> Result<T::Score, ListError> {
727		List::<T, I>::get_score(id)
728	}
729
730	fn on_remove(id: &T::AccountId) -> Result<(), ListError> {
731		Pallet::<T, I>::ensure_unlocked()?;
732		List::<T, I>::remove(id)
733	}
734
735	fn unsafe_regenerate(
736		all: impl IntoIterator<Item = T::AccountId>,
737		score_of: Box<dyn Fn(&T::AccountId) -> Option<T::Score>>,
738	) -> u32 {
739		// NOTE: This call is unsafe for the same reason as SortedListProvider::unsafe_regenerate.
740		// I.e. because it can lead to many storage accesses.
741		// So it is ok to call it as caller must ensure the conditions.
742		List::<T, I>::unsafe_regenerate(all, score_of)
743	}
744
745	fn unsafe_clear() {
746		// NOTE: This call is unsafe for the same reason as SortedListProvider::unsafe_clear.
747		// I.e. because it can lead to many storage accesses.
748		// So it is ok to call it as caller must ensure the conditions.
749		List::<T, I>::unsafe_clear()
750	}
751
752	#[cfg(feature = "try-runtime")]
753	fn try_state() -> Result<(), TryRuntimeError> {
754		Self::do_try_state()
755	}
756
757	frame_election_provider_support::runtime_benchmarks_enabled! {
758		fn score_update_worst_case(who: &T::AccountId, is_increase: bool) -> Self::Score {
759			use frame_support::traits::Get as _;
760			let thresholds = T::BagThresholds::get();
761			let node = list::Node::<T, I>::get(who).unwrap();
762			let current_bag_idx = thresholds
763				.iter()
764				.chain(core::iter::once(&T::Score::max_value()))
765				.position(|w| w == &node.bag_upper)
766				.unwrap();
767
768			if is_increase {
769				let next_threshold_idx = current_bag_idx + 1;
770				assert!(thresholds.len() > next_threshold_idx);
771				thresholds[next_threshold_idx]
772			} else {
773				assert!(current_bag_idx != 0);
774				let prev_threshold_idx = current_bag_idx - 1;
775				thresholds[prev_threshold_idx]
776			}
777		}
778	}
779}
780
781impl<T: Config<I>, I: 'static> ScoreProvider<T::AccountId> for Pallet<T, I> {
782	type Score = <Pallet<T, I> as SortedListProvider<T::AccountId>>::Score;
783
784	fn score(id: &T::AccountId) -> Option<T::Score> {
785		Node::<T, I>::get(id).map(|node| node.score())
786	}
787
788	frame_election_provider_support::runtime_benchmarks_or_std_enabled! {
789		fn set_score_of(id: &T::AccountId, new_score: T::Score) {
790			ListNodes::<T, I>::mutate(id, |maybe_node| {
791				if let Some(node) = maybe_node.as_mut() {
792					node.score = new_score;
793				} else {
794					panic!("trying to mutate {:?} which does not exists", id);
795				}
796			})
797		}
798	}
799}