referrerpolicy=no-referrer-when-downgrade

sc_statement_store/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19#![doc = include_str!("../docs/overview.md")]
20#![doc = include_str!("../docs/usage.md")]
21//! # Implementation notes
22//!
23//! This crate contains a disk-backed implementation of `sp_statement_store::StatementStore`.
24//!
25//! ## Constraint management
26//!
27//! The statement store validates statements using node-side signature verification and
28//! static runtime allowance limits.
29//! The following constraints are then checked:
30//! * For a given account id, there may be at most `max_count` statements with `max_size` total data
31//!   size. To satisfy this, statements for this account ID are removed from the store starting with
32//!   the lowest priority until a constraint is satisfied.
33//! * There may not be more than `MAX_TOTAL_STATEMENTS` total statements with `MAX_TOTAL_SIZE` size.
34//!   To satisfy this, statements are removed from the store starting with the lowest
35//!   `global_priority` until a constraint is satisfied.
36//! * On the v2 DHT path, the statements kept for DHT affinity and the transient ones each have
37//!   their own size limit. Statements kept only for explicit affinity have no limit of their own.
38//!
39//! When a new statement is inserted that would not satisfy constraints in the first place, no
40//! statements are deleted and a `Rejected` result is returned.
41//! The order in which statements with the same priority are deleted is unspecified.
42//!
43//! ## Statement expiration
44//!
45//! Each time a statement is removed from the store (Either evicted by higher priority statement or
46//! explicitly with the `remove` function) the statement is marked as expired. Expired statements
47//! can't be added to the store for `Options::purge_after_sec` seconds. This is to prevent old
48//! statements from being propagated on the network.
49
50#![warn(missing_docs)]
51#![warn(unused_extern_crates)]
52
53mod metrics;
54mod subscription;
55
56#[cfg(feature = "test-helpers")]
57pub mod subxt_client;
58#[cfg(feature = "test-helpers")]
59pub mod test_utils;
60
61use crate::subscription::{SubscriptionStatementsStream, SubscriptionsHandle};
62use futures::FutureExt;
63use metrics::MetricsLink as PrometheusMetrics;
64use parking_lot::RwLock;
65use prometheus_endpoint::Registry as PrometheusRegistry;
66use sc_client_api::{backend::StorageProvider, Backend, StorageKey};
67use sc_keystore::LocalKeystore;
68pub use sc_network_statement::RetentionReasonMask;
69use schnellru::{ByLength, LruMap};
70use sp_blockchain::HeaderBackend;
71use sp_core::{crypto::UncheckedFrom, hexdisplay::HexDisplay, traits::SpawnNamed, Decode, Encode};
72use sp_runtime::traits::Block as BlockT;
73use sp_statement_store::{
74	runtime_api::{StatementSource, StatementStoreExt},
75	AccountId, AdmittedBatch, BlockHash, Channel, DecryptionKey, FilterDecision, Hash,
76	InvalidReason, OptimizedTopicFilter, RejectionReason, Result, SignatureVerificationResult,
77	Statement, StatementAllowance, StatementEvent, SubmitResult,
78};
79pub use sp_statement_store::{Error, StatementStore, Topic, MAX_TOPICS};
80use std::{
81	collections::{BTreeMap, HashMap, HashSet},
82	sync::{
83		atomic::{AtomicU64, AtomicUsize, Ordering as AtomicOrdering},
84		Arc, Weak,
85	},
86	time::{Duration, Instant},
87};
88pub use subscription::{
89	AddFilterError, MultiFilterEventStream, MultiFilterSubscriptionApi,
90	MultiFilterSubscriptionEvent, StatementStoreSubscriptionApi, SubscriptionHandle,
91	MAX_FILTERS_PER_SUBSCRIPTION,
92};
93use subscription::{ReplayBatch, ReplaySnapshotProvider, REPLAY_CHUNK_RAW_BYTES};
94
95const KEY_VERSION: &[u8] = b"version".as_slice();
96const CURRENT_VERSION: u32 = 3;
97
98/// Meta column key of the persisted global counters, SCALE-encoded as
99/// `(totals: StoreTotals, next_seq: u64)`. The row is rewritten as part of
100/// every mutating commit (all of which happen under the submit-index write lock), so it is always
101/// consistent with the statement data and makes startup independent of the store size.
102const KEY_COUNTERS: &[u8] = b"counters".as_slice();
103
104const MIGRATION_COMMIT_CHUNK: usize = 100_000;
105
106/// A single raw database operation: writes `value` under `key` in `column`, or deletes the key
107/// when `value` is `None`.
108struct DbOperation {
109	column: u8,
110	key: Vec<u8>,
111	value: Option<Vec<u8>>,
112}
113
114impl From<(u8, Vec<u8>, Option<Vec<u8>>)> for DbOperation {
115	fn from((column, key, value): (u8, Vec<u8>, Option<Vec<u8>>)) -> Self {
116		Self { column, key, value }
117	}
118}
119
120struct MigrationBatch<'a> {
121	db: &'a parity_db::Db,
122	operations: Vec<DbOperation>,
123	committed: usize,
124}
125
126impl<'a> MigrationBatch<'a> {
127	fn new(db: &'a parity_db::Db) -> Self {
128		Self { db, operations: Vec::new(), committed: 0 }
129	}
130
131	fn push(&mut self, operation: DbOperation) -> Result<()> {
132		self.operations.push(operation);
133		self.flush_if_full()
134	}
135
136	fn extend(&mut self, operations: impl IntoIterator<Item = DbOperation>) -> Result<()> {
137		self.operations.extend(operations);
138		self.flush_if_full()
139	}
140
141	fn flush_if_full(&mut self) -> Result<()> {
142		if self.operations.len() >= MIGRATION_COMMIT_CHUNK {
143			self.flush()?;
144		}
145		Ok(())
146	}
147
148	fn flush(&mut self) -> Result<()> {
149		if self.operations.is_empty() {
150			return Ok(());
151		}
152		let operations = std::mem::take(&mut self.operations);
153		let count = operations.len();
154		self.db
155			.commit(
156				operations
157					.into_iter()
158					.map(|operation| (operation.column, operation.key, operation.value)),
159			)
160			.map_err(|error| Error::Db(error.to_string()))?;
161		self.committed += count;
162		Ok(())
163	}
164
165	fn finish(mut self) -> Result<usize> {
166		self.flush()?;
167		Ok(self.committed)
168	}
169}
170
171const LOG_TARGET: &str = "statement-store";
172
173/// The amount of time an expired statement is kept before it is removed from the store entirely.
174pub const DEFAULT_PURGE_AFTER_SEC: u64 = 2 * 24 * 60 * 60; // 48h
175/// The maximum number of statements the statement store can hold.
176pub const DEFAULT_MAX_TOTAL_STATEMENTS: usize = 4 * 1024 * 1024; // ~4 million
177/// The maximum amount of data the statement store can hold, regardless of the number of
178/// statements from which the data originates.
179pub const DEFAULT_MAX_TOTAL_SIZE: usize = 2 * 1024 * 1024 * 1024; // 2GiB
180/// The maximum size of a single statement in bytes.
181/// Accounts for the 1-byte vector length prefix when statements are gossiped as `Vec<Statement>`.
182pub const MAX_STATEMENT_SIZE: usize =
183	sc_network_statement::config::MAX_STATEMENT_NOTIFICATION_SIZE as usize - 1;
184
185/// Maximum number of statements to expire in a single iteration.
186const MAX_EXPIRY_STATEMENTS_PER_ITERATION: usize = 10_000;
187/// Maximum number of accounts to check for expiry in a single iteration.
188const MAX_EXPIRY_ACCOUNTS_PER_ITERATION: usize = 10_000;
189/// Maximum time in milliseconds to spend checking for expiry in a single iteration.
190const MAX_EXPIRY_TIME_PER_ITERATION: Duration = Duration::from_millis(100);
191
192/// Number of subscription filter worker tasks.
193const NUM_FILTER_WORKERS: usize = 1;
194
195const MAINTENANCE_PERIOD: std::time::Duration = std::time::Duration::from_secs(29);
196
197/// Specifies which block hash to use when reading statement allowances.
198enum AllowanceBlock {
199	/// Use the best (latest) block hash.
200	Best,
201	/// Use the finalized block hash.
202	Finalized,
203}
204
205// Period between enforcing limits (checking for expired statements and making sure statements stay
206// within allowances). Different from maintenance period to avoid keeping the lock for too long for
207// maintenance tasks. If expired statements are still due after a pass, the background task runs the
208// next pass after `ENFORCE_LIMITS_BACKLOG_PERIOD` instead of waiting for the next tick.
209const ENFORCE_LIMITS_PERIOD: std::time::Duration = std::time::Duration::from_secs(31);
210
211// Delay before the next enforce-limits pass while expired statements are still due. Each pass is
212// bounded by `MAX_EXPIRY_STATEMENTS_PER_ITERATION` and `MAX_EXPIRY_TIME_PER_ITERATION`; the delay
213// keeps the sweep from holding the store lock back to back, so inbound statements are not starved
214// while a backlog drains.
215const ENFORCE_LIMITS_BACKLOG_PERIOD: std::time::Duration = std::time::Duration::from_millis(500);
216
217mod col {
218	pub const META: u8 = 0;
219	pub const STATEMENTS: u8 = 1;
220	pub const EXPIRED: u8 = 2;
221	pub const INDEX_BY_TOPIC: u8 = 3;
222	pub const INDEX_BY_DEC_KEY: u8 = 4;
223	pub const INDEX_EVICTED: u8 = 5;
224	pub const ADMISSION_SEQ: u8 = 6;
225	pub const INDEX_BY_ACCOUNT: u8 = 7;
226	pub const INDEX_BY_EXPIRY: u8 = 8;
227
228	pub const COUNT: u8 = 9;
229}
230
231/// Btree-indexed columns (ordered keys with prefix scans), as opposed to the hash columns.
232const BTREE_COLUMNS: [u8; 6] = [
233	col::INDEX_BY_TOPIC,
234	col::INDEX_BY_DEC_KEY,
235	col::INDEX_EVICTED,
236	col::ADMISSION_SEQ,
237	col::INDEX_BY_ACCOUNT,
238	col::INDEX_BY_EXPIRY,
239];
240
241/// Budget of the per-account details cache, measured in cached statements across all account
242/// records (a record costs at least one unit). Bounds cache memory regardless of how statements
243/// are distributed over accounts.
244#[cfg(not(test))]
245const DETAILS_CACHE_BUDGET: usize = 65_536;
246#[cfg(test)]
247const DETAILS_CACHE_BUDGET: usize = 8;
248
249/// Maximum number of per-account count/size summaries kept in memory.
250#[cfg(not(test))]
251const SUMMARY_CACHE_ACCOUNTS: u32 = 131_072;
252#[cfg(test)]
253const SUMMARY_CACHE_ACCOUNTS: u32 = 4;
254
255const INDEX_EMPTY_VALUE: &[u8] = &[];
256const DEC_KEY_TAG_NONE: u8 = 0;
257const DEC_KEY_TAG_SOME: u8 = 1;
258
259fn topic_index_key(topic: &Topic, hash: &Hash) -> Vec<u8> {
260	let mut key = Vec::with_capacity(topic.len() + hash.len());
261	key.extend_from_slice(&topic[..]);
262	key.extend_from_slice(&hash[..]);
263	key
264}
265
266fn dec_key_index_prefix(dec_key: &Option<DecryptionKey>) -> Vec<u8> {
267	match dec_key {
268		None => vec![DEC_KEY_TAG_NONE],
269		Some(dec_key) => {
270			let mut prefix = Vec::with_capacity(1 + dec_key.len());
271			prefix.push(DEC_KEY_TAG_SOME);
272			prefix.extend_from_slice(&dec_key[..]);
273			prefix
274		},
275	}
276}
277
278fn dec_key_index_key(dec_key: &Option<DecryptionKey>, hash: &Hash) -> Vec<u8> {
279	let mut key = dec_key_index_prefix(dec_key);
280	key.extend_from_slice(&hash[..]);
281	key
282}
283
284/// Reverses [`dec_key_index_prefix`]; `None` if `prefix` does not have that layout.
285fn parse_dec_key_index_prefix(prefix: &[u8]) -> Option<Option<DecryptionKey>> {
286	match prefix.split_first() {
287		Some((&DEC_KEY_TAG_NONE, [])) => Some(None),
288		Some((&DEC_KEY_TAG_SOME, dec_key)) if dec_key.len() == size_of::<DecryptionKey>() => {
289			dec_key.try_into().ok().map(Some)
290		},
291		_ => {
292			log::error!(
293				target: LOG_TARGET,
294				"Corrupt decryption-key index prefix: {:?}",
295				HexDisplay::from(&prefix)
296			);
297			None
298		},
299	}
300}
301
302fn evicted_index_key(purge_at: u64, hash: &Hash) -> Vec<u8> {
303	let mut key = Vec::with_capacity(8 + hash.len());
304	key.extend_from_slice(&purge_at.to_be_bytes());
305	key.extend_from_slice(&hash[..]);
306	key
307}
308
309/// Key of a statement's row in [`col::INDEX_BY_ACCOUNT`]
310fn account_index_key(account: &AccountId, expiry: Expiry, hash: &Hash) -> Vec<u8> {
311	let mut key = Vec::with_capacity(account.len() + size_of::<u64>() + hash.len());
312	key.extend_from_slice(&account[..]);
313	key.extend_from_slice(&expiry.0.to_be_bytes());
314	key.extend_from_slice(&hash[..]);
315	key
316}
317
318/// Reverses [`account_index_key`]; `None` if `key` does not have that layout.
319fn parse_account_index_key(key: &[u8]) -> Option<(AccountId, Expiry, Hash)> {
320	if key.len() != size_of::<AccountId>() + size_of::<u64>() + size_of::<Hash>() {
321		log::error!(
322			target: LOG_TARGET,
323			"Corrupt account index key: {:?}",
324			HexDisplay::from(&key)
325		);
326		return None;
327	}
328	let (account, rest) = key.split_at(size_of::<AccountId>());
329	let (expiry, hash) = rest.split_at(size_of::<u64>());
330	Some((
331		account.try_into().ok()?,
332		Expiry(u64::from_be_bytes(expiry.try_into().ok()?)),
333		hash.try_into().ok()?,
334	))
335}
336
337/// Key of a statement's row in [`col::INDEX_BY_EXPIRY`]: the whole column iterates in expiry
338/// order, so the statements due for expiry form a prefix of it.
339fn expiry_index_key(expiry: Expiry, hash: &Hash) -> Vec<u8> {
340	let mut key = Vec::with_capacity(size_of::<u64>() + hash.len());
341	key.extend_from_slice(&expiry.0.to_be_bytes());
342	key.extend_from_slice(&hash[..]);
343	key
344}
345
346/// Reverses the shared `u64_be ‖ hash` layout of [`expiry_index_key`] and [`evicted_index_key`];
347/// `None` if `key` does not have that layout.
348fn parse_time_index_key(key: &[u8]) -> Option<(u64, Hash)> {
349	if key.len() != size_of::<u64>() + size_of::<Hash>() {
350		log::error!(target: LOG_TARGET, "Corrupt time index key: {:?}", HexDisplay::from(&key));
351		return None;
352	}
353	let (time, hash) = key.split_at(size_of::<u64>());
354	Some((u64::from_be_bytes(time.try_into().ok()?), hash.try_into().ok()?))
355}
356
357/// Per-statement details tracked inside a per-account record; also the (SCALE-encoded) value of
358/// the statement's [`col::INDEX_BY_ACCOUNT`] row.
359#[derive(Clone, Copy, PartialEq, Eq, Debug)]
360struct EntryDetails {
361	channel: Option<Channel>,
362	data_len: usize,
363	admission_seq: u64,
364	/// The track the statement counts toward, set at admission and moved by the sweep.
365	track: RetentionTrack,
366}
367
368impl Encode for EntryDetails {
369	fn size_hint(&self) -> usize {
370		self.channel.size_hint() +
371			(self.data_len as u32).size_hint() +
372			self.admission_seq.size_hint() +
373			self.track.size_hint()
374	}
375
376	fn encode_to<T: codec::Output + ?Sized>(&self, dest: &mut T) {
377		self.channel.encode_to(dest);
378		(self.data_len as u32).encode_to(dest);
379		self.admission_seq.encode_to(dest);
380		self.track.encode_to(dest);
381	}
382}
383
384impl Decode for EntryDetails {
385	fn decode<I: codec::Input>(input: &mut I) -> std::result::Result<Self, codec::Error> {
386		let (channel, data_len, admission_seq, track) =
387			<(Option<Channel>, u32, u64, RetentionTrack)>::decode(input)?;
388		Ok(EntryDetails { channel, data_len: data_len as usize, admission_seq, track })
389	}
390}
391
392/// Number of stored statements and their data size per retention track, indexed by the track's
393/// discriminant.
394#[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Encode, Decode)]
395struct StoreTotals {
396	count: u64,
397	sizes: [u64; RetentionTrack::COUNT],
398}
399
400impl StoreTotals {
401	fn add(&mut self, track: RetentionTrack, data_len: usize) {
402		self.count += 1;
403		self.sizes[track as usize] += data_len as u64;
404	}
405
406	fn sub(&mut self, track: RetentionTrack, data_len: usize) {
407		self.count = self.count.saturating_sub(1);
408		let size = &mut self.sizes[track as usize];
409		*size = size.saturating_sub(data_len as u64);
410	}
411
412	/// Removes a statement whose track is unknown: the bytes come off the unlimited track first
413	/// and off the others only for what it holds less, so the store size stays exact.
414	fn sub_unattributed(&mut self, data_len: usize) {
415		self.count = self.count.saturating_sub(1);
416		let mut left = data_len as u64;
417		for track in
418			[RetentionTrack::ExplicitOnly, RetentionTrack::Transient, RetentionTrack::Persistent]
419		{
420			let size = &mut self.sizes[track as usize];
421			let taken = left.min(*size);
422			*size -= taken;
423			left -= taken;
424		}
425	}
426
427	fn count(&self) -> usize {
428		self.count as usize
429	}
430
431	fn size(&self) -> usize {
432		self.sizes.iter().sum::<u64>() as usize
433	}
434
435	fn track_size(&self, track: RetentionTrack) -> usize {
436		self.sizes[track as usize] as usize
437	}
438}
439
440/// The two rows tying a statement into the per-account and expiry indexes; written on insert
441/// (`details` carries the account row's value) and deleted with `None`.
442fn account_index_ops(
443	account: &AccountId,
444	expiry: Expiry,
445	hash: &Hash,
446	details: Option<&EntryDetails>,
447) -> [(u8, Vec<u8>, Option<Vec<u8>>); 2] {
448	[
449		(
450			col::INDEX_BY_ACCOUNT,
451			account_index_key(account, expiry, hash),
452			details.map(EntryDetails::encode),
453		),
454		(
455			col::INDEX_BY_EXPIRY,
456			expiry_index_key(expiry, hash),
457			details.map(|_| INDEX_EMPTY_VALUE.to_vec()),
458		),
459	]
460}
461
462/// The account id immediately after `account` in the index ordering, or `None` when `account`
463/// is the maximum id.
464fn next_account_id(mut account: AccountId) -> Option<AccountId> {
465	for byte in account.iter_mut().rev() {
466		match byte.checked_add(1) {
467			Some(incremented) => {
468				*byte = incremented;
469				return Some(account);
470			},
471			None => *byte = 0,
472		}
473	}
474	None
475}
476
477/// Extracts the trailing hash from a composite index key, if it is long enough.
478fn hash_from_index_key(key: &[u8]) -> Option<Hash> {
479	let Some(prefix_len) = key.len().checked_sub(size_of::<Hash>()) else {
480		log::error!(target: LOG_TARGET, "Corrupt index key: {:?}", HexDisplay::from(&key));
481		return None;
482	};
483	key[prefix_len..].try_into().ok()
484}
485
486/// The prefix of a composite index key — everything before the trailing hash — if it is long
487/// enough.
488fn prefix_from_index_key(key: &[u8]) -> Option<&[u8]> {
489	let Some(prefix_len) = key.len().checked_sub(size_of::<Hash>()) else {
490		log::error!(target: LOG_TARGET, "Corrupt index key: {:?}", HexDisplay::from(&key));
491		return None;
492	};
493	Some(&key[..prefix_len])
494}
495
496/// Builds the index-column operations for a statement's topic and decryption-key entries. With
497/// `insert == true` the entries are written; otherwise they are deleted. Designed to be folded
498/// into the same atomic [`parity_db::Db::commit`] as the statement body.
499fn statement_index_ops(
500	hash: &Hash,
501	statement: &Statement,
502	insert: bool,
503) -> Vec<(u8, Vec<u8>, Option<Vec<u8>>)> {
504	let value = insert.then(|| INDEX_EMPTY_VALUE.to_vec());
505	let mut ops = Vec::new();
506	let mut nt = 0;
507	while let Some(topic) = statement.topic(nt) {
508		ops.push((col::INDEX_BY_TOPIC, topic_index_key(&topic, hash), value.clone()));
509		nt += 1;
510	}
511	let dec_key = statement.decryption_key();
512	ops.push((col::INDEX_BY_DEC_KEY, dec_key_index_key(&dec_key, hash), value));
513	ops
514}
515
516#[derive(Eq, PartialEq, Debug, Ord, PartialOrd, Clone, Copy)]
517struct Expiry(u64);
518
519impl Expiry {
520	/// Returns the expiration timestamp in seconds
521	fn get_expiration_timestamp_secs(self) -> u64 {
522		self.0 >> 32
523	}
524}
525
526#[derive(PartialEq, Eq, Clone, Copy)]
527struct PriorityKey {
528	hash: Hash,
529	expiry: Expiry,
530}
531
532impl PartialOrd for PriorityKey {
533	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
534		Some(self.cmp(other))
535	}
536}
537
538impl Ord for PriorityKey {
539	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
540		self.expiry.cmp(&other.expiry).then_with(|| self.hash.cmp(&other.hash))
541	}
542}
543
544#[derive(PartialEq, Eq)]
545struct ChannelEntry {
546	hash: Hash,
547	expiry: Expiry,
548}
549
550#[derive(Default)]
551struct StatementsForAccount {
552	// Statements ordered by priority.
553	by_priority: BTreeMap<PriorityKey, EntryDetails>,
554	// Channel to statement map. Only one statement per channel is allowed.
555	channels: HashMap<Channel, ChannelEntry>,
556	// Sum of all `Data` field sizes.
557	data_size: usize,
558}
559
560impl StatementsForAccount {
561	fn insert_entry(&mut self, hash: Hash, expiry: Expiry, details: EntryDetails) {
562		self.data_size += details.data_len;
563		if let Some(channel) = details.channel {
564			self.channels.insert(channel, ChannelEntry { hash, expiry });
565		}
566		self.by_priority.insert(PriorityKey { hash, expiry }, details);
567	}
568
569	fn remove_entry(&mut self, key: &PriorityKey) -> Option<EntryDetails> {
570		let details = self.by_priority.remove(key)?;
571		self.data_size -= details.data_len;
572		if let Some(channel) = details.channel {
573			self.channels.remove(&channel);
574		}
575		Some(details)
576	}
577}
578
579/// Default number of concurrent workers for statement validation.
580pub const DEFAULT_NETWORK_WORKERS: usize = 1;
581
582/// Default maximum statements per second per peer before rate limiting kicks in.
583pub use sc_network_statement::config::DEFAULT_STATEMENTS_PER_SECOND as DEFAULT_RATE_LIMIT;
584
585/// Default replication factor (K) for v2 DHT-affinity statement routing.
586pub use sc_network_statement::config::DEFAULT_REPLICATION_FACTOR;
587
588/// Default inbound slots for full peers on the v2 DHT statement path.
589pub use sc_network_statement::config::DEFAULT_IN_PEERS;
590
591/// Default gossip target for v2 DHT-affinity statement routing.
592pub use sc_network_statement::config::DEFAULT_GOSSIP_TARGET;
593
594/// Parameters of the v2 DHT statement path.
595pub use sc_network_statement::{AffinityTopicsFile, V2DhtConfig};
596
597/// Default and lowest accepted false-positive rate of the advertised topic-affinity bloom
598/// filter.
599pub use sc_network_statement::config::DEFAULT_BLOOM_FALSE_POS_RATE;
600
601/// Statement store and network handler configuration.
602#[derive(Debug, Clone)]
603pub struct Config {
604	/// Maximum statements allowed in the store. Once this limit is reached lower-priority
605	/// statements may be evicted.
606	pub max_total_statements: usize,
607	/// Maximum total data size allowed in the store. Once this limit is reached lower-priority
608	/// statements may be evicted.
609	pub max_total_size: usize,
610	/// Number of seconds for which removed statements won't be allowed to be added back in.
611	pub purge_after_sec: u64,
612	/// Number of concurrent workers for statement validation from the network.
613	pub network_workers: usize,
614	/// Maximum statements per second per peer before rate limiting kicks in.
615	pub rate_limit: u32,
616	/// Parameters of the v2 DHT statement path, `None` when the legacy flood path is in use.
617	pub v2dht: Option<V2DhtConfig>,
618}
619
620impl Config {
621	/// Validate the configuration, returning an error if any values are invalid.
622	pub fn validate(&self) -> Result<()> {
623		if self.max_total_statements == 0 {
624			return Err(Error::InvalidConfig(
625				"max_total_statements must be greater than zero".into(),
626			));
627		}
628		if self.max_total_size == 0 {
629			return Err(Error::InvalidConfig("max_total_size must be greater than zero".into()));
630		}
631		if self.network_workers == 0 {
632			return Err(Error::InvalidConfig("network_workers must be greater than zero".into()));
633		}
634		if self.v2dht.as_ref().is_some_and(|cfg| {
635			!(cfg.bloom_false_pos_rate >= DEFAULT_BLOOM_FALSE_POS_RATE &&
636				cfg.bloom_false_pos_rate < 1.0)
637		}) {
638			return Err(Error::InvalidConfig(format!(
639				"bloom_false_pos_rate must be at least {DEFAULT_BLOOM_FALSE_POS_RATE} and below 1"
640			)));
641		}
642		if self
643			.track_max_sizes()
644			.iter()
645			.flatten()
646			.any(|max_size| !(1..=self.max_total_size).contains(max_size))
647		{
648			return Err(Error::InvalidConfig(
649				"track size limits must be between one and max_total_size".into(),
650			));
651		}
652		Ok(())
653	}
654
655	/// The size limit of every retention track by discriminant, `None` where the store size is
656	/// the limit.
657	fn track_max_sizes(&self) -> [Option<usize>; RetentionTrack::COUNT] {
658		let mut max_sizes = [None; RetentionTrack::COUNT];
659		if let Some(cfg) = &self.v2dht {
660			max_sizes[RetentionTrack::Transient as usize] = cfg.transient_max_size;
661			max_sizes[RetentionTrack::Persistent as usize] = cfg.dht_affinity_max_size;
662		}
663		max_sizes
664	}
665
666	/// Warns about a track size limit above half of the store size: the other tracks may then
667	/// get less than their own limits promise.
668	fn warn_on_large_track_limits(&self) {
669		for track in [RetentionTrack::Persistent, RetentionTrack::Transient] {
670			let Some(max_size) = self.track_max_sizes()[track as usize] else { continue };
671			if max_size > self.max_total_size / 2 {
672				log::warn!(
673					target: LOG_TARGET,
674					"Size limit of the statements kept for {} ({} bytes) is above half of the store size ({} bytes)",
675					track.reason(),
676					max_size,
677					self.max_total_size,
678				);
679			}
680		}
681	}
682}
683
684impl Default for Config {
685	fn default() -> Self {
686		Config {
687			max_total_statements: DEFAULT_MAX_TOTAL_STATEMENTS,
688			max_total_size: DEFAULT_MAX_TOTAL_SIZE,
689			purge_after_sec: DEFAULT_PURGE_AFTER_SEC,
690			network_workers: DEFAULT_NETWORK_WORKERS,
691			rate_limit: DEFAULT_RATE_LIMIT,
692			v2dht: None,
693		}
694	}
695}
696
697/// In-memory part of the read index.
698struct QueryIndex {
699	// TODO: Remove counters; replace them with a merge-join/leapfrog1
700	topic_counts: HashMap<Topic, usize>,
701	dec_key_counts: HashMap<Option<DecryptionKey>, usize>,
702	recent: HashMap<Hash, u64>,
703	/// The track of every statement the maintenance sweep re-checks once it is propagated.
704	/// Persistent statements are not recorded.
705	retention_tracks: HashMap<Hash, RetentionTrack>,
706	/// Number of holds per hash, see [`StatementStore::hold_statements`]; the maintenance sweep
707	/// skips held statements. A removal keeps the count, as its holders release it even after a
708	/// re-admission.
709	held: HashMap<Hash, usize>,
710}
711
712#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode)]
713enum RetentionTrack {
714	/// No affinity covers the statement, it only passes through on its way to the replicas: kept
715	/// until propagated.
716	#[codec(index = 0)]
717	Transient,
718	/// Only explicit affinity covers the statement: it is dropped once that affinity lapses.
719	#[codec(index = 1)]
720	ExplicitOnly,
721	/// DHT affinity covers the statement, or nothing limits its retention.
722	#[codec(index = 2)]
723	Persistent,
724}
725
726impl From<RetentionReasonMask> for RetentionTrack {
727	fn from(mask: RetentionReasonMask) -> Self {
728		if !mask.is_persistent() {
729			RetentionTrack::Transient
730		} else if mask.contains(RetentionReasonMask::EXPLICIT_AFFINITY) &&
731			!mask.contains(RetentionReasonMask::DHT_AFFINITY)
732		{
733			RetentionTrack::ExplicitOnly
734		} else {
735			RetentionTrack::Persistent
736		}
737	}
738}
739
740impl RetentionTrack {
741	/// Number of variants, persisted in the counters row and the account index along with the
742	/// discriminants, so a change of count or order needs a database version bump.
743	const COUNT: usize = 3;
744
745	fn is_persistent(&self) -> bool {
746		matches!(self, RetentionTrack::Persistent)
747	}
748
749	/// Name of the track, used as the `track` label in metrics.
750	fn label(&self) -> &'static str {
751		match self {
752			RetentionTrack::Transient => "transient",
753			RetentionTrack::ExplicitOnly => "explicit",
754			RetentionTrack::Persistent => "persistent",
755		}
756	}
757
758	/// The reason the track's statements are kept for, as named in logs.
759	fn reason(&self) -> &'static str {
760		match self {
761			RetentionTrack::Transient => "propagation",
762			RetentionTrack::ExplicitOnly => "explicit affinity",
763			RetentionTrack::Persistent => "DHT affinity",
764		}
765	}
766}
767
768impl QueryIndex {
769	fn new() -> Self {
770		QueryIndex {
771			topic_counts: HashMap::new(),
772			dec_key_counts: HashMap::new(),
773			recent: HashMap::new(),
774			retention_tracks: HashMap::new(),
775			held: HashMap::new(),
776		}
777	}
778
779	/// Records a newly inserted statement: bumps cardinalities and marks the hash as recent
780	/// under its admission sequence number.
781	fn note_insert(&mut self, hash: Hash, statement: &Statement, seq: u64, track: RetentionTrack) {
782		let mut nt = 0;
783		while let Some(topic) = statement.topic(nt) {
784			*self.topic_counts.entry(topic).or_insert(0) += 1;
785			nt += 1;
786		}
787		let dec_key = statement.decryption_key();
788		*self.dec_key_counts.entry(dec_key).or_insert(0) += 1;
789		self.recent.insert(hash, seq);
790		if !track.is_persistent() {
791			self.retention_tracks.insert(hash, track);
792		}
793	}
794
795	/// Records a removed statement: decrements cardinalities and drops the hash from `recent`.
796	fn note_remove(&mut self, hash: &Hash, statement: &Statement) {
797		let mut nt = 0;
798		while let Some(topic) = statement.topic(nt) {
799			if let Some(count) = self.topic_counts.get_mut(&topic) {
800				*count = count.saturating_sub(1);
801				if *count == 0 {
802					self.topic_counts.remove(&topic);
803				}
804			}
805			nt += 1;
806		}
807		let dec_key = statement.decryption_key();
808		if let Some(count) = self.dec_key_counts.get_mut(&dec_key) {
809			*count = count.saturating_sub(1);
810			if *count == 0 {
811				self.dec_key_counts.remove(&dec_key);
812			}
813		}
814		self.recent.remove(hash);
815		self.retention_tracks.remove(hash);
816	}
817
818	/// The track of an already propagated statement, which the retention sweep re-checks.
819	fn propagated_track(&self, hash: &Hash) -> Option<RetentionTrack> {
820		if self.recent.contains_key(hash) || self.held.contains_key(hash) {
821			return None;
822		}
823		self.retention_tracks.get(hash).copied()
824	}
825
826	fn hold<'a>(&mut self, hashes: impl IntoIterator<Item = &'a Hash>) {
827		for hash in hashes {
828			*self.held.entry(*hash).or_insert(0) += 1;
829		}
830	}
831
832	fn release(&mut self, hashes: &[Hash]) {
833		for hash in hashes {
834			if let Some(count) = self.held.get_mut(hash) {
835				*count = count.saturating_sub(1);
836				if *count == 0 {
837					self.held.remove(hash);
838				}
839			}
840		}
841	}
842
843	/// Copies the set of recently added hashes with their admission sequence numbers.
844	fn recent_snapshot(&self) -> HashMap<Hash, u64> {
845		self.recent.clone()
846	}
847
848	/// Drops the propagated hashes from `recent`, keeping those re-admitted under a newer
849	/// sequence number since the snapshot was taken.
850	fn clear_propagated(&mut self, propagated: &HashMap<Hash, u64>) {
851		self.recent.retain(|hash, seq| propagated.get(hash) != Some(seq));
852	}
853
854	fn forget_retention_tracking<'a>(&mut self, keys: impl IntoIterator<Item = &'a PriorityKey>) {
855		for key in keys {
856			self.retention_tracks.remove(&key.hash);
857		}
858	}
859}
860
861/// Statement count and total data size of one account.
862#[derive(Clone, Copy)]
863struct AccountSummary {
864	count: usize,
865	data_size: usize,
866}
867
868/// In-memory part of the submit index (constraint checking, quota enforcement).
869///
870/// The authoritative per-statement data lives on disk in [`col::INDEX_BY_ACCOUNT`] /
871/// [`col::INDEX_BY_EXPIRY`]; this structure holds bounded write-through caches over it plus the
872/// global counters.
873struct SubmitIndex {
874	/// Cached per-account detail records. Bounded by [`Self::cached_statement_count`]
875	/// against [`DETAILS_CACHE_BUDGET`].
876	account_statements: LruMap<AccountId, StatementsForAccount>,
877	/// Total number of statements across all cached records in [`Self::account_statements`].
878	cached_statement_count: usize,
879	/// Cached per-account count/size summaries. Cheap enough to cover many more accounts than
880	/// the details cache; lets `submit` skip loading the full record for channel-less statements
881	/// well within their quota, and lets `enforce_limits` skip accounts within their allowance.
882	summaries: LruMap<AccountId, AccountSummary>,
883	/// Resume point of the incremental per-account allowance sweep in `enforce_limits`: the
884	/// account id to continue the scan from, or `None` when a new pass starts from the beginning.
885	allowance_cursor: Option<AccountId>,
886	/// Number of accounts already seen by the current allowance sweep pass.
887	allowance_cycle_seen: usize,
888	/// Store configuration (global limits, purge period).
889	config: Config,
890	/// Number of stored statements and their data size per retention track.
891	totals: StoreTotals,
892	evicted_count: usize,
893	// Monotonic sequence number assigned to each statement as it is inserted. Written only by
894	// `set_next_seq`, which keeps `admission_watermark` equal to it.
895	next_seq: u64,
896	// Same counter as `Store::admission_watermark`: `set_next_seq` writes it here, the store reads
897	// it without the lock.
898	admission_watermark: Arc<AtomicU64>,
899	// Sequence numbers of recently inserted statements, kept only while at least one subscription
900	// snapshot scan is in progress and only back to the oldest such scan's watermark.
901	recent_seqs: HashMap<Hash, u64>,
902	// Watermarks of the currently running snapshot scans.
903	active_scan_floors: BTreeMap<u64, usize>,
904}
905
906struct ClientWrapper<Block, Client, BE> {
907	client: Arc<Client>,
908	_block: std::marker::PhantomData<Block>,
909	_backend: std::marker::PhantomData<BE>,
910}
911
912impl<Block, Client, BE> ClientWrapper<Block, Client, BE>
913where
914	Block: BlockT,
915	Block::Hash: From<BlockHash>,
916	BE: Backend<Block> + 'static,
917	Client: HeaderBackend<Block> + StorageProvider<Block, BE> + Send + Sync + 'static,
918{
919	fn read_allowance(
920		&self,
921		account_id: &AccountId,
922		allowance_block: AllowanceBlock,
923	) -> Result<Option<StatementAllowance>> {
924		use sp_statement_store::{statement_allowance_key, StatementAllowance};
925
926		let block_hash = match allowance_block {
927			AllowanceBlock::Best => self.client.info().best_hash,
928			AllowanceBlock::Finalized => self.client.info().finalized_hash,
929		};
930		let key = statement_allowance_key(account_id);
931		let storage_key = StorageKey(key);
932		self.client
933			.storage(block_hash, &storage_key)
934			.map_err(|e| Error::Storage(format!("Failed to read allowance: {:?}", e)))?
935			.map(|value| {
936				StatementAllowance::decode(&mut &value.0[..])
937					.map_err(|e| Error::Decode(format!("Failed to decode allowance: {:?}", e)))
938			})
939			.transpose()
940	}
941}
942
943/// Statement store.
944pub struct Store {
945	db: parity_db::Db,
946	submit_index: RwLock<SubmitIndex>,
947	query_index: RwLock<QueryIndex>,
948	read_allowance_fn:
949		Box<dyn Fn(&AccountId, AllowanceBlock) -> Result<Option<StatementAllowance>> + Send + Sync>,
950	/// Derives the retention mask for each submitted statement.
951	/// By default every submission is persisted unconditionally.
952	retention_fn: std::sync::OnceLock<Box<dyn Fn(&Statement) -> RetentionReasonMask + Send + Sync>>,
953	subscription_manager: SubscriptionsHandle,
954	keystore: Arc<LocalKeystore>,
955	/// Number of accounts with stored statements. Reported by `maintain`; may lag the
956	/// exact value by up to one sweep cycle.
957	known_accounts_count: AtomicUsize,
958	/// Shared with `SubmitIndex`, which keeps it equal to its `next_seq`, so the gossip loop reads
959	/// the watermark without waiting for a writer stalled on the disk.
960	admission_watermark: Arc<AtomicU64>,
961	// Used for testing
962	time_override: Option<u64>,
963	metrics: PrometheusMetrics,
964}
965
966impl ReplaySnapshotProvider for Weak<Store> {
967	fn register_replay(&self, enqueue: &mut dyn FnMut(u64) -> bool) -> Result<Option<u64>> {
968		let Some(store) = self.upgrade() else {
969			return Err(Error::InvalidConfig("statement store is closed".into()));
970		};
971		store.register_replay(enqueue)
972	}
973
974	fn replay_batch(
975		&self,
976		filter: &OptimizedTopicFilter,
977		cursor: u64,
978		watermark: u64,
979	) -> Result<ReplayBatch> {
980		let Some(store) = self.upgrade() else {
981			return Err(Error::InvalidConfig("statement store is closed".into()));
982		};
983		store.replay_batch(filter, cursor, watermark)
984	}
985}
986
987/// What admitting a new statement will claim and evict, as decided by
988/// [`SubmitIndex::plan_insert`].
989struct InsertPlan {
990	/// Admission sequence the new statement will claim.
991	seq: u64,
992	/// The account's own statements that must be evicted to make room. Their bodies and on-disk
993	/// index rows must be deleted.
994	evicted: Vec<(PriorityKey, EntryDetails)>,
995	/// The subset of `evicted` that is banned from re-acceptance, with its purge deadline. These
996	/// must be recorded in the on-disk evicted journal.
997	banned: Vec<(Hash, u64)>,
998	/// The store totals once the statement is in and `evicted` is out.
999	totals: StoreTotals,
1000}
1001
1002enum Resubmission {
1003	Banned,
1004	Allowed,
1005}
1006
1007impl Resubmission {
1008	fn is_banned(&self) -> bool {
1009		matches!(self, Resubmission::Banned)
1010	}
1011}
1012
1013/// A single on-disk index set referenced during a query: either the set of hashes carrying a
1014/// topic, or the set of hashes for a decryption key.
1015#[derive(Clone)]
1016enum IndexSet {
1017	Topic(Topic),
1018	DecKey(Option<DecryptionKey>),
1019}
1020
1021impl IndexSet {
1022	fn column(&self) -> u8 {
1023		match self {
1024			IndexSet::Topic(_) => col::INDEX_BY_TOPIC,
1025			IndexSet::DecKey(_) => col::INDEX_BY_DEC_KEY,
1026		}
1027	}
1028
1029	/// Prefix selecting every entry of this set within its column.
1030	fn prefix(&self) -> Vec<u8> {
1031		match self {
1032			IndexSet::Topic(t) => t[..].to_vec(),
1033			IndexSet::DecKey(k) => dec_key_index_prefix(k),
1034		}
1035	}
1036
1037	/// Full key of `hash` within this set's column, for point membership lookups.
1038	fn member_key(&self, hash: &Hash) -> Vec<u8> {
1039		match self {
1040			IndexSet::Topic(t) => topic_index_key(t, hash),
1041			IndexSet::DecKey(k) => dec_key_index_key(k, hash),
1042		}
1043	}
1044
1045	/// Cardinality of this set, read from the in-memory cardinality counters.
1046	fn len(&self, read_index: &QueryIndex) -> usize {
1047		match self {
1048			IndexSet::Topic(t) => read_index.topic_counts.get(t).copied().unwrap_or(0),
1049			IndexSet::DecKey(k) => read_index.dec_key_counts.get(k).copied().unwrap_or(0),
1050		}
1051	}
1052}
1053
1054impl SubmitIndex {
1055	fn new(config: Config, admission_watermark: Arc<AtomicU64>) -> SubmitIndex {
1056		SubmitIndex {
1057			// The real bound is [`Self::cached_statement_count`], enforced by
1058			// [`Self::cache_record`]; this length limiter must never trigger on its own, and
1059			// cannot: every record costs at least one unit, so the cost trimming keeps the
1060			// length at or below the budget.
1061			account_statements: LruMap::new(ByLength::new(u32::MAX)),
1062			summaries: LruMap::new(ByLength::new(SUMMARY_CACHE_ACCOUNTS)),
1063			config,
1064			totals: StoreTotals::default(),
1065			next_seq: 0,
1066			admission_watermark,
1067			cached_statement_count: 0,
1068			allowance_cursor: None,
1069			allowance_cycle_seen: 0,
1070			evicted_count: 0,
1071			recent_seqs: HashMap::new(),
1072			active_scan_floors: BTreeMap::new(),
1073		}
1074	}
1075
1076	fn set_next_seq(&mut self, next_seq: u64) {
1077		self.next_seq = next_seq;
1078		self.admission_watermark.store(next_seq, AtomicOrdering::Release);
1079	}
1080
1081	/// The [`KEY_COUNTERS`] row reflecting the given post-commit totals. Folded into every
1082	/// mutating commit.
1083	fn counters_op(totals: &StoreTotals, next_seq: u64) -> (u8, Vec<u8>, Option<Vec<u8>>) {
1084		(col::META, KEY_COUNTERS.to_vec(), Some((totals, next_seq).encode()))
1085	}
1086
1087	fn statement_count(&self) -> usize {
1088		self.totals.count()
1089	}
1090
1091	fn total_size(&self) -> usize {
1092		self.totals.size()
1093	}
1094
1095	/// The limit an admission leaving `totals` under `track` would break: the track's own size
1096	/// limit, or else the store's. A rejection for the store while the track has a limit means
1097	/// the track had room the store did not.
1098	fn exceeded_limit(
1099		&self,
1100		totals: &StoreTotals,
1101		track: RetentionTrack,
1102	) -> Option<RejectionReason> {
1103		let track_max_size = self.config.track_max_sizes()[track as usize];
1104		if track_max_size.is_some_and(|max_size| totals.track_size(track) > max_size) {
1105			Some(RejectionReason::TrackFull)
1106		} else if totals.count() > self.config.max_total_statements ||
1107			totals.size() > self.config.max_total_size
1108		{
1109			Some(RejectionReason::StoreFull)
1110		} else {
1111			None
1112		}
1113	}
1114
1115	/// Removes the account's record from the details cache, keeping the cost accounting exact.
1116	fn uncache_record(&mut self, account: &AccountId) -> Option<StatementsForAccount> {
1117		let record = self.account_statements.remove(account)?;
1118		self.cached_statement_count -= record.by_priority.len();
1119		Some(record)
1120	}
1121
1122	/// Puts a record (back) into the details cache, then evicts the least-recently-used records
1123	/// while the total number of cached statements exceeds the budget. A single record larger
1124	/// than the whole budget is kept: the cache never trims below one entry.
1125	fn cache_record(&mut self, account: AccountId, record: StatementsForAccount) {
1126		if record.by_priority.is_empty() {
1127			return;
1128		}
1129		self.cached_statement_count += record.by_priority.len();
1130		self.account_statements.insert(account, record);
1131		while self.cached_statement_count > DETAILS_CACHE_BUDGET &&
1132			self.account_statements.len() > 1
1133		{
1134			match self.account_statements.pop_oldest() {
1135				Some((_, evicted)) => self.cached_statement_count -= evicted.by_priority.len(),
1136				None => break,
1137			}
1138		}
1139	}
1140
1141	/// Puts a record into the details cache together with the summary derived from it. An
1142	/// account with no statements is represented in both caches by absence, so an empty record
1143	/// refreshes neither.
1144	fn cache_record_with_summary(&mut self, account: AccountId, record: StatementsForAccount) {
1145		if !record.by_priority.is_empty() {
1146			self.summaries.insert(
1147				account,
1148				AccountSummary { count: record.by_priority.len(), data_size: record.data_size },
1149			);
1150		}
1151		self.cache_record(account, record);
1152	}
1153
1154	/// Records a sequence number in the snapshot window, once its statement and admission entries
1155	/// have committed atomically. The number itself is claimed earlier, by [`Self::insert`].
1156	fn note_seq(&mut self, hash: Hash, seq: u64) {
1157		if !self.active_scan_floors.is_empty() {
1158			self.recent_seqs.insert(hash, seq);
1159		}
1160	}
1161
1162	/// Registers a subscription snapshot scan and returns its watermark.
1163	fn begin_scan(&mut self) -> u64 {
1164		let watermark = self.next_seq;
1165		*self.active_scan_floors.entry(watermark).or_insert(0) += 1;
1166		watermark
1167	}
1168
1169	/// Deregisters a snapshot scan previously registered with [`Self::begin_scan`] and prunes
1170	/// `recent_seqs` down to the smallest still-active watermark.
1171	fn end_scan(&mut self, watermark: u64) {
1172		if let Some(count) = self.active_scan_floors.get_mut(&watermark) {
1173			*count -= 1;
1174			if *count == 0 {
1175				self.active_scan_floors.remove(&watermark);
1176			}
1177		}
1178		match self.active_scan_floors.keys().next() {
1179			Some(&floor) => self.recent_seqs.retain(|_, seq| *seq >= floor),
1180			None => self.recent_seqs.clear(),
1181		}
1182	}
1183
1184	/// Whether the statement `hash` belongs in the snapshot of a scan with the given `watermark`.
1185	fn seq_covered_by_snapshot(&self, hash: &Hash, watermark: u64) -> bool {
1186		match self.recent_seqs.get(hash) {
1187			Some(&seq) => seq < watermark,
1188			None => true,
1189		}
1190	}
1191
1192	/// Pure constraint check for admitting `statement`: decides, without mutating anything, which
1193	/// of the account's own statements must be evicted to make room, or why the statement cannot
1194	/// be admitted. `record` is the account's current state; global and per-track limits are
1195	/// checked against the in-memory counters. The store never evicts other accounts' statements
1196	/// to admit a new one — when the limits cannot be met from this account alone, the statement
1197	/// is rejected.
1198	fn plan_insert(
1199		&self,
1200		record: &StatementsForAccount,
1201		hash: Hash,
1202		statement: &Statement,
1203		track: RetentionTrack,
1204		account: &AccountId,
1205		validation: &StatementAllowance,
1206		current_time: u64,
1207	) -> std::result::Result<InsertPlan, RejectionReason> {
1208		let statement_len = statement.data_len();
1209		if statement_len > validation.max_size as usize {
1210			log::debug!(
1211				target: LOG_TARGET,
1212				"Ignored oversize message from account {}: {:?} ({} bytes)",
1213				HexDisplay::from(account),
1214				HexDisplay::from(&hash),
1215				statement_len,
1216			);
1217			return Err(RejectionReason::DataTooLarge {
1218				submitted_size: statement_len,
1219				available_size: validation.max_size as usize,
1220			});
1221		}
1222
1223		let mut evicted: Vec<(PriorityKey, EntryDetails)> = Vec::new();
1224		let mut evicted_hashes = HashSet::new();
1225		let mut would_free_size = 0;
1226		let expiry = Expiry(statement.expiry());
1227		let (max_size, max_count) = (validation.max_size as usize, validation.max_count as usize);
1228		// It may happen that we can't delete enough lower priority messages
1229		// to satisfy size constraints. We check for that before deleting anything,
1230		// taking into account channel message replacement.
1231		if let Some(channel) = statement.channel() {
1232			if let Some(channel_record) = record.channels.get(&channel) {
1233				if expiry <= channel_record.expiry {
1234					// Trying to replace channel message with lower expiry.
1235					log::debug!(
1236						target: LOG_TARGET,
1237						"Ignored lower priority channel message from account {}: {:?} {:?} <= {:?}",
1238						HexDisplay::from(account),
1239						HexDisplay::from(&hash),
1240						expiry,
1241						channel_record.expiry,
1242					);
1243					return Err(RejectionReason::ChannelPriorityTooLow {
1244						submitted_expiry: expiry.0,
1245						min_expiry: channel_record.expiry.0,
1246					});
1247				} else {
1248					// Would replace channel message. Still need to check for size constraints
1249					// below.
1250					log::debug!(
1251						target: LOG_TARGET,
1252						"Replacing higher priority channel message from account {}: {:?} ({:?}) > {:?} ({:?})",
1253						HexDisplay::from(account),
1254						HexDisplay::from(&hash),
1255						expiry,
1256						HexDisplay::from(&channel_record.hash),
1257						channel_record.expiry,
1258					);
1259					let key =
1260						PriorityKey { hash: channel_record.hash, expiry: channel_record.expiry };
1261					if let Some(details) = record.by_priority.get(&key) {
1262						would_free_size += details.data_len;
1263						evicted_hashes.insert(key.hash);
1264						evicted.push((key, *details));
1265					}
1266				}
1267			}
1268		}
1269		// Check if we can evict enough lower priority statements to satisfy constraints
1270		for (entry, details) in record.by_priority.iter() {
1271			if (record.data_size - would_free_size + statement_len <= max_size) &&
1272				record.by_priority.len() + 1 - evicted_hashes.len() <= max_count
1273			{
1274				// Satisfied
1275				break;
1276			}
1277			if evicted_hashes.contains(&entry.hash) {
1278				// Already accounted for above
1279				continue;
1280			}
1281			if entry.expiry >= expiry {
1282				log::debug!(
1283					target: LOG_TARGET,
1284					"Ignored message from account {} due to constraints {:?} {:?} < {:?}",
1285					HexDisplay::from(account),
1286					HexDisplay::from(&hash),
1287					expiry,
1288					entry.expiry,
1289				);
1290				let retained_size = record.data_size - would_free_size;
1291				if retained_size + statement_len > max_size {
1292					return Err(RejectionReason::DataTooLarge {
1293						submitted_size: statement_len,
1294						available_size: max_size.saturating_sub(retained_size),
1295					});
1296				}
1297				return Err(RejectionReason::AccountFull {
1298					submitted_expiry: expiry.0,
1299					min_expiry: entry.expiry.0,
1300				});
1301			}
1302			evicted_hashes.insert(entry.hash);
1303			would_free_size += details.data_len;
1304			evicted.push((*entry, *details));
1305		}
1306		// Now check the global and the track's constraints as well.
1307		let totals = self.totals_after_insert(
1308			track,
1309			statement_len,
1310			evicted.iter().map(|(_, details)| details),
1311		);
1312		if let Some(reason) = self.exceeded_limit(&totals, track) {
1313			log::debug!(
1314				target: LOG_TARGET,
1315				"Ignored statement {} from account {}: {} (size={}, count={}, track={:?})",
1316				HexDisplay::from(&hash),
1317				HexDisplay::from(account),
1318				reason.label(),
1319				self.total_size(),
1320				self.statement_count(),
1321				track,
1322			);
1323			return Err(reason);
1324		}
1325
1326		let banned = evicted
1327			.iter()
1328			.filter_map(|(key, _)| {
1329				let expiry_ts = key.expiry.get_expiration_timestamp_secs();
1330				(current_time < expiry_ts).then(|| {
1331					(
1332						key.hash,
1333						expiry_ts.min(current_time.saturating_add(self.config.purge_after_sec)),
1334					)
1335				})
1336			})
1337			.collect();
1338		Ok(InsertPlan { seq: self.next_seq, evicted, banned, totals })
1339	}
1340
1341	fn totals_after_insert<'a>(
1342		&self,
1343		track: RetentionTrack,
1344		data_len: usize,
1345		evicted: impl IntoIterator<Item = &'a EntryDetails>,
1346	) -> StoreTotals {
1347		let mut totals = self.totals_after_removal(evicted);
1348		totals.add(track, data_len);
1349		totals
1350	}
1351
1352	fn totals_after_removal<'a>(
1353		&self,
1354		removed: impl IntoIterator<Item = &'a EntryDetails>,
1355	) -> StoreTotals {
1356		let mut totals = self.totals;
1357		for details in removed {
1358			totals.sub(details.track, details.data_len);
1359		}
1360		totals
1361	}
1362
1363	/// Applies a committed insertion to the caches and counters. `loaded_record` carries the
1364	/// account's record when planning had to load it from disk; with `None` the cached copy (if
1365	/// any) is updated in place, which also covers the summary fast path where no record was
1366	/// materialised at all.
1367	fn apply_insert(
1368		&mut self,
1369		account: &AccountId,
1370		loaded_record: Option<StatementsForAccount>,
1371		hash: Hash,
1372		statement: &Statement,
1373		track: RetentionTrack,
1374		plan: &InsertPlan,
1375	) {
1376		let statement_len = statement.data_len();
1377		self.totals = plan.totals;
1378		self.evicted_count += plan.banned.len();
1379		self.set_next_seq(plan.seq.saturating_add(1));
1380		self.note_seq(hash, plan.seq);
1381		for (key, _) in &plan.evicted {
1382			log::trace!(target: LOG_TARGET, "Expired statement {:?}", HexDisplay::from(&key.hash));
1383		}
1384		let details = EntryDetails {
1385			channel: statement.channel(),
1386			data_len: statement_len,
1387			admission_seq: plan.seq,
1388			track,
1389		};
1390		match loaded_record.or_else(|| self.uncache_record(account)) {
1391			Some(mut record) => {
1392				for (key, _) in &plan.evicted {
1393					record.remove_entry(key);
1394				}
1395				record.insert_entry(hash, Expiry(statement.expiry()), details);
1396				self.cache_record_with_summary(*account, record);
1397			},
1398			None => {
1399				// Summary fast path: no record was materialised, only the summary is maintained.
1400				assert!(plan.evicted.is_empty());
1401				if let Some(summary) = self.summaries.get(account) {
1402					summary.count += 1;
1403					summary.data_size += statement_len;
1404				}
1405			},
1406		}
1407	}
1408
1409	/// Applies the committed removal of one statement to the caches and counters.
1410	fn apply_removal(
1411		&mut self,
1412		account: &AccountId,
1413		key: &PriorityKey,
1414		totals: StoreTotals,
1415		data_len: usize,
1416		banned: bool,
1417	) {
1418		self.totals = totals;
1419		if banned {
1420			self.evicted_count += 1;
1421		}
1422		if let Some(record) = self.account_statements.peek_mut(account) {
1423			if record.remove_entry(key).is_some() {
1424				self.cached_statement_count -= 1;
1425			}
1426			if record.by_priority.is_empty() {
1427				self.account_statements.remove(account);
1428			}
1429		}
1430		if let Some(summary) = self.summaries.peek_mut(account) {
1431			summary.count = summary.count.saturating_sub(1);
1432			summary.data_size = summary.data_size.saturating_sub(data_len);
1433			if summary.count == 0 {
1434				self.summaries.remove(account);
1435			}
1436		}
1437	}
1438
1439	/// Applies a committed track change to the counters and the cached record.
1440	fn apply_retrack(
1441		&mut self,
1442		account: &AccountId,
1443		key: &PriorityKey,
1444		from: RetentionTrack,
1445		to: RetentionTrack,
1446		data_len: usize,
1447	) {
1448		self.totals.sub(from, data_len);
1449		self.totals.add(to, data_len);
1450		if let Some(cached) = self
1451			.account_statements
1452			.peek_mut(account)
1453			.and_then(|record| record.by_priority.get_mut(key))
1454		{
1455			cached.track = to;
1456		}
1457	}
1458
1459	/// Applies the committed removal of an account's every statement to the caches and counters.
1460	fn apply_account_removal(
1461		&mut self,
1462		account: &AccountId,
1463		totals: StoreTotals,
1464		banned_count: usize,
1465	) {
1466		self.totals = totals;
1467		self.evicted_count += banned_count;
1468		if let Some(record) = self.account_statements.remove(account) {
1469			self.cached_statement_count -= record.by_priority.len();
1470		}
1471		self.summaries.remove(account);
1472	}
1473}
1474
1475impl Store {
1476	/// Create a new shared store instance. There should only be one per process.
1477	/// `path` will be used to open a statement database or create a new one if it does not exist.
1478	pub fn new_shared<Block, Client, BE>(
1479		path: &std::path::Path,
1480		config: Config,
1481		client: Arc<Client>,
1482		keystore: Arc<LocalKeystore>,
1483		prometheus: Option<&PrometheusRegistry>,
1484		task_spawner: Box<dyn SpawnNamed>,
1485	) -> Result<Arc<Store>>
1486	where
1487		Block: BlockT,
1488		Block::Hash: From<BlockHash>,
1489		BE: Backend<Block> + 'static,
1490		Client: HeaderBackend<Block> + StorageProvider<Block, BE> + Send + Sync + 'static,
1491	{
1492		let store =
1493			Arc::new(Self::new(path, config, client, keystore, prometheus, task_spawner.clone())?);
1494
1495		// Perform periodic statement store maintenance
1496		let worker_store = store.clone();
1497		task_spawner.spawn_blocking(
1498			"statement-store-maintenance",
1499			Some("statement-store"),
1500			Box::pin(async move {
1501				let mut maintenance_interval = tokio::time::interval(MAINTENANCE_PERIOD);
1502				let mut enforce_limits_interval = tokio::time::interval(ENFORCE_LIMITS_PERIOD);
1503				loop {
1504					futures::select! {
1505						_ = maintenance_interval.tick().fuse() => {worker_store.maintain();}
1506						_ = enforce_limits_interval.tick().fuse() => {
1507							if worker_store.enforce_limits() {
1508								enforce_limits_interval.reset_after(ENFORCE_LIMITS_BACKLOG_PERIOD);
1509							}
1510						}
1511					}
1512				}
1513			}),
1514		);
1515
1516		Ok(store)
1517	}
1518
1519	/// Create a new instance.
1520	/// `path` will be used to open a statement database or create a new one if it does not exist.
1521	#[doc(hidden)]
1522	pub fn new<Block, Client, BE>(
1523		path: &std::path::Path,
1524		config: Config,
1525		client: Arc<Client>,
1526		keystore: Arc<LocalKeystore>,
1527		prometheus: Option<&PrometheusRegistry>,
1528		task_spawner: Box<dyn SpawnNamed>,
1529	) -> Result<Store>
1530	where
1531		Block: BlockT,
1532		Block::Hash: From<BlockHash>,
1533		BE: Backend<Block> + 'static,
1534		Client: HeaderBackend<Block> + StorageProvider<Block, BE> + Send + Sync + 'static,
1535	{
1536		config.validate()?;
1537		config.warn_on_large_track_limits();
1538
1539		let mut path: std::path::PathBuf = path.into();
1540		path.push("statements");
1541
1542		Self::migrate_columns(&path)?;
1543		let db = Self::open_db(&path)?;
1544		let migrate_from = Self::check_db_version(&db)?;
1545
1546		let storage_reader =
1547			ClientWrapper { client, _block: Default::default(), _backend: Default::default() };
1548		let read_allowance_fn =
1549			Box::new(move |account_id: &AccountId, allowance_block: AllowanceBlock| {
1550				storage_reader.read_allowance(account_id, allowance_block)
1551			});
1552
1553		let admission_watermark = Arc::new(AtomicU64::new(0));
1554		let store = Store {
1555			db,
1556			submit_index: RwLock::new(SubmitIndex::new(config, admission_watermark.clone())),
1557			query_index: RwLock::new(QueryIndex::new()),
1558			read_allowance_fn,
1559			retention_fn: std::sync::OnceLock::new(),
1560			keystore,
1561			known_accounts_count: AtomicUsize::new(0),
1562			admission_watermark,
1563			time_override: None,
1564			metrics: PrometheusMetrics::new(prometheus),
1565			subscription_manager: SubscriptionsHandle::new(
1566				task_spawner.clone(),
1567				NUM_FILTER_WORKERS,
1568			),
1569		};
1570		store.populate(migrate_from)?;
1571		Ok(store)
1572	}
1573
1574	/// Install the resolver that derives the retention mask for each submitted statement.
1575	///
1576	/// Without it, the store persists every submission. Installation is first-wins: the resolver is
1577	/// wired once at node startup, so a second install means a wiring bug and is rejected loudly.
1578	pub fn set_retention_resolver(
1579		&self,
1580		resolver: Box<dyn Fn(&Statement) -> RetentionReasonMask + Send + Sync>,
1581	) {
1582		if self.retention_fn.set(resolver).is_err() {
1583			log::error!(
1584				target: LOG_TARGET,
1585				"retention resolver already installed; ignoring the second install (wiring bug)",
1586			);
1587		}
1588	}
1589
1590	/// Migrate the column layout of an existing database to the current schema.
1591	fn migrate_columns(path: &std::path::Path) -> Result<()> {
1592		let Some(metadata) =
1593			parity_db::Options::load_metadata(path).map_err(|e| Error::Db(e.to_string()))?
1594		else {
1595			return Ok(());
1596		};
1597		if metadata.columns.len() >= col::COUNT as usize {
1598			return Ok(());
1599		}
1600		let mut migrate_config = parity_db::Options::with_columns(path, 0);
1601		migrate_config.columns = metadata.columns;
1602		while migrate_config.columns.len() < col::COUNT as usize {
1603			// `add_column` takes the options by value, so build a fresh one each iteration.
1604			let mut new_column_options = parity_db::ColumnOptions::default();
1605			let column = migrate_config.columns.len() as u8;
1606			new_column_options.btree_index = BTREE_COLUMNS.contains(&column);
1607			parity_db::Db::add_column(&mut migrate_config, new_column_options)
1608				.map_err(|e| Error::Db(e.to_string()))?;
1609		}
1610		Ok(())
1611	}
1612
1613	/// Open (or create) the statement database with the column options expected by the current
1614	/// schema.
1615	fn open_db(path: &std::path::Path) -> Result<parity_db::Db> {
1616		let mut db_config = parity_db::Options::with_columns(path, col::COUNT);
1617		let statement_col = &mut db_config.columns[col::STATEMENTS as usize];
1618		statement_col.ref_counted = false;
1619		statement_col.preimage = true;
1620		statement_col.uniform = true;
1621		for c in BTREE_COLUMNS {
1622			db_config.columns[c as usize].btree_index = true;
1623		}
1624		parity_db::Db::open_or_create(&db_config).map_err(|e| Error::Db(e.to_string()))
1625	}
1626
1627	/// Read the on-disk database version and reconcile it with [`CURRENT_VERSION`].
1628	///
1629	/// A brand new database has its version initialised and needs no migration. An existing
1630	/// database from a newer version is rejected. Returns the on-disk version when it predates
1631	/// the current one and the database therefore needs migrating.
1632	fn check_db_version(db: &parity_db::Db) -> Result<Option<u32>> {
1633		match db.get(col::META, &KEY_VERSION).map_err(|e| Error::Db(e.to_string()))? {
1634			Some(version) => {
1635				let version = u32::from_le_bytes(
1636					version
1637						.try_into()
1638						.map_err(|_| Error::Db("Error reading database version".into()))?,
1639				);
1640				if version > CURRENT_VERSION {
1641					return Err(Error::Db(format!("Unsupported database version: {version}")));
1642				}
1643				Ok((version < CURRENT_VERSION).then_some(version))
1644			},
1645			None => {
1646				// Brand new database: the index columns start empty, nothing to migrate.
1647				Self::set_db_version(db, CURRENT_VERSION)?;
1648				Ok(None)
1649			},
1650		}
1651	}
1652
1653	/// Restore the in-memory state from the database at startup. Statement bodies are never
1654	/// decoded here, so startup cost does not depend on the size of the stored statements.
1655	///
1656	/// A database written by an older version is first migrated with [`Self::migrate_database`].
1657	// This function should only be used on startup. There should be no other DB operations when
1658	// iterating the index.
1659	fn populate(&self, migrate_from: Option<u32>) -> Result<()> {
1660		if let Some(version) = migrate_from {
1661			self.migrate_database(version)?;
1662		}
1663
1664		{
1665			let mut submit_index = self.submit_index.write();
1666			let mut query_index = self.query_index.write();
1667
1668			if let Some(counters) =
1669				self.db.get(col::META, KEY_COUNTERS).map_err(|e| Error::Db(e.to_string()))?
1670			{
1671				let (totals, next_seq) = <(StoreTotals, u64)>::decode(&mut counters.as_slice())
1672					.map_err(|_| Error::Db("Error reading the store counters".into()))?;
1673				submit_index.totals = totals;
1674				submit_index.set_next_seq(next_seq);
1675			}
1676			// While `next_seq` already holds the correct admission sequence number, it costs close
1677			// to nothing to check if the `next_seq` is consistent on the startup, and it can
1678			// catch a bug which could otherwise escape silently.
1679			let mut iter =
1680				self.db.iter(col::ADMISSION_SEQ).map_err(|e| Error::Db(e.to_string()))?;
1681			iter.seek_to_last().map_err(|e| Error::Db(e.to_string()))?;
1682			if let Some((key, _)) = iter.prev().map_err(|e| Error::Db(e.to_string()))? {
1683				let seq = u64::from_be_bytes(
1684					key.try_into()
1685						.map_err(|_| Error::Db("Invalid admission sequence key".into()))?,
1686				);
1687				if submit_index.next_seq <= seq {
1688					log::error!(
1689						target: LOG_TARGET,
1690						"The store counters lag the admission journal (next_seq {} <= last \
1691						 admission {}); recovering. This must be a bug, please report.",
1692						submit_index.next_seq,
1693						seq,
1694					);
1695					submit_index.set_next_seq(seq.saturating_add(1));
1696				}
1697			}
1698
1699			let mut evicted_count = 0usize;
1700			self.db
1701				.iter_column_while(col::EXPIRED, |_| {
1702					evicted_count += 1;
1703					true
1704				})
1705				.map_err(|e| Error::Db(e.to_string()))?;
1706			submit_index.evicted_count = evicted_count;
1707
1708			// Read-side cardinality counters, rebuilt from the index keys alone.
1709			for (prefix, count) in self.count_index_prefixes(col::INDEX_BY_TOPIC)? {
1710				let Ok(topic) = <[u8; 32]>::try_from(prefix.as_slice()).map(Topic::from) else {
1711					log::error!(
1712						target: LOG_TARGET,
1713						"Corrupt topic index prefix: {:?}",
1714						HexDisplay::from(&prefix)
1715					);
1716					continue;
1717				};
1718				query_index.topic_counts.insert(topic, count);
1719			}
1720			for (prefix, count) in self.count_index_prefixes(col::INDEX_BY_DEC_KEY)? {
1721				let Some(dec_key) = parse_dec_key_index_prefix(&prefix) else { continue };
1722				query_index.dec_key_counts.insert(dec_key, count);
1723			}
1724		}
1725
1726		self.known_accounts_count.store(self.count_accounts()?, AtomicOrdering::Relaxed);
1727		self.maintain();
1728		Ok(())
1729	}
1730
1731	/// Brings a database written at `from_version` to [`CURRENT_VERSION`], one version step at a
1732	/// time. Every step rewrites rows in place, so it is idempotent and safe to re-run after an
1733	/// interruption; the version is bumped only after the step has been committed.
1734	fn migrate_database(&self, from_version: u32) -> Result<()> {
1735		for version in from_version..CURRENT_VERSION {
1736			match version {
1737				1 => self.migrate_v1_to_v2()?,
1738				2 => self.migrate_v2_to_v3()?,
1739				_ => {
1740					return Err(Error::Db(format!("No migration from database version {version}")))
1741				},
1742			}
1743		}
1744		Ok(())
1745	}
1746
1747	/// Version 2 keeps the read indexes, the admission journal, the evicted journal and the
1748	/// counters row on disk. All of them are rebuilt from the authoritative `STATEMENTS` and
1749	/// `EXPIRED` columns.
1750	fn migrate_v1_to_v2(&self) -> Result<()> {
1751		let purge_after_sec = self.submit_index.read().config.purge_after_sec;
1752		// Admission entries persisted by an earlier version keep their sequence numbers;
1753		// statements lacking one (all of them, on a migration from version 1) get fresh numbers.
1754		let (mut admission_seqs, mut next_seq) = self.load_admission_seqs()?;
1755
1756		let mut migration = MigrationBatch::new(&self.db);
1757		// Older versions record no track, so migrated statements count as explicit-only.
1758		let mut totals = StoreTotals::default();
1759		self.for_each_stored_statement(|hash, statement, account| {
1760			let persisted_seq = admission_seqs.remove(hash);
1761			let seq = persisted_seq.unwrap_or_else(|| {
1762				let seq = next_seq;
1763				next_seq = seq.saturating_add(1);
1764				seq
1765			});
1766			totals.add(RetentionTrack::ExplicitOnly, statement.data_len());
1767			let details = EntryDetails {
1768				channel: statement.channel(),
1769				data_len: statement.data_len(),
1770				admission_seq: seq,
1771				track: RetentionTrack::ExplicitOnly,
1772			};
1773			let admission_op = persisted_seq.is_none().then(|| DbOperation {
1774				column: col::ADMISSION_SEQ,
1775				key: seq.to_be_bytes().to_vec(),
1776				value: Some(hash.to_vec()),
1777			});
1778			let operations = statement_index_ops(hash, statement, true)
1779				.into_iter()
1780				.chain(account_index_ops(account, Expiry(statement.expiry()), hash, Some(&details)))
1781				.map(DbOperation::from)
1782				.chain(admission_op);
1783			migration.extend(operations)
1784		})?;
1785
1786		let mut migration_error = None;
1787		self.db
1788			.iter_column_while(col::EXPIRED, |item| {
1789				if let Ok((hash, timestamp)) = <(Hash, u64)>::decode(&mut item.value.as_slice()) {
1790					log::trace!(
1791						target: LOG_TARGET,
1792						"Statement loaded (expired): {:?}",
1793						HexDisplay::from(&hash)
1794					);
1795					let purge_at = timestamp.saturating_add(purge_after_sec);
1796					let operation = DbOperation {
1797						column: col::INDEX_EVICTED,
1798						key: evicted_index_key(purge_at, &hash),
1799						value: Some(INDEX_EMPTY_VALUE.to_vec()),
1800					};
1801					if let Err(error) = migration.push(operation) {
1802						migration_error = Some(error);
1803						return false;
1804					}
1805				}
1806				true
1807			})
1808			.map_err(|e| Error::Db(e.to_string()))?;
1809		if let Some(error) = migration_error {
1810			return Err(error);
1811		}
1812
1813		migration.push(SubmitIndex::counters_op(&totals, next_seq).into())?;
1814		let migrated_entries = migration.finish()?;
1815		Self::set_db_version(&self.db, 2)?;
1816		log::info!(
1817			target: LOG_TARGET,
1818			"Migrated the statement store index to the on-disk format ({} rows)",
1819			migrated_entries
1820		);
1821		Ok(())
1822	}
1823
1824	/// Version 3 records the retention track in every account index row and keeps the store
1825	/// totals per track. Older rows carry no track, so every statement lands on the explicit-only
1826	/// track; the other columns are left as they are.
1827	fn migrate_v2_to_v3(&self) -> Result<()> {
1828		// A statement whose admission entry is missing gets a fresh sequence number, as on a
1829		// migration from version 1.
1830		let (mut admission_seqs, mut next_seq) = self.load_admission_seqs()?;
1831		let mut migration = MigrationBatch::new(&self.db);
1832		let mut totals = StoreTotals::default();
1833		self.for_each_stored_statement(|hash, statement, account| {
1834			let persisted_seq = admission_seqs.remove(hash);
1835			let seq = persisted_seq.unwrap_or_else(|| {
1836				let seq = next_seq;
1837				next_seq = seq.saturating_add(1);
1838				seq
1839			});
1840			totals.add(RetentionTrack::ExplicitOnly, statement.data_len());
1841			let details = EntryDetails {
1842				channel: statement.channel(),
1843				data_len: statement.data_len(),
1844				admission_seq: seq,
1845				track: RetentionTrack::ExplicitOnly,
1846			};
1847			let admission_op = persisted_seq.is_none().then(|| DbOperation {
1848				column: col::ADMISSION_SEQ,
1849				key: seq.to_be_bytes().to_vec(),
1850				value: Some(hash.to_vec()),
1851			});
1852			let operations =
1853				account_index_ops(account, Expiry(statement.expiry()), hash, Some(&details))
1854					.into_iter()
1855					.map(DbOperation::from)
1856					.chain(admission_op);
1857			migration.extend(operations)
1858		})?;
1859		migration.push(SubmitIndex::counters_op(&totals, next_seq).into())?;
1860		let migrated_entries = migration.finish()?;
1861		Self::set_db_version(&self.db, 3)?;
1862		log::info!(
1863			target: LOG_TARGET,
1864			"Migrated the statement store index to per-track totals ({} rows)",
1865			migrated_entries
1866		);
1867		Ok(())
1868	}
1869
1870	fn set_db_version(db: &parity_db::Db, version: u32) -> Result<()> {
1871		db.commit([(col::META, KEY_VERSION.to_vec(), Some(version.to_le_bytes().to_vec()))])
1872			.map_err(|e| Error::Db(e.to_string()))
1873	}
1874
1875	/// The persisted admission sequence numbers by statement hash, and the next free one.
1876	fn load_admission_seqs(&self) -> Result<(HashMap<Hash, u64>, u64)> {
1877		let mut admission_seqs = HashMap::new();
1878		let mut next_seq = 0u64;
1879		let mut iter = self.db.iter(col::ADMISSION_SEQ).map_err(|e| Error::Db(e.to_string()))?;
1880		iter.seek_to_first().map_err(|e| Error::Db(e.to_string()))?;
1881		while let Some((key, value)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
1882			let seq = u64::from_be_bytes(
1883				key.try_into().map_err(|_| Error::Db("Invalid admission sequence key".into()))?,
1884			);
1885			let hash: Hash = value
1886				.as_slice()
1887				.try_into()
1888				.map_err(|_| Error::Db("Invalid admission sequence hash".into()))?;
1889			admission_seqs.insert(hash, seq);
1890			next_seq = next_seq.max(seq.saturating_add(1));
1891		}
1892		Ok((admission_seqs, next_seq))
1893	}
1894
1895	/// Runs `f` on every stored statement and its account. Rows that fail to decode or carry no
1896	/// account are logged and skipped; an error from `f` ends the pass.
1897	fn for_each_stored_statement(
1898		&self,
1899		mut f: impl FnMut(&Hash, &Statement, &AccountId) -> Result<()>,
1900	) -> Result<()> {
1901		let mut error = None;
1902		self.db
1903			.iter_column_while(col::STATEMENTS, |item| {
1904				let Ok(statement) = Statement::decode(&mut item.value.as_slice()) else {
1905					log::error!(
1906						target: LOG_TARGET,
1907						"Corrupt statement {:?}",
1908						HexDisplay::from(&sp_statement_store::hash_encoded(&item.value))
1909					);
1910					return true;
1911				};
1912				let hash = statement.hash();
1913				let Some(account) = statement.account_id() else {
1914					log::error!(
1915						target: LOG_TARGET,
1916						"Statement without an account id loaded from the DB: {:?}",
1917						HexDisplay::from(&hash)
1918					);
1919					return true;
1920				};
1921				log::trace!(target: LOG_TARGET, "Statement loaded {:?}", HexDisplay::from(&hash));
1922				match f(&hash, &statement, &account) {
1923					Ok(()) => true,
1924					Err(e) => {
1925						error = Some(e);
1926						false
1927					},
1928				}
1929			})
1930			.map_err(|e| Error::Db(e.to_string()))?;
1931		error.map_or(Ok(()), Err)
1932	}
1933
1934	/// Counts, for every distinct prefix (the key minus its trailing 32-byte hash), the number of
1935	/// entries in a btree index column. The keys iterate in order, so each prefix's entries form
1936	/// one contiguous run.
1937	fn count_index_prefixes(&self, column: u8) -> Result<Vec<(Vec<u8>, usize)>> {
1938		let mut counts: Vec<(Vec<u8>, usize)> = Vec::new();
1939		let mut iter = self.db.iter(column).map_err(|e| Error::Db(e.to_string()))?;
1940		iter.seek_to_first().map_err(|e| Error::Db(e.to_string()))?;
1941		while let Some((key, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
1942			let Some(prefix) = prefix_from_index_key(&key) else { continue };
1943			match counts.last_mut() {
1944				Some((last, count)) if last.as_slice() == prefix => *count += 1,
1945				_ => counts.push((prefix.to_vec(), 1)),
1946			}
1947		}
1948		Ok(counts)
1949	}
1950
1951	/// First account at or after `from` in the on-disk per-account index. Corrupt keys are skipped
1952	/// rather than treated as the end of the index: they must not disable allowance enforcement
1953	/// for the accounts sorted after them.
1954	fn next_account_from(&self, from: &AccountId) -> Result<Option<AccountId>> {
1955		let mut iter = self.db.iter(col::INDEX_BY_ACCOUNT).map_err(|e| Error::Db(e.to_string()))?;
1956		iter.seek(&from[..]).map_err(|e| Error::Db(e.to_string()))?;
1957		while let Some((key, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
1958			if let Some((account, _, _)) = parse_account_index_key(&key) {
1959				return Ok(Some(account));
1960			}
1961		}
1962		Ok(None)
1963	}
1964
1965	/// Number of accounts with at least one stored statement, counted by hopping over the
1966	/// distinct account prefixes of the on-disk per-account index.
1967	fn count_accounts(&self) -> Result<usize> {
1968		let mut count = 0usize;
1969		let mut cursor = [0u8; 32];
1970		while let Some(account) = self.next_account_from(&cursor)? {
1971			count += 1;
1972			match next_account_id(account) {
1973				Some(next) => cursor = next,
1974				None => break,
1975			}
1976		}
1977		Ok(count)
1978	}
1979
1980	/// Reads every per-account index row of `account`, in priority order.
1981	fn load_account_entries(
1982		&self,
1983		account: &AccountId,
1984	) -> Result<Vec<(PriorityKey, EntryDetails)>> {
1985		let mut entries = Vec::new();
1986		let mut iter = self.db.iter(col::INDEX_BY_ACCOUNT).map_err(|e| Error::Db(e.to_string()))?;
1987		iter.seek(&account[..]).map_err(|e| Error::Db(e.to_string()))?;
1988		while let Some((key, value)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
1989			if !key.starts_with(&account[..]) {
1990				break;
1991			}
1992			let Some((_, expiry, hash)) = parse_account_index_key(&key) else { continue };
1993			let Ok(details) = EntryDetails::decode(&mut value.as_slice()) else {
1994				log::error!(
1995					target: LOG_TARGET,
1996					"Corrupt account index row for statement {:?}",
1997					HexDisplay::from(&hash)
1998				);
1999				continue;
2000			};
2001			entries.push((PriorityKey { hash, expiry }, details));
2002		}
2003		Ok(entries)
2004	}
2005
2006	/// Assembles an account's in-memory record from its on-disk index rows.
2007	fn load_account_record(&self, account: &AccountId) -> Result<StatementsForAccount> {
2008		let mut record = StatementsForAccount::default();
2009		for (key, details) in self.load_account_entries(account)? {
2010			record.insert_entry(key.hash, key.expiry, details);
2011		}
2012		Ok(record)
2013	}
2014
2015	/// Scans an on-disk btree index column for every hash whose key starts with `prefix`.
2016	fn scan_index_prefix(&self, column: u8, prefix: &[u8]) -> Result<HashSet<Hash>> {
2017		let mut set = HashSet::new();
2018		let mut iter = self.db.iter(column).map_err(|e| Error::Db(e.to_string()))?;
2019		iter.seek(prefix).map_err(|e| Error::Db(e.to_string()))?;
2020		while let Some((key, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
2021			if !key.starts_with(prefix) {
2022				break;
2023			}
2024			if let Some(hash) = hash_from_index_key(&key) {
2025				set.insert(hash);
2026			}
2027		}
2028		Ok(set)
2029	}
2030
2031	/// Enumerates the hashes of all active statements. Each statement has exactly one entry in
2032	/// [`col::INDEX_BY_DEC_KEY`], so scanning that column's keys yields every hash exactly once,
2033	/// without decoding any bodies.
2034	fn enumerate_hashes(&self) -> Result<Vec<Hash>> {
2035		let mut hashes = Vec::new();
2036		let mut iter = self.db.iter(col::INDEX_BY_DEC_KEY).map_err(|e| Error::Db(e.to_string()))?;
2037		iter.seek_to_first().map_err(|e| Error::Db(e.to_string()))?;
2038		while let Some((key, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
2039			if let Some(hash) = hash_from_index_key(&key) {
2040				hashes.push(hash);
2041			}
2042		}
2043		Ok(hashes)
2044	}
2045
2046	/// Tests, against the on-disk column, whether `hash` belongs to an index set.
2047	fn index_set_contains(&self, set: &IndexSet, hash: &Hash) -> Result<bool> {
2048		Ok(self
2049			.db
2050			.get_size(set.column(), &set.member_key(hash))
2051			.map_err(|e| Error::Db(e.to_string()))?
2052			.is_some())
2053	}
2054
2055	/// Whether `hash` is present in every one of `sets`, tested against the on-disk index. Used to
2056	/// intersect a materialised candidate set with the remaining topic / decryption-key sets.
2057	fn hash_in_all_sets(&self, hash: &Hash, sets: &[IndexSet]) -> Result<bool> {
2058		sets.iter().try_fold(true, |acc, set| {
2059			Ok::<bool, Error>(acc && self.index_set_contains(set, hash)?)
2060		})
2061	}
2062
2063	/// Enumerates matching hashes for `key` / `topic`, reading candidates directly from the on-disk
2064	/// index for every filter kind. Used both for ad-hoc reads and for subscription snapshots.
2065	fn iterate_with(
2066		&self,
2067		key: Option<DecryptionKey>,
2068		topic_filter: &OptimizedTopicFilter,
2069		f: impl FnMut(&Hash) -> Result<()>,
2070	) -> Result<()> {
2071		match topic_filter {
2072			OptimizedTopicFilter::Any => self.iterate_with_any(key, f),
2073			OptimizedTopicFilter::MatchAll(topics) => self.iterate_with_match_all(key, topics, f),
2074			OptimizedTopicFilter::MatchAny(topics) => self.iterate_with_match_any(key, topics, f),
2075		}
2076	}
2077
2078	/// Streams every hash for a decryption key directly from disk.
2079	fn iterate_with_any(
2080		&self,
2081		key: Option<DecryptionKey>,
2082		mut f: impl FnMut(&Hash) -> Result<()>,
2083	) -> Result<()> {
2084		let prefix = IndexSet::DecKey(key).prefix();
2085		let mut iter = self.db.iter(col::INDEX_BY_DEC_KEY).map_err(|e| Error::Db(e.to_string()))?;
2086		iter.seek(&prefix).map_err(|e| Error::Db(e.to_string()))?;
2087		while let Some((k, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
2088			if !k.starts_with(&prefix) {
2089				break;
2090			}
2091			if let Some(hash) = hash_from_index_key(&k) {
2092				f(&hash)?;
2093			}
2094		}
2095		Ok(())
2096	}
2097
2098	/// For each requested topic, streams its hashes from disk and yields those that also belong to
2099	/// the decryption-key set. A hash carrying several requested topics is yielded once per topic,
2100	/// matching the in-memory behaviour callers already tolerate.
2101	fn iterate_with_match_any(
2102		&self,
2103		key: Option<DecryptionKey>,
2104		topics: &HashSet<Topic>,
2105		mut f: impl FnMut(&Hash) -> Result<()>,
2106	) -> Result<()> {
2107		let key_set = IndexSet::DecKey(key);
2108		for topic in topics {
2109			let prefix = topic[..].to_vec();
2110			let mut iter =
2111				self.db.iter(col::INDEX_BY_TOPIC).map_err(|e| Error::Db(e.to_string()))?;
2112			iter.seek(&prefix).map_err(|e| Error::Db(e.to_string()))?;
2113			while let Some((k, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
2114				if !k.starts_with(&prefix) {
2115					break;
2116				}
2117				if let Some(hash) = hash_from_index_key(&k) {
2118					if self.index_set_contains(&key_set, &hash)? {
2119						f(&hash)?;
2120					}
2121				}
2122			}
2123		}
2124		Ok(())
2125	}
2126
2127	/// Intersects the decryption-key set with all requested topic sets, reading candidates directly
2128	/// from the on-disk index. The lock is taken only briefly to order the sets by cardinality so
2129	/// the smallest is materialised first; this ordering is a best-effort hint (stale counters can
2130	/// only misorder the sets, never drop a statement). Materialising that set and probing the rest
2131	/// against disk then happen without holding the lock.
2132	fn iterate_with_match_all(
2133		&self,
2134		key: Option<DecryptionKey>,
2135		topics: &HashSet<Topic>,
2136		mut f: impl FnMut(&Hash) -> Result<()>,
2137	) -> Result<()> {
2138		if topics.len() > MAX_TOPICS {
2139			return Ok(());
2140		}
2141		let mut sets = Vec::with_capacity(topics.len() + 1);
2142		sets.push(IndexSet::DecKey(key));
2143		for topic in topics {
2144			sets.push(IndexSet::Topic(*topic));
2145		}
2146		{
2147			// Ordering only (best-effort): stale counters can misorder but never drop a statement.
2148			let query_index = self.query_index.read();
2149			sets.sort_by_key(|s| s.len(&query_index));
2150		}
2151		let smallest = self.scan_index_prefix(sets[0].column(), &sets[0].prefix())?;
2152		let others = &sets[1..];
2153		for hash in &smallest {
2154			if self.hash_in_all_sets(hash, others)? {
2155				log::trace!(
2156					target: LOG_TARGET,
2157					"Iterating by topic/key: statement {:?}",
2158					HexDisplay::from(hash)
2159				);
2160				f(hash)?;
2161			}
2162		}
2163		Ok(())
2164	}
2165
2166	/// Reads the raw SCALE-encoded body of `hash` from `col::STATEMENTS`, or `None` if it is absent
2167	/// (a benign DB race: the statement was removed concurrently). The stored value is exactly
2168	/// `statement.encode()`, so it can be forwarded verbatim.
2169	fn read_statement_encoded(&self, hash: &Hash) -> Result<Option<Vec<u8>>> {
2170		match self.db.get(col::STATEMENTS, hash).map_err(|e| Error::Db(e.to_string()))? {
2171			Some(entry) => Ok(Some(entry)),
2172			None => {
2173				log::debug!(target: LOG_TARGET, "Missing statement {:?}", HexDisplay::from(hash));
2174				Ok(None)
2175			},
2176		}
2177	}
2178
2179	/// Reads and decodes the statement `hash`, returning `None` if it is absent or its stored body
2180	/// fails to decode (a corrupt DB row, which is logged and skipped).
2181	fn read_statement(&self, hash: &Hash) -> Result<Option<Statement>> {
2182		let Some(entry) = self.read_statement_encoded(hash)? else { return Ok(None) };
2183		match Statement::decode(&mut entry.as_slice()) {
2184			Ok(statement) => Ok(Some(statement)),
2185			Err(_) => {
2186				log::error!(target: LOG_TARGET, "Corrupt statement {:?}", HexDisplay::from(hash));
2187				Ok(None)
2188			},
2189		}
2190	}
2191
2192	/// Collects statements matching `key` / `topic_filter`. Reads never hold the query-index lock
2193	/// across disk I/O: `Any` / `MatchAny` touch only the (thread-safe) database, and `MatchAll`
2194	/// takes the lock only momentarily to order the candidate sets.
2195	fn collect_statements<R>(
2196		&self,
2197		key: Option<DecryptionKey>,
2198		topic_filter: &OptimizedTopicFilter,
2199		mut f: impl FnMut(Statement) -> Option<R>,
2200	) -> Result<Vec<R>> {
2201		let mut result = Vec::new();
2202		self.iterate_with(key, topic_filter, |hash| {
2203			if let Some(statement) = self.read_statement(hash)? {
2204				if let Some(data) = f(statement) {
2205					result.push(data);
2206				}
2207			}
2208			Ok(())
2209		})?;
2210		Ok(result)
2211	}
2212
2213	/// Evicts the lowest-priority statements of `account` while it exceeds the larger of its
2214	/// allowances at the finalized and the best block, spending at most `budget` evictions.
2215	/// Admission checks only the best block, so taking it here too keeps what admission accepted
2216	/// while finality lags. Expired statements neither count nor get evicted here; the expiry
2217	/// sweep reaps them.
2218	fn enforce_account_allowance(
2219		&self,
2220		account: &AccountId,
2221		current_time: u64,
2222		budget: &mut usize,
2223	) {
2224		let read_allowance =
2225			|allowance_block| match (self.read_allowance_fn)(account, allowance_block) {
2226				Ok(Some(allowance)) => Some(allowance),
2227				Ok(None) => {
2228					log::debug!(
2229						target: LOG_TARGET,
2230						"No allowance found for account {:?}, treating as zero allowance",
2231						HexDisplay::from(account)
2232					);
2233					Some(StatementAllowance { max_count: 0, max_size: 0 })
2234				},
2235				Err(e) => {
2236					log::error!(target: LOG_TARGET, "Error reading allowance: {:?}", e);
2237					// Skip allowance enforcement for this account on error
2238					None
2239				},
2240			};
2241		let fits = |allowance: &StatementAllowance, count: usize, size: usize| {
2242			count <= allowance.max_count as usize && size <= allowance.max_size as usize
2243		};
2244		let Some(finalized) = read_allowance(AllowanceBlock::Finalized) else { return };
2245
2246		// A cached summary proving the account within its allowance saves the disk scan. The
2247		// summary also counts expired-but-unswept statements, so it can only overestimate usage,
2248		// which is fine for a within-limit conclusion; the over-limit path recounts from disk.
2249		if let Some(summary) = self.submit_index.read().summaries.peek(account) {
2250			if fits(&finalized, summary.count, summary.data_size) {
2251				return;
2252			}
2253		}
2254
2255		let entries = match self.load_account_entries(account) {
2256			Ok(entries) => entries,
2257			Err(e) => {
2258				log::warn!(target: LOG_TARGET, "Error reading the account index: {:?}", e);
2259				return;
2260			},
2261		};
2262		let expiry_bound = Expiry(current_time << 32);
2263		let mut remaining_count = 0usize;
2264		let mut remaining_size = 0usize;
2265		for (key, details) in &entries {
2266			if key.expiry >= expiry_bound {
2267				remaining_count += 1;
2268				remaining_size += details.data_len;
2269			}
2270		}
2271		if fits(&finalized, remaining_count, remaining_size) {
2272			return;
2273		}
2274		// The best block is read only for accounts already over their finalized allowance
2275		let Some(best) = read_allowance(AllowanceBlock::Best) else { return };
2276		let allowance = StatementAllowance {
2277			max_count: finalized.max_count.max(best.max_count),
2278			max_size: finalized.max_size.max(best.max_size),
2279		};
2280		if fits(&allowance, remaining_count, remaining_size) {
2281			return;
2282		}
2283		log::debug!(
2284			target: LOG_TARGET,
2285			"Account {:?} exceeds allowance: count={}/{}, size={}/{}",
2286			HexDisplay::from(account),
2287			remaining_count,
2288			allowance.max_count,
2289			remaining_size,
2290			allowance.max_size
2291		);
2292
2293		// Evict lowest priority statements that exceed allowance
2294		for (key, details) in &entries {
2295			if fits(&allowance, remaining_count, remaining_size) || *budget == 0 {
2296				break;
2297			}
2298			if key.expiry < expiry_bound {
2299				continue;
2300			}
2301			log::debug!(
2302				target: LOG_TARGET,
2303				"Evicting statement {:?} due to allowance enforcement",
2304				HexDisplay::from(&key.hash)
2305			);
2306			if let Err(e) = self.remove(&key.hash) {
2307				log::debug!(
2308					target: LOG_TARGET,
2309					"Error evicting statement {:?}: {:?}",
2310					HexDisplay::from(&key.hash),
2311					e
2312				);
2313			} else {
2314				*budget -= 1;
2315				remaining_count -= 1;
2316				remaining_size -= details.data_len;
2317			}
2318		}
2319	}
2320
2321	// Reaps expired statements and enforces per-account allowances against the on-disk index.
2322	//
2323	// Expired statements form a prefix of the global expiry index ([`col::INDEX_BY_EXPIRY`]), so
2324	// the sweep costs time proportional to the number of due statements, not to the store size.
2325	// Allowance enforcement then walks the accounts of [`col::INDEX_BY_ACCOUNT`] incrementally,
2326	// resuming from where the previous call stopped (`allowance_cursor`), so the process
2327	// eventually covers all accounts across multiple invocations.
2328	//
2329	// The two phases are budgeted independently: each gets its own
2330	// `MAX_EXPIRY_STATEMENTS_PER_ITERATION` statement budget and its own
2331	// `MAX_EXPIRY_TIME_PER_ITERATION` time slice, and allowance enforcement is additionally
2332	// bounded by `MAX_EXPIRY_ACCOUNTS_PER_ITERATION` accounts checked. The isolation matters:
2333	// with shared budgets, a store whose expiry inflow persistently exceeds the expiry budget
2334	// (a full store with a short TTL) would never get an allowance pass at all.
2335	//
2336	// Statements are considered expired when their expiry (which encodes the expiration
2337	// timestamp in the upper 32 bits) is less than the current timestamp.
2338	/// Reap expired statements and enforce per-account allowances (one bounded pass); runs
2339	/// periodically from the background task. Hidden: exposed only for the benchmarks.
2340	/// Returns `true` if expired statements are still due after the pass.
2341	#[doc(hidden)]
2342	pub fn enforce_limits(&self) -> bool {
2343		self.enforce_limits_bounded(
2344			MAX_EXPIRY_STATEMENTS_PER_ITERATION,
2345			MAX_EXPIRY_ACCOUNTS_PER_ITERATION,
2346			MAX_EXPIRY_TIME_PER_ITERATION,
2347		)
2348	}
2349
2350	/// Body of [`Self::enforce_limits`] with the per-call bounds as parameters, letting the
2351	/// tests drive the incremental sweep with budgets small enough to need several calls.
2352	/// `statement_budget` and `time_budget` apply to each phase separately.
2353	fn enforce_limits_bounded(
2354		&self,
2355		statement_budget: usize,
2356		account_budget: usize,
2357		time_budget: Duration,
2358	) -> bool {
2359		let _start_check_expiration_timer = self.metrics.start_check_expiration_timer();
2360		let current_time = self.timestamp();
2361		let start = Instant::now();
2362		let mut expired = 0u64;
2363
2364		// Phase 1: reap statements past their expiry, straight off the expiry index.
2365		let mut due = Vec::new();
2366		let scan = (|| -> Result<()> {
2367			let mut iter =
2368				self.db.iter(col::INDEX_BY_EXPIRY).map_err(|e| Error::Db(e.to_string()))?;
2369			iter.seek_to_first().map_err(|e| Error::Db(e.to_string()))?;
2370			while let Some((key, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
2371				let Some((expiry, hash)) = parse_time_index_key(&key) else { continue };
2372				if expiry >= (current_time << 32) {
2373					// Entries are ordered by expiry, so nothing further is due.
2374					break;
2375				}
2376				due.push((expiry, hash));
2377				if due.len() >= statement_budget || start.elapsed() >= time_budget {
2378					break;
2379				}
2380			}
2381			Ok(())
2382		})();
2383		if let Err(e) = scan {
2384			log::warn!(target: LOG_TARGET, "Error scanning the expiry index: {:?}", e);
2385		}
2386		for (expiry, hash) in due {
2387			match self.remove_statement(&hash, Resubmission::Banned) {
2388				Ok(true) => {
2389					expired += 1;
2390					log::trace!(
2391						target: LOG_TARGET,
2392						"Marked statement {:?} as expired",
2393						HexDisplay::from(&hash)
2394					);
2395				},
2396				// The row survived its statement: either a concurrent removal won the race (and
2397				// deleted the row along with the body), or the store is inconsistent.
2398				Ok(false) => self.report_orphan_expiry_row(expiry, &hash),
2399				Err(e) => {
2400					log::debug!(
2401						target: LOG_TARGET,
2402						"Error marking statement {:?} as expired: {:?}",
2403						HexDisplay::from(&hash),
2404						e
2405					);
2406				},
2407			}
2408		}
2409		// If due statements remain, the background task runs the next pass after a short delay.
2410		let more_due = expired > 0 && self.has_due_expiry(current_time).unwrap_or(false);
2411
2412		// Phase 2: enforce allowances account by account, resuming from the cursor. The phase
2413		// runs on its own statement and time budgets: with shared ones, a sustained expiry
2414		// backlog exhausting phase 1's budget on every pass would starve allowance enforcement
2415		// indefinitely.
2416		let allowance_start = Instant::now();
2417		let mut allowance_budget = statement_budget;
2418		let mut cursor = self.submit_index.read().allowance_cursor;
2419		let mut checked = 0usize;
2420		let mut wrapped = false;
2421		while checked < account_budget &&
2422			allowance_budget > 0 &&
2423			allowance_start.elapsed() < time_budget
2424		{
2425			let from = cursor.unwrap_or([0u8; 32]);
2426			let account = match self.next_account_from(&from) {
2427				Ok(Some(account)) => account,
2428				Ok(None) => {
2429					wrapped = true;
2430					break;
2431				},
2432				Err(e) => {
2433					log::warn!(target: LOG_TARGET, "Error reading the account index: {:?}", e);
2434					break;
2435				},
2436			};
2437			checked += 1;
2438			let budget_before = allowance_budget;
2439			self.enforce_account_allowance(&account, current_time, &mut allowance_budget);
2440			expired += (budget_before - allowance_budget) as u64;
2441			cursor = match next_account_id(account) {
2442				next @ Some(_) => next,
2443				None => {
2444					wrapped = true;
2445					break;
2446				},
2447			};
2448		}
2449		{
2450			let mut submit_index = self.submit_index.write();
2451			submit_index.allowance_cycle_seen += checked;
2452			if wrapped {
2453				// A full pass over the account index just completed; it is the only place where
2454				// the total number of accounts is (re)counted.
2455				self.known_accounts_count
2456					.store(submit_index.allowance_cycle_seen, AtomicOrdering::Relaxed);
2457				submit_index.allowance_cycle_seen = 0;
2458				submit_index.allowance_cursor = None;
2459			} else {
2460				submit_index.allowance_cursor = cursor;
2461			}
2462		}
2463
2464		drop(_start_check_expiration_timer);
2465
2466		self.metrics.report(|metrics| {
2467			metrics.statements_expired_total.inc_by(expired);
2468		});
2469
2470		more_due
2471	}
2472
2473	/// Returns `true` if the expiry index still holds a statement due at `current_time`.
2474	fn has_due_expiry(&self, current_time: u64) -> Result<bool> {
2475		let db_err = |e: parity_db::Error| Error::Db(e.to_string());
2476		let mut iter = self.db.iter(col::INDEX_BY_EXPIRY).map_err(db_err)?;
2477		iter.seek_to_first().map_err(db_err)?;
2478		let first = iter.next().map_err(db_err)?;
2479		Ok(first
2480			.and_then(|(key, _)| parse_time_index_key(&key))
2481			.is_some_and(|(expiry, _)| expiry < (current_time << 32)))
2482	}
2483
2484	/// Drains the on-disk evicted journal of entries whose purge deadline has passed. Returns how
2485	/// many entries were drained.
2486	fn drain_due_evicted(&self, current_time: u64) -> Result<usize> {
2487		let mut commit: Vec<(u8, Vec<u8>, Option<Vec<u8>>)> = Vec::new();
2488		let mut drained = 0usize;
2489		{
2490			let mut iter =
2491				self.db.iter(col::INDEX_EVICTED).map_err(|e| Error::Db(e.to_string()))?;
2492			iter.seek_to_first().map_err(|e| Error::Db(e.to_string()))?;
2493			loop {
2494				let Some((key, _)) = iter.next().map_err(|e| Error::Db(e.to_string()))? else {
2495					break;
2496				};
2497				let Some((purge_at, hash)) = parse_time_index_key(&key) else { continue };
2498				if purge_at > current_time {
2499					// Entries are ordered by purge time, so nothing further is due.
2500					break;
2501				}
2502				commit.push((col::EXPIRED, hash.to_vec(), None));
2503				commit.push((col::INDEX_EVICTED, key, None));
2504				drained += 1;
2505			}
2506		}
2507		if !commit.is_empty() {
2508			self.db.commit(commit).map_err(|e| Error::Db(e.to_string()))?;
2509		}
2510		Ok(drained)
2511	}
2512
2513	/// Re-check the retention of the tracked statements once they are propagated: the
2514	/// resolver's verdict becomes their track, and a statement no affinity covers is removed.
2515	fn sweep_retention(&self) {
2516		let Some(resolver) = self.retention_fn.get() else { return };
2517		let candidates: Vec<(Hash, RetentionTrack)> = {
2518			let query_index = self.query_index.read();
2519			query_index
2520				.retention_tracks
2521				.iter()
2522				.filter(|(hash, _)| query_index.propagated_track(hash).is_some())
2523				.map(|(hash, track)| (*hash, *track))
2524				.collect()
2525		};
2526		for (hash, track) in candidates {
2527			let encoded = match self.db.get(col::STATEMENTS, &hash) {
2528				Ok(Some(encoded)) => encoded,
2529				Ok(None) => continue,
2530				Err(e) => {
2531					log::warn!(
2532						target: LOG_TARGET,
2533						"Error reading statement {:?}: {:?}",
2534						HexDisplay::from(&hash),
2535						e
2536					);
2537					continue;
2538				},
2539			};
2540			let Ok(statement) = Statement::decode(&mut encoded.as_slice()) else {
2541				log::error!(target: LOG_TARGET, "Corrupt statement {:?}", HexDisplay::from(&hash));
2542				continue;
2543			};
2544			let verdict = RetentionTrack::from(resolver(&statement));
2545			if (track, verdict) == (RetentionTrack::ExplicitOnly, RetentionTrack::ExplicitOnly) {
2546				continue;
2547			}
2548			let mut submit_index = self.submit_index.write();
2549			// Admission updates the query index under the submit lock, so this re-check rules
2550			// out a copy re-admitted since the candidates were collected: under another track
2551			// its entry changed, under the same track it awaits propagation in `recent`.
2552			if self.query_index.read().propagated_track(&hash) != Some(track) {
2553				continue;
2554			}
2555			match verdict {
2556				RetentionTrack::Persistent | RetentionTrack::ExplicitOnly => {
2557					match self.retrack_statement_locked(&mut submit_index, &statement, verdict) {
2558						Ok(true) => {
2559							let mut query_index = self.query_index.write();
2560							if verdict.is_persistent() {
2561								query_index.retention_tracks.remove(&hash);
2562							} else {
2563								query_index.retention_tracks.insert(hash, verdict);
2564							}
2565						},
2566						// Logged where found, left tracked so the next sweep reports it again.
2567						Ok(false) => {},
2568						Err(e) => log::warn!(
2569							target: LOG_TARGET,
2570							"Error moving statement {:?} to {:?}: {:?}",
2571							HexDisplay::from(&hash),
2572							verdict,
2573							e
2574						),
2575					}
2576				},
2577				RetentionTrack::Transient => {
2578					// A lapsed explicit-only statement may return with its affinity, a forwarded
2579					// transient one must not be forwarded again.
2580					let resubmission = if track == RetentionTrack::ExplicitOnly {
2581						Resubmission::Allowed
2582					} else {
2583						Resubmission::Banned
2584					};
2585					match self.remove_statement_locked(&mut submit_index, &hash, resubmission) {
2586						Ok(true) => {},
2587						// The re-check above saw the entry under the submit lock, so a missing
2588						// body is an index inconsistency, left in place for investigation.
2589						Ok(false) => log::error!(
2590							target: LOG_TARGET,
2591							"Missing body for tracked statement {:?}",
2592							HexDisplay::from(&hash)
2593						),
2594						Err(e) => log::warn!(
2595							target: LOG_TARGET,
2596							"Error removing statement {:?}: {:?}",
2597							HexDisplay::from(&hash),
2598							e
2599						),
2600					}
2601				},
2602			}
2603		}
2604	}
2605
2606	/// Perform periodic store maintenance: re-check the tracked statements, permanently
2607	/// delete statements whose purge period has elapsed, and refresh store metrics.
2608	///
2609	/// Expired and evicted statements are not removed from the database immediately; they are kept
2610	/// in the `EXPIRED` column for [`DEFAULT_PURGE_AFTER_SEC`] (default 48h) to prevent
2611	/// re-acceptance while they may still be propagating over gossip. This method removes those
2612	/// whose purge period has passed.
2613	///
2614	/// Runs in a background task on a fixed interval (`MAINTENANCE_PERIOD`, 29s). Enforcing
2615	/// per-account and global limits — expiring over-quota statements — is handled separately by
2616	/// `enforce_limits` on its own interval (`ENFORCE_LIMITS_PERIOD`, 31s), kept distinct to avoid
2617	/// holding the index lock for too long during maintenance.
2618	pub fn maintain(&self) {
2619		log::trace!(target: LOG_TARGET, "Started store maintenance");
2620		self.sweep_retention();
2621		let current_time = self.timestamp();
2622		let deleted_count = match self.drain_due_evicted(current_time) {
2623			Ok(count) => count as u64,
2624			Err(e) => {
2625				log::warn!(target: LOG_TARGET, "Error writing to the statement database: {:?}", e);
2626				0
2627			},
2628		};
2629
2630		let (active_count, expired_count, totals, capacity_statements, capacity_bytes) = {
2631			let mut submit_index = self.submit_index.write();
2632			submit_index.evicted_count =
2633				submit_index.evicted_count.saturating_sub(deleted_count as usize);
2634			(
2635				submit_index.statement_count(),
2636				submit_index.evicted_count,
2637				submit_index.totals,
2638				submit_index.config.max_total_statements,
2639				submit_index.config.max_total_size,
2640			)
2641		};
2642		let accounts_count = self.known_accounts_count.load(AtomicOrdering::Relaxed);
2643		let held_count = self.query_index.read().held.len();
2644
2645		if deleted_count > 0 {
2646			self.metrics.report(|metrics| metrics.statements_pruned.inc_by(deleted_count));
2647		}
2648
2649		self.metrics.report(|metrics| {
2650			metrics.statements_total.set(active_count as u64);
2651			metrics.bytes_total.set(totals.size() as u64);
2652			for track in [
2653				RetentionTrack::Transient,
2654				RetentionTrack::ExplicitOnly,
2655				RetentionTrack::Persistent,
2656			] {
2657				metrics
2658					.bytes_by_retention
2659					.with_label_values(&[track.label()])
2660					.set(totals.track_size(track) as u64);
2661			}
2662			metrics.accounts_total.set(accounts_count as u64);
2663			metrics.expired_total.set(expired_count as u64);
2664			metrics.held_statements.set(held_count as u64);
2665			metrics.capacity_statements.set(capacity_statements as u64);
2666			metrics.capacity_bytes.set(capacity_bytes as u64);
2667		});
2668
2669		log::trace!(
2670			target: LOG_TARGET,
2671			"Completed store maintenance. Purged: {}, Active: {}, Expired: {}",
2672			deleted_count,
2673			active_count,
2674			expired_count
2675		);
2676	}
2677
2678	fn timestamp(&self) -> u64 {
2679		self.time_override.unwrap_or_else(|| {
2680			std::time::SystemTime::now()
2681				.duration_since(std::time::UNIX_EPOCH)
2682				.unwrap_or_default()
2683				.as_secs()
2684		})
2685	}
2686
2687	#[cfg(test)]
2688	fn set_time(&mut self, time: u64) {
2689		self.time_override = Some(time);
2690	}
2691
2692	/// Returns `self` as [`StatementStoreExt`].
2693	pub fn as_statement_store_ext(self: Arc<Self>) -> StatementStoreExt {
2694		StatementStoreExt::new(self)
2695	}
2696
2697	/// Return information of all known statements whose decryption key is identified as
2698	/// `dest`. The key must be available to the client.
2699	fn posted_clear_inner<R>(
2700		&self,
2701		match_all_topics: &[Topic],
2702		dest: [u8; 32],
2703		// Map the statement and the decrypted data to the desired result.
2704		mut map_f: impl FnMut(Statement, Vec<u8>) -> R,
2705	) -> Result<Vec<R>> {
2706		self.collect_statements(
2707			Some(dest),
2708			&OptimizedTopicFilter::MatchAll(match_all_topics.iter().cloned().collect()),
2709			|statement| {
2710				if let (Some(key), Some(_)) = (statement.decryption_key(), statement.data()) {
2711					let public: sp_core::ed25519::Public = UncheckedFrom::unchecked_from(key);
2712					let public: sp_statement_store::ed25519::Public = public.into();
2713					match self.keystore.key_pair::<sp_statement_store::ed25519::Pair>(&public) {
2714						Err(e) => {
2715							log::debug!(
2716								target: LOG_TARGET,
2717								"Keystore error: {:?}, for statement {:?}",
2718								e,
2719								HexDisplay::from(&statement.hash())
2720							);
2721							None
2722						},
2723						Ok(None) => {
2724							log::debug!(
2725								target: LOG_TARGET,
2726								"Keystore is missing key for statement {:?}",
2727								HexDisplay::from(&statement.hash())
2728							);
2729							None
2730						},
2731						Ok(Some(pair)) => match statement.decrypt_private(&pair.into_inner()) {
2732							Ok(r) => r.map(|data| map_f(statement, data)),
2733							Err(e) => {
2734								log::debug!(
2735									target: LOG_TARGET,
2736									"Decryption error: {:?}, for statement {:?}",
2737									e,
2738									HexDisplay::from(&statement.hash())
2739								);
2740								None
2741							},
2742						},
2743					}
2744				} else {
2745					None
2746				}
2747			},
2748		)
2749	}
2750}
2751
2752impl StatementStore for Store {
2753	/// Return every statement currently in the store.
2754	///
2755	/// Takes a read lock on the query index, iterates all indexed hashes, reads and SCALE-decodes
2756	/// each statement from the `STATEMENTS` database column, and skips any entry that fails to
2757	/// decode.
2758	fn statements(&self) -> Result<Vec<(Hash, Statement)>> {
2759		let hashes = self.enumerate_hashes()?;
2760		let mut result = Vec::with_capacity(hashes.len());
2761		for hash in hashes {
2762			let Some(encoded) =
2763				self.db.get(col::STATEMENTS, &hash).map_err(|e| Error::Db(e.to_string()))?
2764			else {
2765				continue;
2766			};
2767			match Statement::decode(&mut encoded.as_slice()) {
2768				Ok(statement) => result.push((hash, statement)),
2769				Err(_) => log::error!(
2770					target: LOG_TARGET,
2771					"Corrupt statement {:?}",
2772					HexDisplay::from(&hash)
2773				),
2774			}
2775		}
2776		Ok(result)
2777	}
2778
2779	fn take_recent_statements(&self) -> Result<Vec<(u64, Hash, Statement)>> {
2780		// `recent` is cleared only once the bodies are in hand, and the taken statements are held
2781		// under the same lock, so the sweep never sees one off `recent` and unheld.
2782		let recent = self.query_index.read().recent_snapshot();
2783		let mut result = Vec::with_capacity(recent.len());
2784		for (&hash, &seq) in &recent {
2785			let Some(encoded) =
2786				self.db.get(col::STATEMENTS, &hash).map_err(|e| Error::Db(e.to_string()))?
2787			else {
2788				continue;
2789			};
2790			match Statement::decode(&mut encoded.as_slice()) {
2791				Ok(statement) => result.push((seq, hash, statement)),
2792				Err(_) => log::error!(
2793					target: LOG_TARGET,
2794					"Corrupt statement {:?}",
2795					HexDisplay::from(&hash)
2796				),
2797			}
2798		}
2799		{
2800			let mut query_index = self.query_index.write();
2801			query_index.clear_propagated(&recent);
2802			if self.retention_fn.get().is_some() {
2803				query_index.hold(result.iter().map(|(_, hash, _)| hash));
2804			}
2805		}
2806		result.sort_unstable_by_key(|(seq, ..)| *seq);
2807		Ok(result)
2808	}
2809
2810	fn hold_statements(&self, hashes: &[Hash]) {
2811		if self.retention_fn.get().is_some() {
2812			self.query_index.write().hold(hashes);
2813		}
2814	}
2815
2816	fn release_statements(&self, hashes: &[Hash]) {
2817		if self.retention_fn.get().is_some() {
2818			self.query_index.write().release(hashes);
2819		}
2820	}
2821
2822	fn admission_watermark(&self) -> Result<u64> {
2823		// Every admission commits its journal row under the submit-index write lock before
2824		// releasing it, so a lock holder observes every sequence number below `next_seq`
2825		// already persisted. The mirror advances after that commit, so the same holds for it.
2826		Ok(self.admission_watermark.load(AtomicOrdering::Acquire))
2827	}
2828
2829	fn admitted_statements(
2830		&self,
2831		mut cursor: u64,
2832		watermark: u64,
2833		scan_limit: usize,
2834		filter: &mut dyn FnMut(&Hash, &[u8], &Statement) -> FilterDecision,
2835	) -> Result<AdmittedBatch> {
2836		// A cursor past the watermark would snap back to it below, moving the caller's
2837		// position backwards.
2838		debug_assert!(
2839			cursor <= watermark,
2840			"admission cursor {cursor} must not exceed the watermark {watermark}"
2841		);
2842		debug_assert!(scan_limit > 0, "a zero scan limit cannot advance the cursor");
2843		let mut statements = Vec::new();
2844		let mut aborted = false;
2845		let mut scanned = 0usize;
2846		let mut iter = self.db.iter(col::ADMISSION_SEQ).map_err(|e| Error::Db(e.to_string()))?;
2847		iter.seek(&cursor.to_be_bytes()).map_err(|e| Error::Db(e.to_string()))?;
2848
2849		while let Some((key, value)) = iter.next().map_err(|e| Error::Db(e.to_string()))? {
2850			let seq = u64::from_be_bytes(
2851				key.try_into().map_err(|_| Error::Db("Invalid admission sequence key".into()))?,
2852			);
2853			if seq >= watermark {
2854				cursor = watermark;
2855				break;
2856			}
2857			if scanned == scan_limit {
2858				aborted = true;
2859				break;
2860			}
2861			scanned += 1;
2862			let hash: Hash = value
2863				.as_slice()
2864				.try_into()
2865				.map_err(|_| Error::Db("Invalid admission sequence hash".into()))?;
2866			let next_cursor = seq.saturating_add(1);
2867			let Some(encoded) =
2868				self.db.get(col::STATEMENTS, &hash).map_err(|e| Error::Db(e.to_string()))?
2869			else {
2870				cursor = next_cursor;
2871				continue;
2872			};
2873			// The admission row is deleted atomically with the statement it admits, so re-reading
2874			// it after the body confirms that this sequence number is still the statement's
2875			// current admission (and not a stale row of an evicted-and-readmitted statement).
2876			let is_current = self
2877				.db
2878				.get(col::ADMISSION_SEQ, &seq.to_be_bytes())
2879				.map_err(|e| Error::Db(e.to_string()))?
2880				.is_some_and(|current| current.as_slice() == hash.as_slice());
2881			if !is_current {
2882				cursor = next_cursor;
2883				continue;
2884			}
2885			let statement = match Statement::decode(&mut encoded.as_slice()) {
2886				Ok(statement) => statement,
2887				Err(e) => {
2888					log::error!(
2889						target: LOG_TARGET,
2890						"Could not decode statement {:?} while walking the admission journal: {:?}",
2891						HexDisplay::from(&hash),
2892						e
2893					);
2894					cursor = next_cursor;
2895					continue;
2896				},
2897			};
2898			match filter(&hash, &encoded, &statement) {
2899				FilterDecision::Skip => cursor = next_cursor,
2900				FilterDecision::Take => {
2901					statements.push((hash, statement));
2902					cursor = next_cursor;
2903				},
2904				FilterDecision::Abort => {
2905					aborted = true;
2906					break;
2907				},
2908			}
2909		}
2910
2911		// The journal can end below the watermark when the newest admissions were removed;
2912		// nothing is left to visit there, so the walk is complete.
2913		if !aborted && cursor < watermark {
2914			cursor = watermark;
2915		}
2916		Ok(AdmittedBatch { statements, cursor, done: cursor >= watermark })
2917	}
2918
2919	/// Read a single statement directly from the `STATEMENTS` database column by hash and decode
2920	/// it. Returns `Ok(None)` if no statement with that hash is stored.
2921	fn statement(&self, hash: &Hash) -> Result<Option<Statement>> {
2922		Ok(
2923			match self
2924				.db
2925				.get(col::STATEMENTS, hash.as_slice())
2926				.map_err(|e| Error::Db(e.to_string()))?
2927			{
2928				Some(entry) => {
2929					log::trace!(
2930						target: LOG_TARGET,
2931						"Queried statement {:?}",
2932						HexDisplay::from(hash)
2933					);
2934					Some(Statement::decode(&mut entry.as_slice()).map_err(|e| {
2935						log::error!(
2936							target: LOG_TARGET,
2937							"Corrupt statement {:?}",
2938							HexDisplay::from(hash)
2939						);
2940						Error::Decode(e.to_string())
2941					})?)
2942				},
2943				None => {
2944					log::trace!(
2945						target: LOG_TARGET,
2946						"Queried missing statement {:?}",
2947						HexDisplay::from(hash)
2948					);
2949					None
2950				},
2951			},
2952		)
2953	}
2954
2955	fn has_statement(&self, hash: &Hash) -> bool {
2956		match self.db.get_size(col::STATEMENTS, hash.as_slice()) {
2957			Ok(size) => size.is_some(),
2958			Err(e) => {
2959				log::debug!(
2960					target: LOG_TARGET,
2961					"Error checking statement presence {:?}: {:?}",
2962					HexDisplay::from(hash),
2963					e
2964				);
2965				false
2966			},
2967		}
2968	}
2969
2970	fn statements_by_hashes(
2971		&self,
2972		hashes: &[Hash],
2973		filter: &mut dyn FnMut(&Hash, &[u8], &Statement) -> FilterDecision,
2974	) -> Result<(Vec<(Hash, Statement)>, usize)> {
2975		let mut result = Vec::new();
2976		let mut processed = 0;
2977		for hash in hashes {
2978			processed += 1;
2979			let Some(encoded) =
2980				self.db.get(col::STATEMENTS, hash).map_err(|e| Error::Db(e.to_string()))?
2981			else {
2982				continue;
2983			};
2984			let Ok(statement) = Statement::decode(&mut encoded.as_slice()) else {
2985				log::error!(target: LOG_TARGET, "Corrupt statement {:?}", HexDisplay::from(hash));
2986				continue;
2987			};
2988			match filter(hash, &encoded, &statement) {
2989				FilterDecision::Skip => {},
2990				FilterDecision::Take => {
2991					result.push((*hash, statement));
2992				},
2993				FilterDecision::Abort => {
2994					// We did not process it :)
2995					processed -= 1;
2996					break;
2997				},
2998			}
2999		}
3000
3001		Ok((result, processed))
3002	}
3003
3004	/// Return the `data` of all statements matching all of `match_all_topics` that have no
3005	/// decryption key (i.e. public broadcasts).
3006	///
3007	/// Filters the query index by topic (intersection; an empty list matches every broadcast),
3008	/// reads and decodes each match from the `STATEMENTS` column, and returns the plaintext data,
3009	/// skipping any inconsistent entries.
3010	fn broadcasts(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>> {
3011		self.collect_statements(
3012			None,
3013			&OptimizedTopicFilter::MatchAll(match_all_topics.iter().cloned().collect()),
3014			|statement| statement.into_data(),
3015		)
3016	}
3017
3018	/// Return the (encrypted) `data` of all statements matching all of `match_all_topics` whose
3019	/// decryption key equals `dest`.
3020	///
3021	/// Same filtering and DB read as [`broadcasts`](Self::broadcasts), but keyed on `dest` rather
3022	/// than the absence of a decryption key.
3023	fn posted(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
3024		self.collect_statements(
3025			Some(dest),
3026			&OptimizedTopicFilter::MatchAll(match_all_topics.iter().cloned().collect()),
3027			|statement| statement.into_data(),
3028		)
3029	}
3030
3031	/// Like [`posted`](Self::posted) but returns the decrypted data.
3032	///
3033	/// For each match, looks up the ed25519 key identified by `dest` in the keystore and decrypts
3034	/// the statement data; statements are skipped when the key is unavailable or decryption fails.
3035	fn posted_clear(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
3036		self.posted_clear_inner(match_all_topics, dest, |_statement, data| data)
3037	}
3038
3039	/// Return the full SCALE-encoded statements matching all of `match_all_topics` that have no
3040	/// decryption key (i.e. public broadcasts).
3041	///
3042	/// Takes a read lock on the query index and filters by the absence of a decryption key and
3043	/// topics (intersection / AND — an empty topic list matches every broadcast), then reads,
3044	/// decodes and re-encodes each match from the `STATEMENTS` column, skipping inconsistent
3045	/// entries. Unlike [`broadcasts`](Self::broadcasts), which returns only the data, this returns
3046	/// the whole statement.
3047	fn broadcasts_stmt(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>> {
3048		self.collect_statements(
3049			None,
3050			&OptimizedTopicFilter::MatchAll(match_all_topics.iter().cloned().collect()),
3051			|statement| Some(statement.encode()),
3052		)
3053	}
3054
3055	/// Return the full SCALE-encoded statements matching all of `match_all_topics` whose decryption
3056	/// key equals `dest`.
3057	///
3058	/// Takes a read lock on the query index and filters by decryption key (`dest`) and topics
3059	/// (intersection / AND — an empty topic list matches every statement keyed to `dest`), then
3060	/// reads, decodes and re-encodes each match from the `STATEMENTS` column, skipping inconsistent
3061	/// entries. Unlike [`posted`](Self::posted), which returns only the (still-encrypted) data,
3062	/// this returns the whole statement.
3063	fn posted_stmt(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
3064		self.collect_statements(
3065			Some(dest),
3066			&OptimizedTopicFilter::MatchAll(match_all_topics.iter().cloned().collect()),
3067			|statement| Some(statement.encode()),
3068		)
3069	}
3070
3071	/// Return, for each statement matching all of `match_all_topics` whose decryption key equals
3072	/// `dest`, the SCALE-encoded statement concatenated with its decrypted data.
3073	///
3074	/// Filters as [`posted_stmt`](Self::posted_stmt), then for each match looks up the ed25519 key
3075	/// identified by `dest` in the keystore and decrypts the statement data, appending the
3076	/// plaintext to the encoded statement. Statements are skipped when the key is unavailable or
3077	/// decryption fails.
3078	fn posted_clear_stmt(
3079		&self,
3080		match_all_topics: &[Topic],
3081		dest: [u8; 32],
3082	) -> Result<Vec<Vec<u8>>> {
3083		self.posted_clear_inner(match_all_topics, dest, |statement, data| {
3084			let mut res = Vec::with_capacity(statement.size_hint() + data.len());
3085			statement.encode_to(&mut res);
3086			res.extend_from_slice(&data);
3087			res
3088		})
3089	}
3090
3091	/// Submit a statement to the store, validating it and enforcing constraints.
3092	///
3093	/// Runs the following pipeline, short-circuiting on the first failure:
3094	/// 1. **Expiry check** — reject if the statement's expiration timestamp is already in the past
3095	///    (`SubmitResult::Invalid(InvalidReason::AlreadyExpired)`).
3096	/// 2. **Encoding size check** — reject if the encoded statement exceeds [`MAX_STATEMENT_SIZE`]
3097	///    (`InvalidReason::EncodingTooLarge`).
3098	/// 3. **Topics check** — reject a statement without topics (`InvalidReason::NoTopics`).
3099	/// 4. **Duplicate check** — a statement already in the store is reported `Known`: the hash
3100	///    covers the whole content, so a duplicate carries nothing to renew. A recently evicted
3101	///    statement may be resubmitted (renewed) by `Chain` and `Local` sources but not by
3102	///    `Network` (`SubmitResult::KnownExpired`).
3103	/// 5. **Proof & signature** — extract the account from the proof and verify the signature
3104	///    (`InvalidReason::NoProof` / `InvalidReason::BadProof`).
3105	/// 6. **Allowance** — read the account's allowance (`StatementAllowance`: max count and size)
3106	///    directly from chain state at the best block (via the `statement_allowance_key` storage
3107	///    key — not a runtime call); reject with `SubmitResult::Rejected(NoAllowance)` if none is
3108	///    set. The best block is used for responsiveness. Limit enforcement takes the larger of the
3109	///    best and the finalized allowance, so a statement accepted here outlives the finality lag;
3110	///    it is evicted later if the allowance it relied on leaves the best chain or a lower
3111	///    allowance is finalized.
3112	/// 7. **Constraint check & eviction** — check the account's record, enforcing per-account
3113	///    limits (count, size, one statement per channel, higher priority replaces lower) and
3114	///    global limits ([`DEFAULT_MAX_TOTAL_STATEMENTS`], [`DEFAULT_MAX_TOTAL_SIZE`]), evicting
3115	///    lower-priority statements of the same account as needed (`SubmitResult::Rejected` if it
3116	///    still does not fit).
3117	/// 8. **Persist** — commit the statement, its index rows, any evictions and the refreshed
3118	///    counters atomically, then update the caches and the in-memory query index.
3119	///
3120	/// Returns `SubmitResult::New` on success.
3121	fn submit(&self, statement: Statement, source: StatementSource) -> SubmitResult {
3122		let mask = self
3123			.retention_fn
3124			.get()
3125			.map_or_else(RetentionReasonMask::persistent, |resolver| resolver(&statement));
3126		let track = RetentionTrack::from(mask);
3127
3128		let _histogram_submit_start_timer = self.metrics.start_submit_timer();
3129		let hash = statement.hash();
3130		// Get unix timestamp
3131		if statement.is_expired(self.timestamp()) {
3132			log::debug!(
3133				target: LOG_TARGET,
3134				"Statement is already expired: {:?}",
3135				HexDisplay::from(&hash),
3136			);
3137			let reason = InvalidReason::AlreadyExpired;
3138			self.metrics.report(|metrics| {
3139				metrics.validations_invalid.with_label_values(&[reason.label()]).inc();
3140			});
3141			return SubmitResult::Invalid(reason);
3142		}
3143		let encoded_size = statement.encoded_size();
3144		if encoded_size > MAX_STATEMENT_SIZE {
3145			log::debug!(
3146				target: LOG_TARGET,
3147				"Statement is too big for propogation: {:?} ({}/{} bytes)",
3148				HexDisplay::from(&hash),
3149				statement.encoded_size(),
3150				MAX_STATEMENT_SIZE
3151			);
3152			let reason = InvalidReason::EncodingTooLarge {
3153				submitted_size: encoded_size,
3154				max_size: MAX_STATEMENT_SIZE,
3155			};
3156			self.metrics.report(|metrics| {
3157				metrics.validations_invalid.with_label_values(&[reason.label()]).inc();
3158			});
3159			return SubmitResult::Invalid(reason);
3160		}
3161		if statement.topics().is_empty() {
3162			log::debug!(
3163				target: LOG_TARGET,
3164				"Statement has no topics: {:?}",
3165				HexDisplay::from(&hash),
3166			);
3167			let reason = InvalidReason::NoTopics;
3168			self.metrics.report(|metrics| {
3169				metrics.validations_invalid.with_label_values(&[reason.label()]).inc();
3170			});
3171			return SubmitResult::Invalid(reason);
3172		}
3173
3174		// Deduplicate against statements we already store (in-memory submit index) or have recently
3175		// evicted (on-disk evicted journal). Both checks are lock-free; a duplicate slipping
3176		// past this early check is caught again under the write lock below.
3177		if self.db.get_size(col::STATEMENTS, hash.as_slice()).ok().flatten().is_some() {
3178			if !source.can_be_resubmitted() {
3179				self.metrics.report(|metrics| {
3180					metrics.known_statements.with_label_values(&["known"]).inc();
3181				});
3182				return SubmitResult::Known;
3183			}
3184		} else if self.db.get_size(col::EXPIRED, hash.as_slice()).ok().flatten().is_some() {
3185			if !source.can_be_resubmitted() {
3186				self.metrics.report(|metrics| {
3187					metrics.known_statements.with_label_values(&["known_expired"]).inc();
3188				});
3189				return SubmitResult::KnownExpired;
3190			}
3191		}
3192
3193		let Some(account_id) = statement.account_id() else {
3194			log::debug!(
3195				target: LOG_TARGET,
3196				"Statement validation failed: Missing proof ({:?})",
3197				HexDisplay::from(&hash),
3198			);
3199			let reason = InvalidReason::NoProof;
3200			self.metrics.report(|metrics| {
3201				metrics.validations_invalid.with_label_values(&[reason.label()]).inc();
3202			});
3203			return SubmitResult::Invalid(reason);
3204		};
3205
3206		match statement.verify_signature() {
3207			SignatureVerificationResult::Valid(_) => {},
3208			SignatureVerificationResult::Invalid => {
3209				log::debug!(
3210					target: LOG_TARGET,
3211					"Statement validation failed: BadProof, {:?}",
3212					HexDisplay::from(&hash),
3213				);
3214				let reason = InvalidReason::BadProof;
3215				self.metrics.report(|metrics| {
3216					metrics.validations_invalid.with_label_values(&[reason.label()]).inc();
3217				});
3218				return SubmitResult::Invalid(reason);
3219			},
3220			SignatureVerificationResult::NoSignature => {
3221				log::debug!(
3222					target: LOG_TARGET,
3223					"Statement validation failed: NoProof, {:?}",
3224					HexDisplay::from(&hash),
3225				);
3226				let reason = InvalidReason::NoProof;
3227				self.metrics.report(|metrics| {
3228					metrics.validations_invalid.with_label_values(&[reason.label()]).inc();
3229				});
3230				return SubmitResult::Invalid(reason);
3231			},
3232		};
3233
3234		// Check statement allowance for the account and evict statements if necessary to make room
3235		// for the new statement. We use the best block for allowance checks to allow for more
3236		// up-to-date allowances. This means that in some cases, a statement may be accepted but
3237		// then later evicted when we enforce limits, if the best_hash does not make it into the
3238		// finalized chain, but this is an acceptable tradeoff for better responsiveness to
3239		// allowance changes.
3240		let validation = match (self.read_allowance_fn)(&account_id, AllowanceBlock::Best) {
3241			Ok(Some(allowance)) if !allowance.is_depleted() => allowance,
3242			Ok(Some(_)) | Ok(None) => {
3243				log::debug!(
3244					target: LOG_TARGET,
3245					"Account {} has no usable statement allowance",
3246					HexDisplay::from(&account_id),
3247				);
3248				let reason = RejectionReason::NoAllowance;
3249				self.metrics.report(|metrics| {
3250					metrics.rejections.with_label_values(&[reason.label()]).inc();
3251				});
3252				return SubmitResult::Rejected(reason);
3253			},
3254			Err(e) => {
3255				log::debug!(
3256					target: LOG_TARGET,
3257					"Reading statement allowance for account {} failed",
3258					HexDisplay::from(&account_id),
3259				);
3260				self.metrics.report(|metrics| {
3261					metrics.internal_errors.with_label_values(&["read_allowance"]).inc();
3262				});
3263				return SubmitResult::InternalError(e);
3264			},
3265		};
3266
3267		let current_time = self.timestamp();
3268		let seq = {
3269			let mut submit_index = self.submit_index.write();
3270
3271			// Re-check for a duplicate under the write lock. Without
3272			// it, a double insertion would double-count the statement in the global counters and
3273			// in the account's quota.
3274			match self.db.get_size(col::STATEMENTS, hash.as_slice()) {
3275				Ok(Some(_)) => {
3276					self.metrics.report(|metrics| {
3277						metrics.known_statements.with_label_values(&["known"]).inc();
3278					});
3279					return SubmitResult::Known;
3280				},
3281				Ok(None) => {},
3282				Err(e) => {
3283					self.metrics.report(|metrics| {
3284						metrics.internal_errors.with_label_values(&["db_read"]).inc();
3285					});
3286					return SubmitResult::InternalError(Error::Db(e.to_string()));
3287				},
3288			}
3289
3290			let statement_len = statement.data_len();
3291			// The account record is materialised only when the constraint check actually needs
3292			// it: a channel-less statement from an account whose cached summary shows headroom
3293			// is admitted without touching the account's on-disk index at all, and an oversize
3294			// statement is rejected by `plan_insert` before it ever looks at the record.
3295			let oversize = statement_len > validation.max_size as usize;
3296			let cached = submit_index.account_statements.peek(&account_id).is_some();
3297			let summary_admits = !cached &&
3298				statement.channel().is_none() &&
3299				submit_index.summaries.peek(&account_id).is_some_and(|summary| {
3300					summary.count < validation.max_count as usize &&
3301						summary.data_size + statement_len <= validation.max_size as usize
3302				}) && submit_index
3303				.exceeded_limit(&submit_index.totals_after_insert(track, statement_len, []), track)
3304				.is_none();
3305			let loaded_record = if cached || summary_admits || oversize {
3306				None
3307			} else {
3308				match self.load_account_record(&account_id) {
3309					Ok(record) => Some(record),
3310					Err(e) => {
3311						self.metrics.report(|metrics| {
3312							metrics.internal_errors.with_label_values(&["db_read"]).inc();
3313						});
3314						return SubmitResult::InternalError(e);
3315					},
3316				}
3317			};
3318
3319			let empty_record = StatementsForAccount::default();
3320			let record = loaded_record
3321				.as_ref()
3322				.or_else(|| submit_index.account_statements.peek(&account_id))
3323				.unwrap_or(&empty_record);
3324			let plan = match submit_index.plan_insert(
3325				record,
3326				hash,
3327				&statement,
3328				track,
3329				&account_id,
3330				&validation,
3331				current_time,
3332			) {
3333				Ok(plan) => plan,
3334				Err(reason) => {
3335					self.metrics.report(|metrics| {
3336						metrics.rejections.with_label_values(&[reason.label()]).inc();
3337					});
3338					// The rejection left the store untouched, so a record loaded for planning
3339					// still mirrors the disk. Cache it: rejections cost the sender nothing, and
3340					// dropping the record here would let rejected submissions against a large
3341					// account rescan its whole on-disk index, under the write lock, on every
3342					// attempt.
3343					if let Some(record) = loaded_record {
3344						submit_index.cache_record_with_summary(account_id, record);
3345					}
3346					return SubmitResult::Rejected(reason);
3347				},
3348			};
3349
3350			// Build the whole admission as one atomic commit
3351			let mut commit = Vec::new();
3352			commit.push((col::STATEMENTS, hash.to_vec(), Some(statement.encode())));
3353			// Local and chain submissions ignore an eviction ban, so a banned statement can come
3354			// back. The ban must go with it: if the statement is later removed without a ban, the
3355			// stale ban would still reject peers redelivering it.
3356			let stale_ban = if source.can_be_resubmitted() {
3357				match self.db.get(col::EXPIRED, hash.as_slice()) {
3358					Ok(stale_ban) => stale_ban,
3359					Err(e) => {
3360						self.metrics.report(|metrics| {
3361							metrics.internal_errors.with_label_values(&["db_read"]).inc();
3362						});
3363						return SubmitResult::InternalError(Error::Db(e.to_string()));
3364					},
3365				}
3366			} else {
3367				None
3368			};
3369			let stale_banned_at = stale_ban.and_then(|stale_ban| {
3370				let banned_at =
3371					<(Hash, u64)>::decode(&mut stale_ban.as_slice()).ok().map(|(_, at)| at);
3372				if banned_at.is_none() {
3373					log::error!(
3374						target: LOG_TARGET,
3375						"Corrupt evicted journal entry {:?}",
3376						HexDisplay::from(&hash)
3377					);
3378				}
3379				banned_at
3380			});
3381			if let Some(stale_banned_at) = stale_banned_at {
3382				let expires_at = Expiry(statement.expiry()).get_expiration_timestamp_secs();
3383				let purge_after_sec = submit_index.config.purge_after_sec;
3384				let purge_at = stale_banned_at.saturating_add(purge_after_sec).min(expires_at);
3385				commit.push((col::EXPIRED, hash.to_vec(), None));
3386				commit.push((col::INDEX_EVICTED, evicted_index_key(purge_at, &hash), None));
3387				// The startup migration writes journal keys without the expiry cap, so that key
3388				// is cleared too.
3389				let migrated_purge_at = stale_banned_at.saturating_add(purge_after_sec);
3390				if migrated_purge_at != purge_at {
3391					commit.push((
3392						col::INDEX_EVICTED,
3393						evicted_index_key(migrated_purge_at, &hash),
3394						None,
3395					));
3396				}
3397			}
3398			commit.push((col::ADMISSION_SEQ, plan.seq.to_be_bytes().to_vec(), Some(hash.to_vec())));
3399			commit.extend(statement_index_ops(&hash, &statement, true));
3400			let details = EntryDetails {
3401				channel: statement.channel(),
3402				data_len: statement_len,
3403				admission_seq: plan.seq,
3404				track,
3405			};
3406			commit.extend(account_index_ops(
3407				&account_id,
3408				Expiry(statement.expiry()),
3409				&hash,
3410				Some(&details),
3411			));
3412
3413			let mut evicted_statements = Vec::new();
3414			for (key, evicted_details) in &plan.evicted {
3415				commit.push((col::STATEMENTS, key.hash.to_vec(), None));
3416				commit.push((
3417					col::ADMISSION_SEQ,
3418					evicted_details.admission_seq.to_be_bytes().to_vec(),
3419					None,
3420				));
3421				commit.extend(account_index_ops(&account_id, key.expiry, &key.hash, None));
3422				match self.db.get(col::STATEMENTS, &key.hash) {
3423					Ok(Some(encoded)) => match Statement::decode(&mut encoded.as_slice()) {
3424						Ok(evicted_statement) => {
3425							commit.extend(statement_index_ops(
3426								&key.hash,
3427								&evicted_statement,
3428								false,
3429							));
3430							evicted_statements.push(evicted_statement);
3431						},
3432						Err(_) => log::error!(
3433							target: LOG_TARGET,
3434							"Corrupt statement {:?}",
3435							HexDisplay::from(&key.hash)
3436						),
3437					},
3438					Ok(None) => log::error!(
3439						target: LOG_TARGET,
3440						"Missing body of the indexed statement {:?}",
3441						HexDisplay::from(&key.hash)
3442					),
3443					Err(e) => log::warn!(
3444						target: LOG_TARGET,
3445						"Could not read evicted statement {:?} to clear its index: {:?}",
3446						HexDisplay::from(&key.hash),
3447						e
3448					),
3449				}
3450			}
3451			for (h, purge_at) in &plan.banned {
3452				commit.push((col::EXPIRED, h.to_vec(), Some((h, current_time).encode())));
3453				commit.push((
3454					col::INDEX_EVICTED,
3455					evicted_index_key(*purge_at, h),
3456					Some(INDEX_EMPTY_VALUE.to_vec()),
3457				));
3458			}
3459			commit.push(SubmitIndex::counters_op(&plan.totals, plan.seq.saturating_add(1)));
3460
3461			if let Err(e) = self.db.commit(commit) {
3462				log::debug!(
3463					target: LOG_TARGET,
3464					"Statement validation failed: database error {}, {:?}",
3465					e,
3466					statement
3467				);
3468				self.metrics.report(|metrics| {
3469					metrics.internal_errors.with_label_values(&["db_commit"]).inc();
3470				});
3471				return SubmitResult::InternalError(Error::Db(e.to_string()));
3472			}
3473			let seq = plan.seq;
3474			submit_index.apply_insert(&account_id, loaded_record, hash, &statement, track, &plan);
3475			if stale_banned_at.is_some() {
3476				submit_index.evicted_count = submit_index.evicted_count.saturating_sub(1);
3477			}
3478			// The query-index bookkeeping is applied under the same lock that ordered the
3479			// commit: a concurrent removal racing a resubmission of the same statement can then
3480			// never apply its stale update on top of this newer one (#12624). The notification
3481			// stays outside — its ordering is protected by the sequence watermark, not the lock.
3482			{
3483				let mut query_index = self.query_index.write();
3484				for evicted_statement in &evicted_statements {
3485					query_index.note_remove(&evicted_statement.hash(), evicted_statement);
3486				}
3487				query_index.forget_retention_tracking(plan.evicted.iter().map(|(key, _)| key));
3488				query_index.note_insert(hash, &statement, plan.seq, track);
3489			}
3490			seq
3491		}; // Release submit index lock
3492		self.subscription_manager.notify(seq, statement);
3493		self.metrics.report(|metrics| {
3494			metrics.submitted_statements.with_label_values(&[mask.label()]).inc();
3495		});
3496		log::trace!(target: LOG_TARGET, "Statement submitted: {:?}", HexDisplay::from(&hash));
3497		SubmitResult::New
3498	}
3499
3500	/// Soft-delete a statement by hash: drop it and its index rows from the database, and record
3501	/// it in the `EXPIRED` column so it cannot be re-accepted until its purge period elapses (see
3502	/// [`maintain`](Self::maintain)). No-op if the statement is unknown.
3503	fn remove(&self, hash: &Hash) -> Result<()> {
3504		self.remove_statement(hash, Resubmission::Banned).map(|_| ())
3505	}
3506
3507	/// Remove every statement authored by `who`, applying the same soft-delete as
3508	/// [`remove`](Self::remove) to each, in a single atomic commit.
3509	fn remove_by(&self, who: [u8; 32]) -> Result<()> {
3510		let current_time = self.timestamp();
3511		{
3512			let mut submit_index = self.submit_index.write();
3513			// The account's statements, from the cached record when there is one, else from the
3514			// on-disk index.
3515			let entries: Vec<(PriorityKey, EntryDetails)> =
3516				match submit_index.account_statements.peek(&who) {
3517					Some(record) => {
3518						record.by_priority.iter().map(|(key, details)| (*key, *details)).collect()
3519					},
3520					None => self.load_account_entries(&who)?,
3521				};
3522			if entries.is_empty() {
3523				return Ok(());
3524			}
3525
3526			let mut commit = Vec::new();
3527			let mut removed_statements = Vec::new();
3528			let mut banned_count = 0usize;
3529			for (key, details) in &entries {
3530				commit.push((col::STATEMENTS, key.hash.to_vec(), None));
3531				commit.push((
3532					col::ADMISSION_SEQ,
3533					details.admission_seq.to_be_bytes().to_vec(),
3534					None,
3535				));
3536				commit.extend(account_index_ops(&who, key.expiry, &key.hash, None));
3537				if current_time < key.expiry.get_expiration_timestamp_secs() {
3538					let purge_at = key
3539						.expiry
3540						.get_expiration_timestamp_secs()
3541						.min(current_time.saturating_add(submit_index.config.purge_after_sec));
3542					commit.push((
3543						col::EXPIRED,
3544						key.hash.to_vec(),
3545						Some((key.hash, current_time).encode()),
3546					));
3547					commit.push((
3548						col::INDEX_EVICTED,
3549						evicted_index_key(purge_at, &key.hash),
3550						Some(INDEX_EMPTY_VALUE.to_vec()),
3551					));
3552					banned_count += 1;
3553				}
3554				match self.db.get(col::STATEMENTS, &key.hash) {
3555					Ok(Some(encoded)) => match Statement::decode(&mut encoded.as_slice()) {
3556						Ok(statement) => {
3557							commit.extend(statement_index_ops(&key.hash, &statement, false));
3558							removed_statements.push((key.hash, statement));
3559						},
3560						Err(_) => log::error!(
3561							target: LOG_TARGET,
3562							"Corrupt statement {:?}",
3563							HexDisplay::from(&key.hash)
3564						),
3565					},
3566					Ok(None) => log::error!(
3567						target: LOG_TARGET,
3568						"Missing body of the indexed statement {:?}",
3569						HexDisplay::from(&key.hash)
3570					),
3571					Err(e) => {
3572						log::warn!(
3573							target: LOG_TARGET,
3574							"Could not read statement {:?} to clear its index: {:?}",
3575							HexDisplay::from(&key.hash),
3576							e
3577						);
3578					},
3579				}
3580			}
3581			let totals =
3582				submit_index.totals_after_removal(entries.iter().map(|(_, details)| details));
3583			commit.push(SubmitIndex::counters_op(&totals, submit_index.next_seq));
3584			self.db.commit(commit).map_err(|e| {
3585				log::debug!(
3586					target: LOG_TARGET,
3587					"Error removing statement: database error {}, remove by {:?}",
3588					e,
3589					HexDisplay::from(&who),
3590				);
3591
3592				Error::Db(e.to_string())
3593			})?;
3594			submit_index.apply_account_removal(&who, totals, banned_count);
3595			// Applied under the same lock that ordered the commit (#12624).
3596			let mut query_index = self.query_index.write();
3597			for (hash, statement) in &removed_statements {
3598				query_index.note_remove(hash, statement);
3599			}
3600			query_index.forget_retention_tracking(entries.iter().map(|(key, _)| key));
3601		}
3602		Ok(())
3603	}
3604
3605	fn subscription_topics(&self) -> HashSet<Topic> {
3606		self.subscription_manager.subscription_topics()
3607	}
3608}
3609
3610/// RAII guard that deregisters a subscription snapshot scan (see [`SubmitIndex::begin_scan`] /
3611/// [`SubmitIndex::end_scan`]) when dropped, so the `recent_seqs` window is always released — on the
3612/// happy path, on an early `?` return, or on a panic during the snapshot.
3613struct ScanGuard<'a> {
3614	store: &'a Store,
3615	watermark: u64,
3616}
3617
3618impl Drop for ScanGuard<'_> {
3619	fn drop(&mut self) {
3620		self.store.submit_index.write().end_scan(self.watermark);
3621	}
3622}
3623
3624impl StatementStoreSubscriptionApi for Store {
3625	fn subscribe_statement(
3626		&self,
3627		topic_filter: OptimizedTopicFilter,
3628	) -> Result<(Vec<Vec<u8>>, async_channel::Sender<StatementEvent>, SubscriptionStatementsStream)>
3629	{
3630		// Avoid overlap between the subscribe-time snapshot and live delivery using a
3631		// sequence-number watermark. Under the submit-index write lock, atomically with respect
3632		// to sequence assignment, capture the current boundary `W` and enqueue the subscription
3633		// registration tagged with `W`.
3634		let (subscription_sender, subscription_stream, watermark) = {
3635			let mut submit_index = self.submit_index.write();
3636			let watermark = submit_index.begin_scan();
3637			let (sender, stream) =
3638				self.subscription_manager.subscribe(topic_filter.clone(), watermark);
3639			(sender, stream, watermark)
3640		};
3641		let _scan_guard = ScanGuard { store: self, watermark };
3642
3643		let mut hashes = HashSet::new();
3644		self.iterate_with(None, &topic_filter, |hash| {
3645			hashes.insert(*hash);
3646			Ok(())
3647		})?;
3648
3649		let hashes: Vec<Hash> = {
3650			let submit_index = self.submit_index.read();
3651			hashes
3652				.into_iter()
3653				.filter(|hash| submit_index.seq_covered_by_snapshot(hash, watermark))
3654				.collect()
3655		};
3656
3657		let mut existing_statements = Vec::with_capacity(hashes.len());
3658		for hash in hashes {
3659			if let Some(entry) = self.read_statement_encoded(&hash)? {
3660				existing_statements.push(entry);
3661			}
3662		}
3663
3664		if existing_statements.is_empty() {
3665			subscription_sender
3666				.send_blocking(StatementEvent::NewStatements {
3667					statements: vec![],
3668					remaining: Some(0),
3669				})
3670				.ok();
3671		}
3672		Ok((existing_statements, subscription_sender, subscription_stream))
3673	}
3674}
3675
3676impl Store {
3677	/// Removes a statement, reporting whether one was actually removed. With
3678	/// [`Resubmission::Banned`], an unexpired statement cannot be re-accepted until its purge
3679	/// period elapses.
3680	///
3681	/// `Ok(false)` means no (decodable) statement is stored under `hash` — it was already gone,
3682	/// or its body is corrupt. A corrupt body cannot be tied back to its index rows, so nothing
3683	/// is removed at all.
3684	fn remove_statement(&self, hash: &Hash, resubmission: Resubmission) -> Result<bool> {
3685		let mut submit_index = self.submit_index.write();
3686		self.remove_statement_locked(&mut submit_index, hash, resubmission)
3687	}
3688
3689	/// [`Self::remove_statement`] for a caller already holding the submit-index write lock.
3690	fn remove_statement_locked(
3691		&self,
3692		submit_index: &mut SubmitIndex,
3693		hash: &Hash,
3694		resubmission: Resubmission,
3695	) -> Result<bool> {
3696		let current_time = self.timestamp();
3697		{
3698			// The body is read under the submit-index lock, so it cannot change under our feet
3699			let Some(encoded) =
3700				self.db.get(col::STATEMENTS, hash).map_err(|e| Error::Db(e.to_string()))?
3701			else {
3702				return Ok(false);
3703			};
3704			let Some((statement, account)) = Statement::decode(&mut encoded.as_slice())
3705				.ok()
3706				.and_then(|statement| statement.account_id().map(|account| (statement, account)))
3707			else {
3708				// A corrupt body cannot be tied back to its index rows
3709				log::error!(target: LOG_TARGET, "Corrupt statement {:?}", HexDisplay::from(hash));
3710				return Ok(false);
3711			};
3712			let expiry = Expiry(statement.expiry());
3713			let account_key = account_index_key(&account, expiry, hash);
3714			let details = self
3715				.db
3716				.get(col::INDEX_BY_ACCOUNT, &account_key)
3717				.map_err(|e| Error::Db(e.to_string()))?
3718				.as_deref()
3719				.and_then(|mut value| EntryDetails::decode(&mut value).ok());
3720
3721			let mut commit = vec![(col::STATEMENTS, hash.to_vec(), None)];
3722			commit.extend(statement_index_ops(hash, &statement, false));
3723			commit.extend(account_index_ops(&account, expiry, hash, None));
3724			match &details {
3725				Some(details) => commit.push((
3726					col::ADMISSION_SEQ,
3727					details.admission_seq.to_be_bytes().to_vec(),
3728					None,
3729				)),
3730				// Nothing points at the admission entry any more; replay skips it once the body
3731				// is gone.
3732				None => log::error!(
3733					target: LOG_TARGET,
3734					"Missing or corrupt account index entry for statement {:?}",
3735					HexDisplay::from(hash)
3736				),
3737			}
3738			let banned =
3739				resubmission.is_banned() && current_time < expiry.get_expiration_timestamp_secs();
3740			if banned {
3741				let purge_at = expiry
3742					.get_expiration_timestamp_secs()
3743					.min(current_time.saturating_add(submit_index.config.purge_after_sec));
3744				commit.push((col::EXPIRED, hash.to_vec(), Some((hash, current_time).encode())));
3745				commit.push((
3746					col::INDEX_EVICTED,
3747					evicted_index_key(purge_at, hash),
3748					Some(INDEX_EMPTY_VALUE.to_vec()),
3749				));
3750			}
3751			let mut totals = submit_index.totals;
3752			let data_len = match &details {
3753				Some(details) => {
3754					totals.sub(details.track, details.data_len);
3755					details.data_len
3756				},
3757				None => {
3758					totals.sub_unattributed(statement.data_len());
3759					statement.data_len()
3760				},
3761			};
3762			commit.push(SubmitIndex::counters_op(&totals, submit_index.next_seq));
3763			if let Err(e) = self.db.commit(commit) {
3764				log::debug!(
3765					target: LOG_TARGET,
3766					"Error removing statement: database error {}, {:?}",
3767					e,
3768					HexDisplay::from(hash),
3769				);
3770				return Err(Error::Db(e.to_string()));
3771			}
3772			submit_index.apply_removal(
3773				&account,
3774				&PriorityKey { hash: *hash, expiry },
3775				totals,
3776				data_len,
3777				banned,
3778			);
3779			self.query_index.write().note_remove(hash, &statement);
3780			log::trace!(target: LOG_TARGET, "Expired statement {:?}", HexDisplay::from(hash));
3781		}
3782		Ok(true)
3783	}
3784
3785	/// Moves a stored statement onto `track` by rewriting its account index row and the totals
3786	/// under the submit-index write lock, `false` when the statement cannot be tied to its row.
3787	fn retrack_statement_locked(
3788		&self,
3789		submit_index: &mut SubmitIndex,
3790		statement: &Statement,
3791		track: RetentionTrack,
3792	) -> Result<bool> {
3793		let hash = statement.hash();
3794		let Some(account) = statement.account_id() else {
3795			log::error!(target: LOG_TARGET, "Unsigned statement {:?}", HexDisplay::from(&hash));
3796			return Ok(false);
3797		};
3798		let expiry = Expiry(statement.expiry());
3799		let account_key = account_index_key(&account, expiry, &hash);
3800		let Some(details) = self
3801			.db
3802			.get(col::INDEX_BY_ACCOUNT, &account_key)
3803			.map_err(|e| Error::Db(e.to_string()))?
3804			.as_deref()
3805			.and_then(|mut value| EntryDetails::decode(&mut value).ok())
3806		else {
3807			log::error!(
3808				target: LOG_TARGET,
3809				"Missing or corrupt account index entry for statement {:?}",
3810				HexDisplay::from(&hash)
3811			);
3812			return Ok(false);
3813		};
3814		if details.track == track {
3815			return Ok(true);
3816		}
3817		let mut totals = submit_index.totals;
3818		totals.sub(details.track, details.data_len);
3819		totals.add(track, details.data_len);
3820		self.db
3821			.commit([
3822				(
3823					col::INDEX_BY_ACCOUNT,
3824					account_key,
3825					Some(EntryDetails { track, ..details }.encode()),
3826				),
3827				SubmitIndex::counters_op(&totals, submit_index.next_seq),
3828			])
3829			.map_err(|e| Error::Db(e.to_string()))?;
3830		submit_index.apply_retrack(
3831			&account,
3832			&PriorityKey { hash, expiry },
3833			details.track,
3834			track,
3835			details.data_len,
3836		);
3837		Ok(true)
3838	}
3839
3840	/// Reports an [`col::INDEX_BY_EXPIRY`] row that survived its statement,
3841	/// re-checking under the submit lock — every commit happens under it — that the row is indeed
3842	/// orphaned: a concurrent removal deletes the row along with its statement, and a concurrent
3843	/// re-admission of the same statement recreates the same content-derived key together with a
3844	/// body.
3845	fn report_orphan_expiry_row(&self, expiry: u64, hash: &Hash) {
3846		let _submit_index = self.submit_index.write();
3847		let body = self.db.get_size(col::STATEMENTS, hash.as_slice());
3848		let row = self.db.get(col::INDEX_BY_EXPIRY, &expiry_index_key(Expiry(expiry), hash));
3849		match (body, row) {
3850			(Ok(None), Ok(Some(_))) => log::error!(
3851				target: LOG_TARGET,
3852				"Orphan expiry index row for statement {:?}",
3853				HexDisplay::from(hash)
3854			),
3855			(Err(e), _) | (_, Err(e)) => {
3856				log::debug!(target: LOG_TARGET, "Error checking statement presence: {:?}", e)
3857			},
3858			_ => {},
3859		}
3860	}
3861
3862	fn register_replay(&self, enqueue: &mut dyn FnMut(u64) -> bool) -> Result<Option<u64>> {
3863		let registered = {
3864			let submit_index = self.submit_index.write();
3865			let watermark = submit_index.next_seq;
3866			enqueue(watermark).then_some(watermark)
3867		}; // Release submit index lock
3868		Ok(registered)
3869	}
3870
3871	fn replay_batch(
3872		&self,
3873		filter: &OptimizedTopicFilter,
3874		cursor: u64,
3875		watermark: u64,
3876	) -> Result<ReplayBatch> {
3877		let mut statements = Vec::new();
3878		let mut chunk_bytes = 0usize;
3879		// Replay batches are pulled by a local subscription task, not a remote peer, so the
3880		// walk is not budgeted.
3881		let batch = StatementStore::admitted_statements(
3882			self,
3883			cursor,
3884			watermark,
3885			usize::MAX,
3886			&mut |_, encoded, statement| {
3887				if !filter.matches(statement) {
3888					return FilterDecision::Skip;
3889				}
3890				if !statements.is_empty() && chunk_bytes + encoded.len() > REPLAY_CHUNK_RAW_BYTES {
3891					return FilterDecision::Abort;
3892				}
3893				chunk_bytes += encoded.len();
3894				statements.push(encoded.to_vec());
3895				// The encoded bytes are already captured above, so the statement is reported
3896				// as skipped to keep the walk from cloning it into the returned batch too.
3897				FilterDecision::Skip
3898			},
3899		)?;
3900		Ok(ReplayBatch { statements, cursor: batch.cursor, done: batch.done })
3901	}
3902}
3903
3904impl MultiFilterSubscriptionApi for Arc<Store> {
3905	fn create_subscription(&self) -> (SubscriptionHandle, MultiFilterEventStream) {
3906		let inner =
3907			Arc::new(parking_lot::Mutex::new(crate::subscription::SubscriptionHandleInner::new()));
3908		let snapshot_provider: Arc<dyn ReplaySnapshotProvider> = Arc::new(Arc::downgrade(self));
3909		let (sub_id, stream) = self.subscription_manager.subscribe_empty(snapshot_provider.clone());
3910
3911		let handle = SubscriptionHandle {
3912			sub_id,
3913			inner,
3914			matchers: self.subscription_manager.matchers(),
3915			snapshot_provider,
3916		};
3917		(handle, stream)
3918	}
3919}
3920
3921#[cfg(test)]
3922impl Store {
3923	/// Number of hashes currently in the on-disk evicted journal (per the in-memory counter).
3924	fn evicted_count(&self) -> usize {
3925		self.submit_index.read().evicted_count
3926	}
3927
3928	/// Whether `hash` is currently banned from re-acceptance (present in the evicted journal).
3929	fn is_evicted(&self, hash: &Hash) -> bool {
3930		self.db.get_size(col::EXPIRED, hash.as_slice()).ok().flatten().is_some()
3931	}
3932
3933	/// Whether the on-disk topic index links `topic` to `hash`.
3934	fn index_has_topic(&self, topic: &Topic, hash: &Hash) -> bool {
3935		self.index_set_contains(&IndexSet::Topic(*topic), hash).unwrap_or(false)
3936	}
3937
3938	/// Whether the on-disk decryption-key index links `key` to `hash`.
3939	fn index_has_dec_key(&self, key: &Option<DecryptionKey>, hash: &Hash) -> bool {
3940		self.index_set_contains(&IndexSet::DecKey(*key), hash).unwrap_or(false)
3941	}
3942
3943	/// Number of stored statements, per the in-memory counter.
3944	fn statement_count(&self) -> usize {
3945		self.submit_index.read().statement_count()
3946	}
3947
3948	/// Whether the details cache currently holds `who`'s record.
3949	fn details_cached(&self, who: &AccountId) -> bool {
3950		self.submit_index.read().account_statements.peek(who).is_some()
3951	}
3952
3953	/// Whether the summary cache currently holds `who`'s entry.
3954	fn summary_cached(&self, who: &AccountId) -> bool {
3955		self.submit_index.read().summaries.peek(who).is_some()
3956	}
3957
3958	/// Total stored data size, per the in-memory counter.
3959	fn total_size(&self) -> usize {
3960		self.submit_index.read().total_size()
3961	}
3962
3963	/// Whether `who` has at least one statement in the on-disk account index.
3964	fn has_account(&self, who: &AccountId) -> bool {
3965		self.next_account_from(who).expect("failed to read the account index") == Some(*who)
3966	}
3967
3968	/// Number of accounts in the on-disk account index.
3969	fn account_count(&self) -> usize {
3970		self.count_accounts().expect("failed to count the accounts")
3971	}
3972
3973	/// Inserts `statement` bypassing signature and allowance validation — used to seed
3974	/// over-allowance states that `submit` would refuse to create.
3975	fn force_insert(&self, statement: &Statement) {
3976		let hash = statement.hash();
3977		let account = statement.account_id().expect("test statements are signed; qed");
3978		let mut submit_index = self.submit_index.write();
3979		let seq = submit_index.next_seq;
3980		let track = RetentionTrack::Persistent;
3981		let details = EntryDetails {
3982			channel: statement.channel(),
3983			data_len: statement.data_len(),
3984			admission_seq: seq,
3985			track,
3986		};
3987		let mut commit = vec![
3988			(col::STATEMENTS, hash.to_vec(), Some(statement.encode())),
3989			(col::ADMISSION_SEQ, seq.to_be_bytes().to_vec(), Some(hash.to_vec())),
3990		];
3991		commit.extend(statement_index_ops(&hash, statement, true));
3992		commit.extend(account_index_ops(
3993			&account,
3994			Expiry(statement.expiry()),
3995			&hash,
3996			Some(&details),
3997		));
3998		let totals = submit_index.totals_after_insert(track, statement.data_len(), []);
3999		commit.push(SubmitIndex::counters_op(&totals, seq.saturating_add(1)));
4000		self.db.commit(commit).expect("failed to commit the statement");
4001		let plan = InsertPlan { seq, evicted: Vec::new(), banned: Vec::new(), totals };
4002		submit_index.apply_insert(&account, None, hash, statement, track, &plan);
4003		self.query_index
4004			.write()
4005			.note_insert(hash, statement, seq, RetentionTrack::Persistent);
4006	}
4007}
4008
4009#[cfg(test)]
4010mod tests {
4011
4012	use crate::{
4013		col, evicted_index_key, parse_time_index_key, AllowanceBlock, Config, Error,
4014		PrometheusMetrics, PrometheusRegistry, QueryIndex, Resubmission, RetentionReasonMask,
4015		RetentionTrack, Store, StoreTotals, V2DhtConfig, INDEX_EMPTY_VALUE, KEY_VERSION,
4016	};
4017	use sc_keystore::Keystore;
4018	use sp_core::{Decode, Encode, Pair};
4019	use sp_statement_store::{
4020		AccountId, Channel, DecryptionKey, FilterDecision, InvalidReason, OptimizedTopicFilter,
4021		Proof, RejectionReason, Statement, StatementAllowance, StatementSource, StatementStore,
4022		SubmitResult, Topic,
4023	};
4024	use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
4025
4026	type Extrinsic = sp_runtime::OpaqueExtrinsic;
4027	type Hash = sp_core::H256;
4028	type Hashing = sp_runtime::traits::BlakeTwo256;
4029	type BlockNumber = u64;
4030	type Header = sp_runtime::generic::Header<BlockNumber, Hashing>;
4031	type Block = sp_runtime::generic::Block<Header, Extrinsic>;
4032
4033	const TEST_BEST_BLOCK_HASH: [u8; 32] = [1u8; 32];
4034
4035	/// Maximum seed value used by `account(seed)`/`statement(seed, ...)` in this
4036	/// test module. Increase if you add tests that pass larger seed values to
4037	/// `statement(..)`. The reverse-lookup table in `TestClient::storage` is
4038	/// populated lazily for seeds in `0..=MAX_TEST_ACCOUNT_SEED`.
4039	const MAX_TEST_ACCOUNT_SEED: u64 = 64;
4040
4041	/// Reverse-lookup table from a real sr25519 public key back to the synthetic
4042	/// `u64` seed it was derived from. Populated once with seeds in
4043	/// `0..=MAX_TEST_ACCOUNT_SEED`, then consulted by `TestClient::storage` to
4044	/// figure out which allowance bucket to return for a given account.
4045	fn account_seed_table() -> &'static std::collections::BTreeMap<AccountId, u64> {
4046		use std::sync::OnceLock;
4047		static TABLE: OnceLock<std::collections::BTreeMap<AccountId, u64>> = OnceLock::new();
4048		TABLE.get_or_init(|| {
4049			let mut t = std::collections::BTreeMap::new();
4050			for seed in 0..=MAX_TEST_ACCOUNT_SEED {
4051				t.insert(account_keypair(seed).public().0, seed);
4052			}
4053			t
4054		})
4055	}
4056
4057	#[derive(Clone)]
4058	pub(crate) struct TestClient;
4059
4060	pub(crate) type TestBackend = sc_client_api::in_mem::Backend<Block>;
4061
4062	impl sc_client_api::StorageProvider<Block, TestBackend> for TestClient {
4063		fn storage(
4064			&self,
4065			_hash: Hash,
4066			key: &sc_client_api::StorageKey,
4067		) -> sp_blockchain::Result<Option<sc_client_api::StorageData>> {
4068			use sp_statement_store::StatementAllowance;
4069
4070			assert_eq!(&key.0[0..21], b":statement_allowance:" as &[u8],);
4071
4072			// Recover the synthetic test seed from the account id. Unknown accounts
4073			// (e.g. //Alice for `signed_statement`) fall through to a generic default.
4074			let account_bytes: AccountId = key.0[21..53].try_into().unwrap();
4075			let seed = account_seed_table().get(&account_bytes).copied();
4076			let allowance = match seed {
4077				// Account 0 has no allowance (used to test eviction of all statements)
4078				Some(0) => return Ok(None),
4079				Some(1) => StatementAllowance::new(1, 1000),
4080				Some(2) => StatementAllowance::new(2, 1000),
4081				Some(3) => StatementAllowance::new(3, 1000),
4082				Some(4) => StatementAllowance::new(4, 1000),
4083				Some(42) => StatementAllowance::new(42, (42 * crate::MAX_STATEMENT_SIZE) as u32),
4084				// Depleted on one axis, but still present in state.
4085				Some(50) => StatementAllowance::new(0, 1000),
4086				Some(51) => StatementAllowance::new(5, 0),
4087				Some(_) | None => StatementAllowance::new(100, 1000),
4088			};
4089			Ok(Some(sc_client_api::StorageData(allowance.encode())))
4090		}
4091
4092		fn storage_hash(
4093			&self,
4094			_hash: Hash,
4095			_key: &sc_client_api::StorageKey,
4096		) -> sp_blockchain::Result<Option<Hash>> {
4097			unimplemented!()
4098		}
4099
4100		fn storage_keys(
4101			&self,
4102			_hash: Hash,
4103			_prefix: Option<&sc_client_api::StorageKey>,
4104			_start_key: Option<&sc_client_api::StorageKey>,
4105		) -> sp_blockchain::Result<
4106			sc_client_api::backend::KeysIter<
4107				<TestBackend as sc_client_api::Backend<Block>>::State,
4108				Block,
4109			>,
4110		> {
4111			unimplemented!()
4112		}
4113
4114		fn storage_pairs(
4115			&self,
4116			_hash: Hash,
4117			_prefix: Option<&sc_client_api::StorageKey>,
4118			_start_key: Option<&sc_client_api::StorageKey>,
4119		) -> sp_blockchain::Result<
4120			sc_client_api::backend::PairsIter<
4121				<TestBackend as sc_client_api::Backend<Block>>::State,
4122				Block,
4123			>,
4124		> {
4125			unimplemented!()
4126		}
4127
4128		fn child_storage(
4129			&self,
4130			_hash: Hash,
4131			_child_info: &sc_client_api::ChildInfo,
4132			_key: &sc_client_api::StorageKey,
4133		) -> sp_blockchain::Result<Option<sc_client_api::StorageData>> {
4134			unimplemented!()
4135		}
4136
4137		fn child_storage_keys(
4138			&self,
4139			_hash: Hash,
4140			_child_info: sc_client_api::ChildInfo,
4141			_prefix: Option<&sc_client_api::StorageKey>,
4142			_start_key: Option<&sc_client_api::StorageKey>,
4143		) -> sp_blockchain::Result<
4144			sc_client_api::backend::KeysIter<
4145				<TestBackend as sc_client_api::Backend<Block>>::State,
4146				Block,
4147			>,
4148		> {
4149			unimplemented!()
4150		}
4151
4152		fn child_storage_hash(
4153			&self,
4154			_hash: Hash,
4155			_child_info: &sc_client_api::ChildInfo,
4156			_key: &sc_client_api::StorageKey,
4157		) -> sp_blockchain::Result<Option<Hash>> {
4158			unimplemented!()
4159		}
4160
4161		fn closest_merkle_value(
4162			&self,
4163			_hash: Hash,
4164			_key: &sc_client_api::StorageKey,
4165		) -> sp_blockchain::Result<Option<sc_client_api::MerkleValue<Hash>>> {
4166			unimplemented!()
4167		}
4168
4169		fn child_closest_merkle_value(
4170			&self,
4171			_hash: Hash,
4172			_child_info: &sc_client_api::ChildInfo,
4173			_key: &sc_client_api::StorageKey,
4174		) -> sp_blockchain::Result<Option<sc_client_api::MerkleValue<Hash>>> {
4175			unimplemented!()
4176		}
4177	}
4178
4179	impl sp_blockchain::HeaderBackend<Block> for TestClient {
4180		fn header(&self, _hash: Hash) -> sp_blockchain::Result<Option<Header>> {
4181			unimplemented!()
4182		}
4183		fn info(&self) -> sp_blockchain::Info<Block> {
4184			sp_blockchain::Info {
4185				best_hash: TEST_BEST_BLOCK_HASH.into(),
4186				best_number: 0,
4187				genesis_hash: Default::default(),
4188				finalized_hash: TEST_BEST_BLOCK_HASH.into(),
4189				finalized_number: 1,
4190				finalized_state: None,
4191				number_leaves: 0,
4192				block_gap: None,
4193			}
4194		}
4195		fn status(&self, _hash: Hash) -> sp_blockchain::Result<sp_blockchain::BlockStatus> {
4196			unimplemented!()
4197		}
4198		fn number(&self, _hash: Hash) -> sp_blockchain::Result<Option<BlockNumber>> {
4199			unimplemented!()
4200		}
4201		fn hash(&self, _number: BlockNumber) -> sp_blockchain::Result<Option<Hash>> {
4202			unimplemented!()
4203		}
4204	}
4205
4206	fn test_store() -> (Store, tempfile::TempDir) {
4207		test_store_with_config(Default::default())
4208	}
4209
4210	fn test_store_with_config(config: Config) -> (Store, tempfile::TempDir) {
4211		sp_tracing::init_for_tests();
4212		let temp_dir = tempfile::Builder::new().tempdir().expect("Error creating test dir");
4213
4214		let client = std::sync::Arc::new(TestClient);
4215		let mut path: std::path::PathBuf = temp_dir.path().into();
4216		path.push("db");
4217		let keystore = std::sync::Arc::new(sc_keystore::LocalKeystore::in_memory());
4218		let store = Store::new::<Block, TestClient, TestBackend>(
4219			&path,
4220			config,
4221			client,
4222			keystore,
4223			None,
4224			Box::new(sp_core::testing::TaskExecutor::new()),
4225		)
4226		.unwrap();
4227		(store, temp_dir) // return order is important. Store must be dropped before TempDir
4228	}
4229
4230	/// Closes `store` and opens the database in `temp` again with the default config.
4231	fn reopen(store: Store, temp: &tempfile::TempDir) -> Store {
4232		let keystore = store.keystore.clone();
4233		drop(store);
4234		let mut path: std::path::PathBuf = temp.path().into();
4235		path.push("db");
4236		Store::new::<Block, TestClient, TestBackend>(
4237			&path,
4238			Default::default(),
4239			std::sync::Arc::new(TestClient),
4240			keystore,
4241			None,
4242			Box::new(sp_core::testing::TaskExecutor::new()),
4243		)
4244		.unwrap()
4245	}
4246
4247	pub fn signed_statement(data: u8) -> Statement {
4248		signed_statement_with_topics(data, &[default_topic()], None)
4249	}
4250
4251	fn signed_statement_with_topics(
4252		data: u8,
4253		topics: &[Topic],
4254		dec_key: Option<DecryptionKey>,
4255	) -> Statement {
4256		let mut statement = Statement::new();
4257		statement.set_plain_data(vec![data]);
4258		statement.set_expiry(u64::MAX);
4259
4260		for i in 0..topics.len() {
4261			statement.set_topic(i, topics[i]);
4262		}
4263		if let Some(key) = dec_key {
4264			statement.set_decryption_key(key);
4265		}
4266		let kp = sp_core::ed25519::Pair::from_string("//Alice", None).unwrap();
4267		statement.sign_ed25519_private(&kp);
4268		statement
4269	}
4270
4271	/// The topic of test statements that need none in particular.
4272	fn default_topic() -> Topic {
4273		Topic::from([0xff; 32])
4274	}
4275
4276	fn topic(data: u64) -> Topic {
4277		let mut bytes = [0u8; 32];
4278		bytes[0..8].copy_from_slice(&data.to_le_bytes());
4279		Topic::from(bytes)
4280	}
4281
4282	fn dec_key(data: u64) -> DecryptionKey {
4283		let mut dec_key: DecryptionKey = Default::default();
4284		dec_key[0..8].copy_from_slice(&data.to_le_bytes());
4285		dec_key
4286	}
4287
4288	/// Returns the deterministic ed25519 keypair used to author statements for the
4289	/// synthetic test account `seed`.
4290	///
4291	/// Uses ed25519 rather than sr25519 because schnorrkel signing is non-deterministic
4292	/// (the signature depends on RNG state), so calling `statement(id, prio, ch, len)`
4293	/// twice would produce different hashes. Several tests compare statement hashes
4294	/// against pre-computed values; ed25519 keeps those comparisons stable.
4295	fn account_keypair(seed: u64) -> sp_core::ed25519::Pair {
4296		sp_core::ed25519::Pair::from_string(&format!("//StatementAccount{seed}"), None)
4297			.expect("Derivation path is valid; qed")
4298	}
4299
4300	fn account(id: u64) -> AccountId {
4301		account_keypair(id).public().0
4302	}
4303
4304	/// Signs `stmt` with `account_id`'s test keypair. Tests that build a statement via
4305	/// `unsigned_statement(..)` and then mutate it call this exactly once at the end.
4306	fn sign_with(stmt: &mut Statement, account_id: u64) {
4307		stmt.sign_ed25519_private(&account_keypair(account_id));
4308	}
4309
4310	fn channel(id: u64) -> Channel {
4311		let mut channel: Channel = Default::default();
4312		channel[0..8].copy_from_slice(&id.to_le_bytes());
4313		channel
4314	}
4315
4316	/// Builds a test statement without signing it. Use this when a test needs to mutate
4317	/// the statement (encryption, expiry change, topic update, etc.) before submission —
4318	/// call `sign_with(&mut stmt, account_id)` once after all mutations.
4319	fn unsigned_statement(
4320		account_id: u64,
4321		priority: u32,
4322		c: Option<u64>,
4323		data_len: usize,
4324	) -> Statement {
4325		assert!(
4326			account_id <= MAX_TEST_ACCOUNT_SEED,
4327			"account_id {account_id} exceeds MAX_TEST_ACCOUNT_SEED ({MAX_TEST_ACCOUNT_SEED}); \
4328			 raise the constant if you need a wider range",
4329		);
4330		let mut statement = Statement::new();
4331		let mut data = Vec::new();
4332		data.resize(data_len, 0);
4333		statement.set_plain_data(data);
4334		statement.set_expiry_from_parts(u32::MAX, priority);
4335		statement.set_topic(0, default_topic());
4336		if let Some(c) = c {
4337			statement.set_channel(channel(c));
4338		}
4339		statement
4340	}
4341
4342	fn statement(account_id: u64, priority: u32, c: Option<u64>, data_len: usize) -> Statement {
4343		let mut statement = unsigned_statement(account_id, priority, c, data_len);
4344		sign_with(&mut statement, account_id);
4345		statement
4346	}
4347
4348	#[test]
4349	fn submit_one() {
4350		let (store, _temp) = test_store();
4351		let statement0 = signed_statement(0);
4352		assert_eq!(store.submit(statement0, StatementSource::Network), SubmitResult::New);
4353		let statement1 = statement(1, 1, None, 0);
4354		assert_eq!(store.submit(statement1, StatementSource::Network), SubmitResult::New);
4355	}
4356
4357	#[test]
4358	fn depleted_count_allowance_admits_nothing() {
4359		let (store, _temp) = test_store();
4360		// Account 50 has `max_count: 0`.
4361		let result = store.submit(statement(50, 1, None, 100), StatementSource::Network);
4362		assert_eq!(result, SubmitResult::Rejected(RejectionReason::NoAllowance));
4363		assert_eq!(store.statement_count(), 0);
4364		assert_eq!(store.total_size(), 0);
4365	}
4366
4367	#[test]
4368	fn depleted_size_allowance_admits_nothing() {
4369		let (store, _temp) = test_store();
4370		// Account 51 has `max_size: 0`; a zero-length statement passes the length gate.
4371		let result = store.submit(statement(51, 1, None, 0), StatementSource::Network);
4372		assert_eq!(result, SubmitResult::Rejected(RejectionReason::NoAllowance));
4373		assert_eq!(store.statement_count(), 0);
4374		assert_eq!(store.total_size(), 0);
4375	}
4376
4377	#[test]
4378	fn save_and_load_statements() {
4379		let (store, temp) = test_store();
4380		let statement0 = signed_statement(0);
4381		let statement1 = signed_statement(1);
4382		let statement2 = signed_statement(2);
4383		assert_eq!(store.submit(statement0.clone(), StatementSource::Network), SubmitResult::New);
4384		assert_eq!(store.submit(statement1.clone(), StatementSource::Network), SubmitResult::New);
4385		assert_eq!(store.submit(statement2.clone(), StatementSource::Network), SubmitResult::New);
4386		assert_eq!(store.statements().unwrap().len(), 3);
4387		assert_eq!(store.broadcasts(&[]).unwrap().len(), 3);
4388		assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1.clone()));
4389		let store = reopen(store, &temp);
4390		assert_eq!(store.statements().unwrap().len(), 3);
4391		assert_eq!(store.broadcasts(&[]).unwrap().len(), 3);
4392		assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1));
4393	}
4394
4395	#[test]
4396	fn admission_seq_is_monotonic_across_restarts() {
4397		// Sequence numbers must never be reused, even when the highest-numbered statements were
4398		// removed before a restart: a replay cursor as high as a dead sequence number would
4399		// silently skip any statement re-admitted under it.
4400		let (store, temp) = test_store();
4401		let first = signed_statement(10);
4402		let second = signed_statement(11);
4403		assert_eq!(store.submit(first.clone(), StatementSource::Network), SubmitResult::New);
4404		assert_eq!(store.submit(second.clone(), StatementSource::Network), SubmitResult::New);
4405		assert_eq!(
4406			store.db.get(col::ADMISSION_SEQ, &0u64.to_be_bytes()).unwrap(),
4407			Some(first.hash().to_vec())
4408		);
4409		assert_eq!(
4410			store.db.get(col::ADMISSION_SEQ, &1u64.to_be_bytes()).unwrap(),
4411			Some(second.hash().to_vec())
4412		);
4413		store.remove(&second.hash()).unwrap();
4414		assert_eq!(
4415			store.db.get(col::ADMISSION_SEQ, &0u64.to_be_bytes()).unwrap(),
4416			Some(first.hash().to_vec())
4417		);
4418		assert_eq!(store.db.get(col::ADMISSION_SEQ, &1u64.to_be_bytes()).unwrap(), None);
4419		let store = reopen(store, &temp);
4420		assert_eq!(store.submit_index.read().next_seq, 2);
4421
4422		let replay = store.replay_batch(&OptimizedTopicFilter::Any, 0, 2).unwrap();
4423		assert_eq!(replay.statements, vec![first.encode()]);
4424		assert!(replay.done);
4425
4426		// The removed statement's sequence number stays dead; the next admission claims a fresh
4427		// one.
4428		let third = signed_statement(12);
4429		assert_eq!(store.submit(third.clone(), StatementSource::Network), SubmitResult::New);
4430		assert_eq!(store.db.get(col::ADMISSION_SEQ, &1u64.to_be_bytes()).unwrap(), None);
4431		assert_eq!(
4432			store.db.get(col::ADMISSION_SEQ, &2u64.to_be_bytes()).unwrap(),
4433			Some(third.hash().to_vec())
4434		);
4435	}
4436
4437	#[test]
4438	fn lagging_counters_row_does_not_reuse_admission_seqs() {
4439		// A counters row lagging the admission journal is impossible on a database written by
4440		// this version (they are committed atomically); should one appear anyway, startup must
4441		// recover `next_seq` from the journal instead of reusing live sequence numbers.
4442		let (store, temp) = test_store();
4443		let first = signed_statement(1);
4444		let second = signed_statement(2);
4445		assert_eq!(store.submit(first.clone(), StatementSource::Network), SubmitResult::New);
4446		assert_eq!(store.submit(second.clone(), StatementSource::Network), SubmitResult::New);
4447		// Corrupt the counters row: keep the totals, rewind the sequence counter.
4448		let (totals, _) = <(StoreTotals, u64)>::decode(
4449			&mut store.db.get(col::META, crate::KEY_COUNTERS).unwrap().unwrap().as_slice(),
4450		)
4451		.unwrap();
4452		store
4453			.db
4454			.commit([(col::META, crate::KEY_COUNTERS.to_vec(), Some((totals, 0u64).encode()))])
4455			.unwrap();
4456		let store = reopen(store, &temp);
4457		assert_eq!(store.submit_index.read().next_seq, 2);
4458
4459		// A new admission claims a fresh sequence number; the existing entries are untouched.
4460		let third = signed_statement(3);
4461		assert_eq!(store.submit(third.clone(), StatementSource::Network), SubmitResult::New);
4462		assert_eq!(
4463			store.db.get(col::ADMISSION_SEQ, &0u64.to_be_bytes()).unwrap(),
4464			Some(first.hash().to_vec())
4465		);
4466		assert_eq!(
4467			store.db.get(col::ADMISSION_SEQ, &1u64.to_be_bytes()).unwrap(),
4468			Some(second.hash().to_vec())
4469		);
4470		assert_eq!(
4471			store.db.get(col::ADMISSION_SEQ, &2u64.to_be_bytes()).unwrap(),
4472			Some(third.hash().to_vec())
4473		);
4474	}
4475
4476	#[test]
4477	fn statement_without_admission_entry_is_restored_by_migration() {
4478		// Admission entries are committed atomically with statement bodies, so a
4479		// current-version database cannot lose one short of external tampering. Statements
4480		// missing an admission entry (a database written before the entries existed) get one
4481		// from the version migration, which rebuilds every derived column from the bodies.
4482		let (store, temp) = test_store();
4483		let statement = signed_statement_with_topics(20, &[topic(1)], None);
4484		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New);
4485		// Drop the admission entry, leaving the body behind, and rewind the database version so
4486		// the next start migrates.
4487		store
4488			.db
4489			.commit([
4490				(col::ADMISSION_SEQ, 0u64.to_be_bytes().to_vec(), None),
4491				(col::META, KEY_VERSION.to_vec(), Some(1u32.to_le_bytes().to_vec())),
4492			])
4493			.unwrap();
4494		let filter = OptimizedTopicFilter::MatchAny([topic(1)].into_iter().collect());
4495		assert!(store.replay_batch(&filter, 0, 1).unwrap().statements.is_empty());
4496		let store = reopen(store, &temp);
4497
4498		let watermark = store.submit_index.read().next_seq;
4499		assert_eq!(watermark, 1);
4500		assert_eq!(
4501			store.replay_batch(&filter, 0, watermark).unwrap().statements,
4502			vec![statement.encode()]
4503		);
4504	}
4505
4506	#[test]
4507	fn admission_cursor_resumes_from_the_middle_of_the_range() {
4508		let (store, _temp) = test_store();
4509		let first = signed_statement(1);
4510		let second = signed_statement(2);
4511		let third = signed_statement(3);
4512		for statement in [&first, &second, &third] {
4513			assert_eq!(
4514				store.submit(statement.clone(), StatementSource::Network),
4515				SubmitResult::New
4516			);
4517		}
4518		let batch = store.replay_batch(&OptimizedTopicFilter::Any, 1, 3).unwrap();
4519		assert_eq!(batch.statements, vec![second.encode(), third.encode()]);
4520		assert_eq!(batch.cursor, 3);
4521		assert!(batch.done);
4522	}
4523
4524	#[test]
4525	fn admission_cursor_replays_only_current_matching_admissions() {
4526		let (store, _temp) = test_store();
4527		let matching = signed_statement_with_topics(20, &[topic(1)], None);
4528		let non_matching = signed_statement_with_topics(21, &[topic(2)], None);
4529		let removed = signed_statement_with_topics(22, &[topic(1)], None);
4530		assert_eq!(store.submit(matching.clone(), StatementSource::Network), SubmitResult::New);
4531		assert_eq!(store.submit(non_matching, StatementSource::Network), SubmitResult::New);
4532		assert_eq!(store.submit(removed.clone(), StatementSource::Network), SubmitResult::New);
4533		store.remove(&removed.hash()).unwrap();
4534
4535		let replay = store
4536			.replay_batch(&OptimizedTopicFilter::MatchAny([topic(1)].into_iter().collect()), 0, 3)
4537			.unwrap();
4538		assert_eq!(replay.statements, vec![matching.encode()]);
4539		assert_eq!(replay.cursor, 3);
4540		assert!(replay.done);
4541	}
4542
4543	#[test]
4544	fn admission_watermark_is_one_past_the_newest_admission() {
4545		let (store, _temp) = test_store();
4546		assert_eq!(store.admission_watermark().unwrap(), 0);
4547
4548		let first = signed_statement(1);
4549		let second = signed_statement(2);
4550		assert_eq!(store.submit(first.clone(), StatementSource::Network), SubmitResult::New);
4551		assert_eq!(store.submit(second, StatementSource::Network), SubmitResult::New);
4552		assert_eq!(store.admission_watermark().unwrap(), 2);
4553
4554		// Sequence numbers are never reused, so a removal leaves the boundary in place.
4555		store.remove(&first.hash()).unwrap();
4556		assert_eq!(store.admission_watermark().unwrap(), 2);
4557	}
4558
4559	#[test]
4560	fn admitted_statements_walk_applies_filter_decisions_and_resumes() {
4561		let (store, _temp) = test_store();
4562		let statements: Vec<_> = (1..=4).map(signed_statement).collect();
4563		for statement in &statements {
4564			assert_eq!(
4565				store.submit(statement.clone(), StatementSource::Network),
4566				SubmitResult::New
4567			);
4568		}
4569		// Seq 1 goes dead, the walk must pass over it.
4570		store.remove(&statements[1].hash()).unwrap();
4571
4572		let batch = store
4573			.admitted_statements(0, 4, usize::MAX, &mut |hash, _encoded, _statement| {
4574				if *hash == statements[0].hash() {
4575					FilterDecision::Skip
4576				} else if *hash == statements[3].hash() {
4577					FilterDecision::Abort
4578				} else {
4579					FilterDecision::Take
4580				}
4581			})
4582			.unwrap();
4583		assert_eq!(batch.statements, vec![(statements[2].hash(), statements[2].clone())]);
4584		// The aborted statement sits at seq 3; the cursor points back at it.
4585		assert_eq!(batch.cursor, 3);
4586		assert!(!batch.done);
4587
4588		// Resuming from the cursor visits the aborted statement first.
4589		let batch = store
4590			.admitted_statements(batch.cursor, 4, usize::MAX, &mut |_, _, _| FilterDecision::Take)
4591			.unwrap();
4592		assert_eq!(batch.statements, vec![(statements[3].hash(), statements[3].clone())]);
4593		assert_eq!(batch.cursor, 4);
4594		assert!(batch.done);
4595	}
4596
4597	#[test]
4598	fn admitted_statements_walk_stops_at_the_scan_limit() {
4599		let (store, _temp) = test_store();
4600		let statements: Vec<_> = (1..=4).map(signed_statement).collect();
4601		for statement in &statements {
4602			assert_eq!(
4603				store.submit(statement.clone(), StatementSource::Network),
4604				SubmitResult::New
4605			);
4606		}
4607
4608		// A filter that takes nothing must still visit no more than `scan_limit` entries.
4609		let mut visited = 0;
4610		let batch = store
4611			.admitted_statements(0, 4, 3, &mut |_, _, _| {
4612				visited += 1;
4613				FilterDecision::Skip
4614			})
4615			.unwrap();
4616		assert!(batch.statements.is_empty());
4617		assert_eq!(visited, 3);
4618		assert_eq!(batch.cursor, 3, "the cursor must sit after the last visited entry");
4619		assert!(!batch.done);
4620
4621		// Resuming from the partial cursor completes the walk.
4622		let batch = store
4623			.admitted_statements(batch.cursor, 4, 3, &mut |_, _, _| FilterDecision::Skip)
4624			.unwrap();
4625		assert!(batch.statements.is_empty());
4626		assert_eq!(batch.cursor, 4);
4627		assert!(batch.done);
4628	}
4629
4630	#[test]
4631	fn take_recent_statements_are_ordered_by_admission() {
4632		let (store, _temp) = test_store();
4633		let statements: Vec<_> = (1..=3).map(signed_statement).collect();
4634		for statement in &statements {
4635			assert_eq!(
4636				store.submit(statement.clone(), StatementSource::Network),
4637				SubmitResult::New
4638			);
4639		}
4640
4641		let recent = store.take_recent_statements().unwrap();
4642		let expected: Vec<_> = statements
4643			.into_iter()
4644			.enumerate()
4645			.map(|(seq, statement)| (seq as u64, statement.hash(), statement))
4646			.collect();
4647		assert_eq!(recent, expected);
4648	}
4649
4650	#[test]
4651	fn migrates_v1_database_to_on_disk_index() {
4652		sp_tracing::init_for_tests();
4653		let temp = tempfile::Builder::new().tempdir().expect("Error creating test dir");
4654		let mut path: std::path::PathBuf = temp.path().into();
4655		path.push("db");
4656		// The store appends `statements` to the path it is given.
4657		let mut db_path = path.clone();
4658		db_path.push("statements");
4659
4660		// One addressed statement (topics 1 & 2, decryption key 9) and one broadcast (topic 1, no
4661		// key).
4662		let addressed = signed_statement_with_topics(1, &[topic(1), topic(2)], Some(dec_key(9)));
4663		let broadcast = signed_statement_with_topics(2, &[topic(1)], None);
4664		let h_addressed = addressed.hash();
4665		let h_broadcast = broadcast.hash();
4666
4667		// A hash seeded into the legacy EXPIRED column, with a deadline far in the future so it
4668		// survives the maintenance pass triggered during migration.
4669		let expired_hash = topic(999);
4670		let expired_ts = 10_000_000_000u64;
4671
4672		// Build a version-1 database by hand: three columns and no on-disk read index.
4673		{
4674			let mut cfg = parity_db::Options::with_columns(&db_path, 3);
4675			let statement_col = &mut cfg.columns[1];
4676			statement_col.ref_counted = false;
4677			statement_col.preimage = true;
4678			statement_col.uniform = true;
4679			let db = parity_db::Db::open_or_create(&cfg).unwrap();
4680			db.commit([
4681				(0u8, b"version".to_vec(), Some(1u32.to_le_bytes().to_vec())),
4682				(1u8, h_addressed.to_vec(), Some(addressed.encode())),
4683				(1u8, h_broadcast.to_vec(), Some(broadcast.encode())),
4684				(2u8, expired_hash.to_vec(), Some((expired_hash, expired_ts).encode())),
4685			])
4686			.unwrap();
4687		}
4688
4689		let open = |path: &std::path::Path| {
4690			Store::new::<Block, TestClient, TestBackend>(
4691				path,
4692				Default::default(),
4693				std::sync::Arc::new(TestClient),
4694				std::sync::Arc::new(sc_keystore::LocalKeystore::in_memory()),
4695				None,
4696				Box::new(sp_core::testing::TaskExecutor::new()),
4697			)
4698			.unwrap()
4699		};
4700
4701		// Re-open through the store: it must add the index columns, rebuild them from the bodies,
4702		// rebuild the evicted journal and admission sequence, and bump the database version.
4703		let store = open(&path);
4704
4705		// Bodies survived.
4706		assert_eq!(store.statements().unwrap().len(), 2);
4707		assert!(store.statement(&h_addressed).unwrap().is_some());
4708		assert!(store.statement(&h_broadcast).unwrap().is_some());
4709
4710		// The read index was rebuilt on disk.
4711		assert!(store.index_has_topic(&topic(1), &h_addressed));
4712		assert!(store.index_has_topic(&topic(1), &h_broadcast));
4713		assert!(store.index_has_topic(&topic(2), &h_addressed));
4714		assert!(store.index_has_dec_key(&Some(dec_key(9)), &h_addressed));
4715		assert!(store.index_has_dec_key(&None, &h_broadcast));
4716		let mut admitted = std::collections::HashSet::new();
4717		let mut iter = store.db.iter(col::ADMISSION_SEQ).unwrap();
4718		iter.seek_to_first().unwrap();
4719		while let Some((_key, value)) = iter.next().unwrap() {
4720			admitted.insert(value.as_slice().try_into().expect("admission hash is 32 bytes"));
4721		}
4722		assert_eq!(admitted, std::collections::HashSet::from([h_addressed, h_broadcast]));
4723		assert_eq!(store.submit_index.read().next_seq, 2);
4724
4725		// And it answers queries: only the broadcast matches topic 1 with no key, only the
4726		// addressed statement matches topic 1 for key 9.
4727		assert_eq!(store.broadcasts(&[topic(1)]).unwrap().len(), 1);
4728		assert_eq!(store.posted(&[topic(1)], dec_key(9)).unwrap().len(), 1);
4729
4730		// The evicted journal was rebuilt from the legacy EXPIRED column.
4731		assert!(store.is_evicted(&expired_hash));
4732		assert_eq!(store.evicted_count(), 1);
4733
4734		// The account and expiry indexes were rebuilt too, along with the counters row.
4735		assert_eq!(store.statement_count(), 2);
4736		assert_eq!(store.total_size(), 2);
4737		assert!(store.has_account(&addressed.account_id().unwrap()));
4738		assert_eq!(store.account_count(), 1);
4739
4740		// The database is now at the current version; re-opening does not migrate again.
4741		drop(store);
4742		let store = open(&path);
4743		assert_eq!(store.statements().unwrap().len(), 2);
4744		assert!(store.index_has_topic(&topic(1), &h_broadcast));
4745		assert!(store.is_evicted(&expired_hash));
4746	}
4747
4748	#[test]
4749	fn interrupted_migration_resumes_preserving_admission_entries() {
4750		// The migration commits in chunks and bumps the version only at the very end, so a crash
4751		// mid-way leaves a version-1 database with some derived rows already written. Re-running
4752		// the migration must preserve the admission entries it already assigned — replay cursors
4753		// depend on them — and rebuild everything else.
4754		sp_tracing::init_for_tests();
4755		let temp = tempfile::Builder::new().tempdir().expect("Error creating test dir");
4756		let mut path: std::path::PathBuf = temp.path().into();
4757		path.push("db");
4758		let mut db_path = path.clone();
4759		db_path.push("statements");
4760
4761		let s1 = signed_statement_with_topics(1, &[topic(1)], None);
4762		let s2 = statement(2, 5, Some(9), 200);
4763
4764		// A version-1 database whose columns were already extended and whose first migration
4765		// attempt committed s1's read-index and admission rows before crashing: the version was
4766		// never bumped.
4767		{
4768			let mut cfg = parity_db::Options::with_columns(&db_path, col::COUNT);
4769			let statement_col = &mut cfg.columns[col::STATEMENTS as usize];
4770			statement_col.ref_counted = false;
4771			statement_col.preimage = true;
4772			statement_col.uniform = true;
4773			for c in crate::BTREE_COLUMNS {
4774				cfg.columns[c as usize].btree_index = true;
4775			}
4776			let db = parity_db::Db::open_or_create(&cfg).unwrap();
4777			let mut commit: Vec<(u8, Vec<u8>, Option<Vec<u8>>)> = vec![
4778				(col::META, b"version".to_vec(), Some(1u32.to_le_bytes().to_vec())),
4779				(col::STATEMENTS, s1.hash().to_vec(), Some(s1.encode())),
4780				(col::STATEMENTS, s2.hash().to_vec(), Some(s2.encode())),
4781				(col::ADMISSION_SEQ, 7u64.to_be_bytes().to_vec(), Some(s1.hash().to_vec())),
4782			];
4783			commit.extend(crate::statement_index_ops(&s1.hash(), &s1, true));
4784			db.commit(commit).unwrap();
4785		}
4786
4787		let store = Store::new::<Block, TestClient, TestBackend>(
4788			&path,
4789			Default::default(),
4790			std::sync::Arc::new(TestClient),
4791			std::sync::Arc::new(sc_keystore::LocalKeystore::in_memory()),
4792			None,
4793			Box::new(sp_core::testing::TaskExecutor::new()),
4794		)
4795		.unwrap();
4796
4797		// Everything was rebuilt: bodies, read index, account and expiry indexes, counters.
4798		assert_eq!(store.statements().unwrap().len(), 2);
4799		assert_eq!(store.statement_count(), 2);
4800		assert_eq!(store.total_size(), 1 + 200);
4801		assert!(store.has_account(&s1.account_id().unwrap()));
4802		assert!(store.has_account(&account(2)));
4803		assert!(store
4804			.db
4805			.get(
4806				col::INDEX_BY_EXPIRY,
4807				&crate::expiry_index_key(crate::Expiry(s2.expiry()), &s2.hash())
4808			)
4809			.unwrap()
4810			.is_some());
4811
4812		// s1 kept the sequence number the first attempt assigned; s2 got a fresh one above it.
4813		assert_eq!(
4814			store.db.get(col::ADMISSION_SEQ, &7u64.to_be_bytes()).unwrap(),
4815			Some(s1.hash().to_vec())
4816		);
4817		assert_eq!(
4818			store.db.get(col::ADMISSION_SEQ, &8u64.to_be_bytes()).unwrap(),
4819			Some(s2.hash().to_vec())
4820		);
4821		assert_eq!(store.submit_index.read().next_seq, 9);
4822		let replay = store.replay_batch(&OptimizedTopicFilter::Any, 7, 9).unwrap();
4823		assert_eq!(replay.statements, vec![s1.encode(), s2.encode()]);
4824
4825		// Channel state was rebuilt from the bodies: a lower-priority replacement is rejected.
4826		assert!(matches!(
4827			store.submit(statement(2, 4, Some(9), 100), StatementSource::Network),
4828			SubmitResult::Rejected(RejectionReason::ChannelPriorityTooLow { .. })
4829		));
4830	}
4831
4832	#[test]
4833	fn counters_and_seq_survive_restart() {
4834		let (store, temp) = test_store();
4835		for i in 0..3u8 {
4836			assert_eq!(
4837				store.submit(signed_statement(i), StatementSource::Network),
4838				SubmitResult::New
4839			);
4840		}
4841		// Without a resolver the signed statements persist; the next three land one per track.
4842		submit_one_statement_per_track(&store);
4843		assert_eq!(store.statement_count(), 6);
4844		assert_eq!(store.total_size(), 3 + 60);
4845		let store = reopen(store, &temp);
4846		assert_eq!(store.statement_count(), 6);
4847		assert_eq!(store.total_size(), 3 + 60);
4848		assert_eq!(track_size(&store, RetentionTrack::Transient), 10);
4849		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 20);
4850		assert_eq!(track_size(&store, RetentionTrack::Persistent), 3 + 30);
4851		assert_eq!(store.submit_index.read().next_seq, 6);
4852		// `signed_statement` signs as Alice, so two distinct accounts are stored.
4853		assert_eq!(store.account_count(), 2);
4854	}
4855
4856	#[test]
4857	fn resubmitting_live_statement_is_known_and_not_double_counted() {
4858		let (store, _temp) = test_store();
4859		let statement = statement(1, 1, None, 100);
4860		assert_eq!(store.submit(statement.clone(), StatementSource::Local), SubmitResult::New);
4861		assert_eq!(store.total_size(), 100);
4862		assert_eq!(store.submit(statement.clone(), StatementSource::Local), SubmitResult::Known);
4863		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::Known);
4864		assert_eq!(store.total_size(), 100);
4865		assert_eq!(store.statement_count(), 1);
4866	}
4867
4868	#[test]
4869	fn eviction_clears_all_index_rows() {
4870		let (mut store, _temp) = test_store();
4871		store.set_time(0);
4872		let mut stmt = unsigned_statement(1, 1, Some(7), 100);
4873		stmt.set_topic(0, topic(3));
4874		stmt.set_expiry_from_parts(500, 1);
4875		sign_with(&mut stmt, 1);
4876		let hash = stmt.hash();
4877		let expiry = crate::Expiry(stmt.expiry());
4878		let who = account(1);
4879		assert_eq!(store.submit(stmt, StatementSource::Network), SubmitResult::New);
4880		let account_key = crate::account_index_key(&who, expiry, &hash);
4881		let expiry_key = crate::expiry_index_key(expiry, &hash);
4882		assert!(store.db.get(col::INDEX_BY_ACCOUNT, &account_key).unwrap().is_some());
4883		assert!(store.db.get(col::INDEX_BY_EXPIRY, &expiry_key).unwrap().is_some());
4884
4885		store.remove(&hash).unwrap();
4886		assert!(store.db.get(col::INDEX_BY_ACCOUNT, &account_key).unwrap().is_none());
4887		assert!(store.db.get(col::INDEX_BY_EXPIRY, &expiry_key).unwrap().is_none());
4888		assert!(!store.index_has_topic(&topic(3), &hash));
4889		assert_eq!(store.db.get(col::ADMISSION_SEQ, &0u64.to_be_bytes()).unwrap(), None);
4890		// Removed before its natural expiry: banned via the evicted journal.
4891		assert!(store.is_evicted(&hash));
4892		assert_eq!(store.statement_count(), 0);
4893		assert_eq!(store.total_size(), 0);
4894	}
4895
4896	#[test]
4897	fn index_key_layouts_roundtrip() {
4898		// The key builders and their parsers are the single place that knows the on-disk key
4899		// layouts; whoever changes one side must keep the other in sync, and this test is the
4900		// tripwire for that.
4901		use crate::{
4902			account_index_key, dec_key_index_key, dec_key_index_prefix, evicted_index_key,
4903			expiry_index_key, hash_from_index_key, parse_account_index_key,
4904			parse_dec_key_index_prefix, parse_time_index_key, prefix_from_index_key,
4905			topic_index_key, Expiry,
4906		};
4907
4908		let who = account(7);
4909		let hash: crate::Hash = account(8);
4910		let expiry = Expiry((123u64 << 32) | 45);
4911
4912		let key = account_index_key(&who, expiry, &hash);
4913		assert_eq!(parse_account_index_key(&key), Some((who, expiry, hash)));
4914		// Any other length is rejected rather than misparsed.
4915		assert_eq!(parse_account_index_key(&key[..key.len() - 1]), None);
4916		assert_eq!(parse_account_index_key(&[]), None);
4917
4918		let key = expiry_index_key(expiry, &hash);
4919		assert_eq!(parse_time_index_key(&key), Some((expiry.0, hash)));
4920		assert_eq!(parse_time_index_key(&key[1..]), None);
4921
4922		let key = evicted_index_key(789, &hash);
4923		assert_eq!(parse_time_index_key(&key), Some((789, hash)));
4924
4925		// Big-endian time keys keep numeric order; the expiry sweep and the evicted journal
4926		// drain rely on it to stop at the first entry that is not yet due.
4927		assert!(expiry_index_key(Expiry(256), &hash) > expiry_index_key(Expiry(1), &hash));
4928		assert!(evicted_index_key(256, &hash) > evicted_index_key(1, &hash));
4929
4930		let key = topic_index_key(&topic(3), &hash);
4931		assert_eq!(hash_from_index_key(&key), Some(hash));
4932		assert_eq!(prefix_from_index_key(&key), Some(&topic(3)[..]));
4933
4934		for dec_key in [None, Some(dec_key(5))] {
4935			assert_eq!(parse_dec_key_index_prefix(&dec_key_index_prefix(&dec_key)), Some(dec_key));
4936			let key = dec_key_index_key(&dec_key, &hash);
4937			assert_eq!(hash_from_index_key(&key), Some(hash));
4938			assert_eq!(
4939				prefix_from_index_key(&key).and_then(parse_dec_key_index_prefix),
4940				Some(dec_key)
4941			);
4942		}
4943	}
4944
4945	#[test]
4946	fn summary_fast_path_stays_coherent_with_disk() {
4947		use crate::{DETAILS_CACHE_BUDGET, SUMMARY_CACHE_ACCOUNTS};
4948
4949		let (store, _temp) = test_store();
4950		let source = StatementSource::Network;
4951
4952		// The test walks three accounts (5, 6 and 7); every summary must stay cached throughout.
4953		assert!(SUMMARY_CACHE_ACCOUNTS >= 3, "three account summaries must fit the cache");
4954		// Two filler accounts grow their records until the details cache overflows by at least
4955		// one statement, so that account 5's record (of one statement) is the one evicted.
4956		let per_filler_account = DETAILS_CACHE_BUDGET.div_ceil(2);
4957		assert!(
4958			per_filler_account <= 100,
4959			"the filler accounts' allowance (100 statements, 1000 bytes of data) caps the cache \
4960			 budget this test can exercise",
4961		);
4962
4963		// Account 5's record enters the details cache with its first statement.
4964		let s5_1 = statement(5, 1, None, 100);
4965		assert_eq!(store.submit(s5_1.clone(), source), SubmitResult::New);
4966		assert!(store.details_cached(&account(5)));
4967
4968		// Grow the filler accounts' records past the cache budget; account 5's record is the
4969		// least recently used one, so it is evicted, while its summary stays cached.
4970		for acc in [6u64, 7] {
4971			for c in 1..=per_filler_account as u64 {
4972				assert_eq!(store.submit(statement(acc, 1, Some(c), 10), source), SubmitResult::New);
4973			}
4974		}
4975		assert!(!store.details_cached(&account(5)));
4976
4977		// A channel-less statement within the account's allowance is admitted through the
4978		// summary alone: the record is not rematerialised.
4979		let s5_2 = statement(5, 2, None, 50);
4980		assert_eq!(store.submit(s5_2.clone(), source), SubmitResult::New);
4981		assert!(!store.details_cached(&account(5)));
4982
4983		// Pushing the account over its size allowance (1000 bytes) forces the record to be
4984		// loaded back from disk. It must contain both earlier statements — including the one
4985		// admitted through the fast path — and evict exactly the lowest-priority one.
4986		let s5_3 = statement(5, 3, None, 900);
4987		assert_eq!(store.submit(s5_3.clone(), source), SubmitResult::New);
4988		assert!(store.details_cached(&account(5)));
4989		assert!(!store.has_statement(&s5_1.hash()), "lowest priority must be evicted");
4990		assert!(store.has_statement(&s5_2.hash()));
4991		assert!(store.has_statement(&s5_3.hash()));
4992		let filler_statements = 2 * per_filler_account;
4993		assert_eq!(store.statement_count(), 2 + filler_statements);
4994		assert_eq!(store.total_size(), 50 + 900 + filler_statements * 10);
4995	}
4996
4997	#[test]
4998	fn rejected_submission_caches_the_loaded_record() {
4999		let (store, temp) = test_store();
5000		let source = StatementSource::Network;
5001
5002		// Account 5 owns one channel statement.
5003		assert_eq!(store.submit(statement(5, 2, Some(1), 100), source), SubmitResult::New);
5004
5005		// Reopen the store so that both caches start cold.
5006		let store = reopen(store, &temp);
5007
5008		// An oversize statement is rejected before the account record is even loaded, so the
5009		// caches stay cold.
5010		assert_eq!(
5011			store.submit(statement(5, 3, None, 1500), source),
5012			SubmitResult::Rejected(RejectionReason::DataTooLarge {
5013				submitted_size: 1500,
5014				available_size: 1000,
5015			})
5016		);
5017		assert!(!store.details_cached(&account(5)));
5018		assert!(!store.summary_cached(&account(5)));
5019
5020		// A channel statement of too low a priority is rejected only after planning against the
5021		// record loaded from disk. The record and its summary must stay cached: rejections cost
5022		// the sender nothing, so retries must not rescan the on-disk index every time.
5023		assert!(matches!(
5024			store.submit(statement(5, 1, Some(1), 100), source),
5025			SubmitResult::Rejected(RejectionReason::ChannelPriorityTooLow { .. })
5026		));
5027		assert!(store.details_cached(&account(5)));
5028		assert!(store.summary_cached(&account(5)));
5029	}
5030
5031	#[test]
5032	fn take_recent_statements_clears_index() {
5033		let (store, _temp) = test_store();
5034		let statement0 = signed_statement(0);
5035		let statement1 = signed_statement(1);
5036		let statement2 = signed_statement(2);
5037		let statement3 = signed_statement(3);
5038
5039		let _ = store.submit(statement0.clone(), StatementSource::Local);
5040		let _ = store.submit(statement1.clone(), StatementSource::Local);
5041		let _ = store.submit(statement2.clone(), StatementSource::Local);
5042
5043		let recent1 = store.take_recent_statements().unwrap();
5044		let (recent1_hashes, recent1_statements): (Vec<_>, Vec<_>) =
5045			recent1.into_iter().map(|(_seq, hash, statement)| (hash, statement)).unzip();
5046		let expected1 = vec![statement0, statement1, statement2];
5047		assert!(expected1.iter().all(|s| recent1_hashes.contains(&s.hash())));
5048		assert!(expected1.iter().all(|s| recent1_statements.contains(s)));
5049
5050		// Recent statements are cleared.
5051		let recent2 = store.take_recent_statements().unwrap();
5052		assert_eq!(recent2.len(), 0);
5053
5054		store.submit(statement3.clone(), StatementSource::Network);
5055
5056		let recent3 = store.take_recent_statements().unwrap();
5057		let (recent3_hashes, recent3_statements): (Vec<_>, Vec<_>) =
5058			recent3.into_iter().map(|(_seq, hash, statement)| (hash, statement)).unzip();
5059		let expected3 = vec![statement3];
5060		assert!(expected3.iter().all(|s| recent3_hashes.contains(&s.hash())));
5061		assert!(expected3.iter().all(|s| recent3_statements.contains(s)));
5062
5063		// Recent statements are cleared, but statements remain in the store.
5064		assert_eq!(store.statements().unwrap().len(), 4);
5065	}
5066
5067	#[test]
5068	fn clearing_propagated_keeps_a_readmitted_statement() {
5069		let mut query_index = QueryIndex::new();
5070		let statement = signed_statement(0);
5071		let hash = statement.hash();
5072
5073		query_index.note_insert(hash, &statement, 1, RetentionTrack::Persistent);
5074		let recent = query_index.recent_snapshot();
5075		// A removal and re-admission while propagation reads the bodies bumps the sequence number.
5076		query_index.note_remove(&hash, &statement);
5077		query_index.note_insert(hash, &statement, 2, RetentionTrack::Persistent);
5078
5079		query_index.clear_propagated(&recent);
5080		assert_eq!(query_index.recent.get(&hash), Some(&2));
5081
5082		query_index.clear_propagated(&query_index.recent_snapshot());
5083		assert!(query_index.recent.is_empty());
5084	}
5085
5086	#[test]
5087	fn transient_statement_is_stored_and_tracked() {
5088		let (store, _temp) = test_store();
5089		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5090		let statement = signed_statement(0);
5091		let hash = statement.hash();
5092
5093		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New,);
5094
5095		// Stored like any other statement, and tracked for the sweep.
5096		assert!(store.has_statement(&hash));
5097		assert_eq!(store.statement(&hash).unwrap(), Some(statement.clone()));
5098		assert_eq!(
5099			store.query_index.read().retention_tracks.get(&hash),
5100			Some(&RetentionTrack::Transient)
5101		);
5102
5103		// Pulled once under its admission sequence, then it stays fetchable by hash.
5104		let recent = store.take_recent_statements().unwrap();
5105		assert_eq!(recent, vec![(0, hash, statement)]);
5106		assert!(store.take_recent_statements().unwrap().is_empty());
5107		assert!(store.has_statement(&hash));
5108		assert_eq!(
5109			store.query_index.read().retention_tracks.get(&hash),
5110			Some(&RetentionTrack::Transient)
5111		);
5112	}
5113
5114	#[test]
5115	fn resubmitting_transient_statement_reports_known() {
5116		let (store, _temp) = test_store();
5117		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5118		let statement = signed_statement(0);
5119
5120		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New,);
5121		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::Known);
5122	}
5123
5124	/// Takes the recent statements and releases their holds, as a finished propagation does.
5125	fn propagate(store: &Store) {
5126		let hashes: Vec<_> = store
5127			.take_recent_statements()
5128			.unwrap()
5129			.into_iter()
5130			.map(|(_, hash, _)| hash)
5131			.collect();
5132		store.release_statements(&hashes);
5133	}
5134
5135	#[test]
5136	fn sweep_removes_propagated_transient_statements_with_a_ban() {
5137		let (store, _temp) = test_store();
5138		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5139		let statement = signed_statement(0);
5140		let hash = statement.hash();
5141		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New);
5142
5143		// Not propagated yet, so the sweep leaves it alone.
5144		store.maintain();
5145		assert!(store.has_statement(&hash));
5146
5147		propagate(&store);
5148		store.maintain();
5149		assert!(!store.has_statement(&hash));
5150		assert!(store.query_index.read().retention_tracks.is_empty());
5151		// Forwarded once: a redelivery from another peer must not start another round.
5152		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::KnownExpired);
5153	}
5154
5155	#[test]
5156	fn sweep_keeps_a_transient_statement_until_its_last_hold_is_released() {
5157		let (store, _temp) = test_store();
5158		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5159		let statement = signed_statement(0);
5160		let hash = statement.hash();
5161		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5162
5163		// The take holds the statement, two outboxes queue it, then the take lets go.
5164		store.take_recent_statements().unwrap();
5165		store.hold_statements(&[hash, hash]);
5166		store.release_statements(&[hash]);
5167		store.maintain();
5168		assert!(store.has_statement(&hash));
5169
5170		// One outbox sent it, the other still holds it.
5171		store.release_statements(&[hash]);
5172		store.maintain();
5173		assert!(store.has_statement(&hash));
5174
5175		store.release_statements(&[hash]);
5176		store.maintain();
5177		assert!(!store.has_statement(&hash));
5178	}
5179
5180	#[test]
5181	fn a_readmitted_statement_keeps_its_hold_when_the_removed_copy_is_released() {
5182		let (store, _temp) = test_store();
5183		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5184		let statement = signed_statement(0);
5185		let hash = statement.hash();
5186		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New);
5187		store.take_recent_statements().unwrap();
5188
5189		// Removed while an outbox still holds it, then resubmitted locally and taken again.
5190		store.remove(&hash).unwrap();
5191		assert_eq!(store.submit(statement, StatementSource::Local), SubmitResult::New);
5192		store.take_recent_statements().unwrap();
5193
5194		// The removed copy's outbox lets go, the new copy's hold remains.
5195		store.release_statements(&[hash]);
5196		store.maintain();
5197		assert!(store.has_statement(&hash));
5198
5199		store.release_statements(&[hash]);
5200		store.maintain();
5201		assert!(!store.has_statement(&hash));
5202	}
5203
5204	#[test]
5205	fn sweep_moves_a_transient_statement_to_the_track_affinity_now_gives_it() {
5206		let (store, _temp) = test_store();
5207		let phase = std::sync::Arc::new(std::sync::atomic::AtomicU8::new(0));
5208		store.set_retention_resolver(Box::new({
5209			let phase = phase.clone();
5210			move |_| match phase.load(Ordering::Relaxed) {
5211				0 => RetentionReasonMask::TRANSIENT,
5212				1 => RetentionReasonMask::EXPLICIT_AFFINITY,
5213				_ => RetentionReasonMask::DHT_AFFINITY,
5214			}
5215		}));
5216		let statement = signed_statement(0);
5217		let hash = statement.hash();
5218		let data_len = statement.data_len();
5219		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New);
5220		propagate(&store);
5221		assert_eq!(track_size(&store, RetentionTrack::Transient), data_len);
5222
5223		// Explicit affinity arrived before the sweep: kept, tracked as explicit-only.
5224		phase.store(1, Ordering::Relaxed);
5225		store.maintain();
5226		assert!(store.has_statement(&hash));
5227		assert_eq!(
5228			store.query_index.read().retention_tracks.get(&hash),
5229			Some(&RetentionTrack::ExplicitOnly)
5230		);
5231		assert_eq!(track_size(&store, RetentionTrack::Transient), 0);
5232		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), data_len);
5233
5234		// DHT affinity makes it a plain persistent statement, so tracking ends.
5235		phase.store(2, Ordering::Relaxed);
5236		store.maintain();
5237		assert!(store.has_statement(&hash));
5238		assert!(store.query_index.read().retention_tracks.is_empty());
5239		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 0);
5240		assert_eq!(track_size(&store, RetentionTrack::Persistent), data_len);
5241
5242		// The index row carries the track the sweep set, so the removal comes off it.
5243		store.remove(&hash).unwrap();
5244		assert_eq!(store.submit_index.read().totals, StoreTotals::default());
5245	}
5246
5247	fn submit_one_statement_per_track(store: &Store) -> Vec<Statement> {
5248		let phase = std::sync::Arc::new(std::sync::atomic::AtomicU8::new(0));
5249		store.set_retention_resolver(Box::new({
5250			let phase = phase.clone();
5251			move |_| match phase.fetch_add(1, Ordering::Relaxed) {
5252				0 => RetentionReasonMask::TRANSIENT,
5253				1 => RetentionReasonMask::EXPLICIT_AFFINITY,
5254				_ => RetentionReasonMask::DHT_AFFINITY,
5255			}
5256		}));
5257		(0..3u32)
5258			.map(|i| {
5259				let statement = statement(3, i, None, 10 * (i as usize + 1));
5260				assert_eq!(
5261					store.submit(statement.clone(), StatementSource::Network),
5262					SubmitResult::New
5263				);
5264				statement
5265			})
5266			.collect()
5267	}
5268
5269	fn track_size(store: &Store, track: RetentionTrack) -> usize {
5270		store.submit_index.read().totals.track_size(track)
5271	}
5272
5273	#[test]
5274	fn totals_are_kept_per_admission_track() {
5275		let (store, _temp) = test_store();
5276		let statements = submit_one_statement_per_track(&store);
5277		assert_eq!(track_size(&store, RetentionTrack::Transient), 10);
5278		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 20);
5279		assert_eq!(track_size(&store, RetentionTrack::Persistent), 30);
5280		assert_eq!(store.statement_count(), 3);
5281		assert_eq!(store.total_size(), 60);
5282
5283		store.remove(&statements[1].hash()).unwrap();
5284		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 0);
5285		assert_eq!(store.statement_count(), 2);
5286
5287		store.remove_by(statements[0].account_id().unwrap()).unwrap();
5288		assert_eq!(store.submit_index.read().totals, StoreTotals::default());
5289	}
5290
5291	#[test]
5292	fn maintenance_reports_the_bytes_of_each_retention_track() {
5293		let (mut store, _temp) = test_store();
5294		store.metrics = PrometheusMetrics::new(Some(&PrometheusRegistry::new()));
5295		let reported = |store: &Store, track: RetentionTrack| {
5296			let mut value = None;
5297			store.metrics.report(|metrics| {
5298				value = Some(metrics.bytes_by_retention.with_label_values(&[track.label()]).get())
5299			});
5300			value.expect("the test registers metrics")
5301		};
5302		let statements = submit_one_statement_per_track(&store);
5303
5304		store.maintain();
5305		assert_eq!(reported(&store, RetentionTrack::Transient), 10);
5306		assert_eq!(reported(&store, RetentionTrack::ExplicitOnly), 20);
5307		assert_eq!(reported(&store, RetentionTrack::Persistent), 30);
5308
5309		store.remove(&statements[1].hash()).unwrap();
5310		store.maintain();
5311		assert_eq!(reported(&store, RetentionTrack::ExplicitOnly), 0);
5312		assert_eq!(reported(&store, RetentionTrack::Persistent), 30);
5313	}
5314
5315	#[test]
5316	fn migration_counts_every_statement_as_explicit_only() {
5317		let (store, temp) = test_store();
5318		let statements = submit_one_statement_per_track(&store);
5319		store
5320			.db
5321			.commit([(col::META, KEY_VERSION.to_vec(), Some(2u32.to_le_bytes().to_vec()))])
5322			.unwrap();
5323		let store = reopen(store, &temp);
5324		assert_eq!(track_size(&store, RetentionTrack::Transient), 0);
5325		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 60);
5326		assert_eq!(track_size(&store, RetentionTrack::Persistent), 0);
5327		// Migrated rows carry the explicit-only track, so the removal comes off it.
5328		store.remove(&statements[0].hash()).unwrap();
5329		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 50);
5330	}
5331
5332	#[test]
5333	fn migration_from_v2_keeps_the_evicted_journal() {
5334		let (store, temp) = test_store();
5335		// A ban whose purge time the statement's expiry capped, so a rebuild from the EXPIRED
5336		// column would add a second key for the same hash.
5337		let banned = topic(999).0;
5338		let banned_at = 10_000_000_000u64;
5339		let purge_at = banned_at + 10;
5340		store
5341			.db
5342			.commit([
5343				(col::EXPIRED, banned.to_vec(), Some((banned, banned_at).encode())),
5344				(
5345					col::INDEX_EVICTED,
5346					evicted_index_key(purge_at, &banned),
5347					Some(INDEX_EMPTY_VALUE.to_vec()),
5348				),
5349				(col::META, KEY_VERSION.to_vec(), Some(2u32.to_le_bytes().to_vec())),
5350			])
5351			.unwrap();
5352		let store = reopen(store, &temp);
5353		assert!(store.is_evicted(&banned));
5354		assert_eq!(store.evicted_count(), 1);
5355		let mut journal = store.db.iter(col::INDEX_EVICTED).unwrap();
5356		journal.seek_to_first().unwrap();
5357		let (key, _) = journal.next().unwrap().unwrap();
5358		assert_eq!(parse_time_index_key(&key), Some((purge_at, banned)));
5359		assert!(journal.next().unwrap().is_none());
5360	}
5361
5362	fn transient_max_size(max_size: usize) -> Config {
5363		Config {
5364			v2dht: Some(V2DhtConfig { transient_max_size: Some(max_size), ..Default::default() }),
5365			..Default::default()
5366		}
5367	}
5368
5369	#[test]
5370	fn track_size_limit_outside_the_store_size_is_an_invalid_config() {
5371		assert!(matches!(transient_max_size(0).validate(), Err(Error::InvalidConfig(_))));
5372		let max_total_size = Config::default().max_total_size;
5373		assert!(transient_max_size(max_total_size).validate().is_ok());
5374		assert!(matches!(
5375			transient_max_size(max_total_size + 1).validate(),
5376			Err(Error::InvalidConfig(_))
5377		));
5378	}
5379
5380	#[test]
5381	fn a_full_track_rejects_its_own_statements_only() {
5382		let (store, _temp) = test_store_with_config(transient_max_size(15));
5383		let (resolver, transient) =
5384			switchable_resolver(RetentionReasonMask::TRANSIENT, RetentionReasonMask::DHT_AFFINITY);
5385		store.set_retention_resolver(resolver);
5386		let source = StatementSource::Network;
5387
5388		// A second statement of 10 bytes exceeds the 15 of the track.
5389		assert_eq!(store.submit(statement(5, 1, None, 10), source), SubmitResult::New);
5390		assert_eq!(
5391			store.submit(statement(5, 2, None, 10), source),
5392			SubmitResult::Rejected(RejectionReason::TrackFull)
5393		);
5394		assert_eq!(track_size(&store, RetentionTrack::Transient), 10);
5395
5396		// The same statement fits another track, whose limit is the store size.
5397		transient.store(false, Ordering::Relaxed);
5398		assert_eq!(store.submit(statement(5, 2, None, 10), source), SubmitResult::New);
5399		assert_eq!(track_size(&store, RetentionTrack::Persistent), 10);
5400
5401		// The track fills up to its limit exactly.
5402		transient.store(true, Ordering::Relaxed);
5403		assert_eq!(store.submit(statement(5, 3, None, 5), source), SubmitResult::New);
5404		assert_eq!(
5405			store.submit(statement(6, 1, None, 1), source),
5406			SubmitResult::Rejected(RejectionReason::TrackFull)
5407		);
5408		assert_eq!(track_size(&store, RetentionTrack::Transient), 15);
5409	}
5410
5411	#[test]
5412	fn explicit_only_statements_take_the_room_the_limited_tracks_leave() {
5413		let (store, _temp) = test_store_with_config(Config {
5414			max_total_size: 300,
5415			v2dht: Some(V2DhtConfig {
5416				dht_affinity_max_size: Some(100),
5417				transient_max_size: Some(100),
5418				..Default::default()
5419			}),
5420			..Default::default()
5421		});
5422		let (resolver, explicit) = switchable_resolver(
5423			RetentionReasonMask::EXPLICIT_AFFINITY,
5424			RetentionReasonMask::TRANSIENT,
5425		);
5426		store.set_retention_resolver(resolver);
5427		let source = StatementSource::Network;
5428
5429		// Explicit-only statements fill the whole store, past the limit of any other track.
5430		for priority in 1..=3 {
5431			assert_eq!(store.submit(statement(5, priority, None, 100), source), SubmitResult::New);
5432		}
5433		assert_eq!(track_size(&store, RetentionTrack::ExplicitOnly), 300);
5434
5435		// The transient track is empty, yet the store has no room left for it.
5436		explicit.store(false, Ordering::Relaxed);
5437		assert_eq!(
5438			store.submit(statement(6, 1, None, 1), source),
5439			SubmitResult::Rejected(RejectionReason::StoreFull)
5440		);
5441		assert_eq!(track_size(&store, RetentionTrack::Transient), 0);
5442	}
5443
5444	#[test]
5445	fn evicting_own_statements_frees_no_room_on_another_track() {
5446		let (store, _temp) = test_store_with_config(transient_max_size(100));
5447		let (resolver, transient) =
5448			switchable_resolver(RetentionReasonMask::TRANSIENT, RetentionReasonMask::DHT_AFFINITY);
5449		store.set_retention_resolver(resolver);
5450		let source = StatementSource::Network;
5451
5452		// The transient track is full, account 3 is at its three-statement allowance.
5453		assert_eq!(store.submit(statement(5, 1, None, 100), source), SubmitResult::New);
5454		transient.store(false, Ordering::Relaxed);
5455		let persistent: Vec<Statement> = (1..=3).map(|p| statement(3, p, None, 100)).collect();
5456		for statement in &persistent {
5457			assert_eq!(store.submit(statement.clone(), source), SubmitResult::New);
5458		}
5459
5460		// The account could evict its lowest priority statement, but the freed room is on the
5461		// persistent track, so the transient one is still rejected and nothing is evicted.
5462		transient.store(true, Ordering::Relaxed);
5463		assert_eq!(
5464			store.submit(statement(3, 10, None, 100), source),
5465			SubmitResult::Rejected(RejectionReason::TrackFull)
5466		);
5467		assert!(persistent.iter().all(|statement| store.has_statement(&statement.hash())));
5468		assert_eq!(track_size(&store, RetentionTrack::Persistent), 300);
5469		assert_eq!(track_size(&store, RetentionTrack::Transient), 100);
5470
5471		// On its own track the same statement evicts the lowest priority one and fits.
5472		transient.store(false, Ordering::Relaxed);
5473		assert_eq!(store.submit(statement(3, 10, None, 100), source), SubmitResult::New);
5474		assert!(!store.has_statement(&persistent[0].hash()));
5475		assert_eq!(track_size(&store, RetentionTrack::Persistent), 300);
5476	}
5477
5478	#[test]
5479	fn submit_persists_without_a_resolver() {
5480		let (store, _temp) = test_store();
5481		let statement = signed_statement(0);
5482		let hash = statement.hash();
5483
5484		assert_eq!(store.submit(statement, StatementSource::Local), SubmitResult::New);
5485		assert!(store.has_statement(&hash));
5486	}
5487
5488	#[test]
5489	fn set_retention_resolver_is_first_wins() {
5490		let (store, _temp) = test_store();
5491		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5492		// The second install is rejected; the first resolver stays in force.
5493		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::persistent()));
5494		let statement = signed_statement(0);
5495		let hash = statement.hash();
5496
5497		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5498		assert_eq!(
5499			store.query_index.read().retention_tracks.get(&hash),
5500			Some(&RetentionTrack::Transient),
5501			"the first, transient resolver still applies"
5502		);
5503	}
5504
5505	/// A resolver that reports `affine` while the returned flag holds `true`, and `lapsed`
5506	/// otherwise — modeling affinity that lapses or shifts.
5507	fn switchable_resolver(
5508		affine: RetentionReasonMask,
5509		lapsed: RetentionReasonMask,
5510	) -> (Box<dyn Fn(&Statement) -> RetentionReasonMask + Send + Sync>, std::sync::Arc<AtomicBool>)
5511	{
5512		let flag = std::sync::Arc::new(AtomicBool::new(true));
5513		let view = flag.clone();
5514		let resolver = Box::new(
5515			move |_: &Statement| if view.load(Ordering::Relaxed) { affine } else { lapsed },
5516		);
5517		(resolver, flag)
5518	}
5519
5520	#[test]
5521	fn sweep_drops_statement_once_explicit_affinity_lapses() {
5522		let (store, _temp) = test_store();
5523		let (resolver, affine) = switchable_resolver(
5524			RetentionReasonMask::EXPLICIT_AFFINITY,
5525			RetentionReasonMask::TRANSIENT,
5526		);
5527		store.set_retention_resolver(resolver);
5528		let statement = signed_statement(0);
5529		let hash = statement.hash();
5530
5531		assert_eq!(store.submit(statement.clone(), StatementSource::Network), SubmitResult::New);
5532		assert!(store.has_statement(&hash));
5533		propagate(&store);
5534
5535		// Affinity still holds: the sweep keeps the statement.
5536		store.maintain();
5537		assert!(store.has_statement(&hash));
5538
5539		// Affinity lapsed: the sweep drops the statement.
5540		affine.store(false, Ordering::Relaxed);
5541		store.maintain();
5542		assert!(!store.has_statement(&hash));
5543
5544		// The removal skips the re-acceptance ban, so the statement returns once affinity does.
5545		affine.store(true, Ordering::Relaxed);
5546		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5547		assert!(store.has_statement(&hash));
5548
5549		// The redelivered statement is tracked again: a second lapse sweeps it once more.
5550		affine.store(false, Ordering::Relaxed);
5551		propagate(&store);
5552		store.maintain();
5553		assert!(!store.has_statement(&hash));
5554	}
5555
5556	#[test]
5557	fn local_resubmission_clears_stale_ban() {
5558		let (store, _temp) = test_store();
5559		let (resolver, affine) = switchable_resolver(
5560			RetentionReasonMask::EXPLICIT_AFFINITY,
5561			RetentionReasonMask::TRANSIENT,
5562		);
5563		store.set_retention_resolver(resolver);
5564		// Account 1 holds one statement, so the second one evicts the first, with a ban.
5565		let evicted = statement(1, 1, None, 100);
5566		let evictor = statement(1, 2, None, 100);
5567		assert_eq!(store.submit(evicted.clone(), StatementSource::Network), SubmitResult::New);
5568		assert_eq!(store.submit(evictor.clone(), StatementSource::Network), SubmitResult::New);
5569		assert!(store.is_evicted(&evicted.hash()));
5570		assert_eq!(store.evicted_count(), 1);
5571
5572		// Affinity lapsed: the sweep removes the evictor without a ban, freeing the slot.
5573		propagate(&store);
5574		affine.store(false, Ordering::Relaxed);
5575		store.maintain();
5576		assert!(!store.has_statement(&evictor.hash()));
5577
5578		// A local resubmission ignores the eviction ban and clears it from the evicted journal.
5579		affine.store(true, Ordering::Relaxed);
5580		assert_eq!(store.submit(evicted.clone(), StatementSource::Local), SubmitResult::New);
5581		assert!(!store.is_evicted(&evicted.hash()));
5582		assert_eq!(store.evicted_count(), 0);
5583		let mut evicted_journal = store.db.iter(col::INDEX_EVICTED).unwrap();
5584		evicted_journal.seek_to_first().unwrap();
5585		assert!(evicted_journal.next().unwrap().is_none());
5586
5587		// The sweep removes the statement again without a ban, so peers may redeliver it.
5588		propagate(&store);
5589		affine.store(false, Ordering::Relaxed);
5590		store.maintain();
5591		assert!(!store.has_statement(&evicted.hash()));
5592		affine.store(true, Ordering::Relaxed);
5593		assert_eq!(store.submit(evicted, StatementSource::Network), SubmitResult::New);
5594	}
5595
5596	#[test]
5597	fn sweep_spares_statements_not_yet_handed_to_propagation() {
5598		let (store, _temp) = test_store();
5599		let (resolver, affine) = switchable_resolver(
5600			RetentionReasonMask::EXPLICIT_AFFINITY,
5601			RetentionReasonMask::TRANSIENT,
5602		);
5603		store.set_retention_resolver(resolver);
5604		let statement = signed_statement(0);
5605		let hash = statement.hash();
5606		assert_eq!(store.submit(statement, StatementSource::Local), SubmitResult::New);
5607
5608		// Affinity lapsed before the outbox took the statement: the sweep leaves it alone,
5609		// so a locally submitted statement is handed to propagation at least once.
5610		affine.store(false, Ordering::Relaxed);
5611		store.maintain();
5612		assert!(store.has_statement(&hash));
5613
5614		// Once propagation has taken it, the next sweep drops it.
5615		propagate(&store);
5616		store.maintain();
5617		assert!(!store.has_statement(&hash));
5618	}
5619
5620	#[test]
5621	fn sweep_keeps_statements_another_affinity_still_covers() {
5622		let (store, _temp) = test_store();
5623		let (resolver, affine) = switchable_resolver(
5624			RetentionReasonMask::EXPLICIT_AFFINITY,
5625			RetentionReasonMask::DHT_AFFINITY,
5626		);
5627		store.set_retention_resolver(resolver);
5628		let statement = signed_statement(0);
5629		let hash = statement.hash();
5630		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5631		propagate(&store);
5632
5633		// Explicit affinity lapsed but the DHT covers the statement at sweep time: the sweep
5634		// checks for any persistent reason, not the explicit bit, and keeps it.
5635		affine.store(false, Ordering::Relaxed);
5636		store.maintain();
5637		assert!(store.has_statement(&hash));
5638	}
5639
5640	#[test]
5641	fn sweep_spares_a_copy_readmitted_while_it_resolves_affinity() {
5642		let (store, _temp) = test_store();
5643		let store = std::sync::Arc::new(store);
5644		let statement = signed_statement(0);
5645		let hash = statement.hash();
5646		// 0: initial admission, 1: the sweep resolves its candidate, 2: the re-admission.
5647		let phase = std::sync::Arc::new(AtomicU8::new(0));
5648		store.set_retention_resolver(Box::new({
5649			let store = store.clone();
5650			let phase = phase.clone();
5651			let statement = statement.clone();
5652			move |_: &Statement| match phase.load(Ordering::Relaxed) {
5653				0 => RetentionReasonMask::EXPLICIT_AFFINITY,
5654				1 => {
5655					phase.store(2, Ordering::Relaxed);
5656					store.remove_statement(&hash, Resubmission::Allowed).unwrap();
5657					assert_eq!(
5658						store.submit(statement.clone(), StatementSource::Network),
5659						SubmitResult::New
5660					);
5661					RetentionReasonMask::TRANSIENT
5662				},
5663				_ => RetentionReasonMask::DHT_AFFINITY,
5664			}
5665		}));
5666		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5667		propagate(&store);
5668
5669		// The candidate is deleted and re-admitted with DHT affinity while the sweep resolves
5670		// its lapsed explicit affinity: the sweep must not remove the new copy.
5671		phase.store(1, Ordering::Relaxed);
5672		store.maintain();
5673		assert!(store.has_statement(&hash));
5674		assert!(!store.query_index.read().retention_tracks.contains_key(&hash));
5675	}
5676
5677	#[test]
5678	fn sweep_skips_statements_admitted_with_both_affinities() {
5679		let (store, _temp) = test_store();
5680		let mut mask = RetentionReasonMask::EXPLICIT_AFFINITY;
5681		mask.insert(RetentionReasonMask::DHT_AFFINITY);
5682		let (resolver, affine) = switchable_resolver(mask, RetentionReasonMask::TRANSIENT);
5683		store.set_retention_resolver(resolver);
5684		let statement = signed_statement(0);
5685		let hash = statement.hash();
5686		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5687		propagate(&store);
5688
5689		// The DHT bit in the admission mask exempts the statement from the sweep.
5690		affine.store(false, Ordering::Relaxed);
5691		store.maintain();
5692		assert!(store.has_statement(&hash));
5693	}
5694
5695	#[test]
5696	fn sweep_skips_statements_admitted_before_a_restart() {
5697		let (store, temp) = test_store();
5698		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::EXPLICIT_AFFINITY));
5699		let statement = signed_statement(0);
5700		let hash = statement.hash();
5701		assert_eq!(store.submit(statement, StatementSource::Network), SubmitResult::New);
5702		let store = reopen(store, &temp);
5703		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::TRANSIENT));
5704
5705		// Affinity tracking is in-memory: a statement admitted before a restart escapes the
5706		// sweep and is kept until natural expiry.
5707		store.maintain();
5708		assert!(store.has_statement(&hash));
5709	}
5710
5711	#[test]
5712	fn removing_statements_clears_their_affinity_tracking() {
5713		let (store, _temp) = test_store();
5714		store.set_retention_resolver(Box::new(|_| RetentionReasonMask::EXPLICIT_AFFINITY));
5715		let statement0 = signed_statement(0);
5716		let statement1 = signed_statement(1);
5717		let hash0 = statement0.hash();
5718		let account = statement0.account_id().unwrap();
5719		assert_eq!(store.submit(statement0, StatementSource::Network), SubmitResult::New);
5720		assert_eq!(store.submit(statement1, StatementSource::Network), SubmitResult::New);
5721		assert_eq!(store.query_index.read().retention_tracks.len(), 2);
5722
5723		store.remove(&hash0).unwrap();
5724		assert_eq!(store.query_index.read().retention_tracks.len(), 1);
5725
5726		store.remove_by(account).unwrap();
5727		assert!(store.query_index.read().retention_tracks.is_empty());
5728	}
5729
5730	#[test]
5731	fn search_by_topic_and_key() {
5732		let (store, _temp) = test_store();
5733		let statement0 = signed_statement(0);
5734		let statement1 = signed_statement_with_topics(1, &[topic(0)], None);
5735		let statement2 = signed_statement_with_topics(2, &[topic(0), topic(1)], Some(dec_key(2)));
5736		let statement3 = signed_statement_with_topics(3, &[topic(0), topic(1), topic(2)], None);
5737		let statement4 =
5738			signed_statement_with_topics(4, &[topic(0), topic(42), topic(2), topic(3)], None);
5739		let statements = vec![statement0, statement1, statement2, statement3, statement4];
5740		for s in &statements {
5741			store.submit(s.clone(), StatementSource::Network);
5742		}
5743
5744		let assert_topics = |topics: &[u64], key: Option<u64>, expected: &[u8]| {
5745			let key = key.map(dec_key);
5746			let topics: Vec<_> = topics.iter().map(|t| topic(*t)).collect();
5747			let mut got_vals: Vec<_> = if let Some(key) = key {
5748				store.posted(&topics, key).unwrap().into_iter().map(|d| d[0]).collect()
5749			} else {
5750				store.broadcasts(&topics).unwrap().into_iter().map(|d| d[0]).collect()
5751			};
5752			got_vals.sort();
5753			assert_eq!(expected.to_vec(), got_vals);
5754		};
5755
5756		assert_topics(&[], None, &[0, 1, 3, 4]);
5757		assert_topics(&[], Some(2), &[2]);
5758		assert_topics(&[0], None, &[1, 3, 4]);
5759		assert_topics(&[1], None, &[3]);
5760		assert_topics(&[2], None, &[3, 4]);
5761		assert_topics(&[3], None, &[4]);
5762		assert_topics(&[42], None, &[4]);
5763
5764		assert_topics(&[0, 1], None, &[3]);
5765		assert_topics(&[0, 1], Some(2), &[2]);
5766		assert_topics(&[0, 1, 99], Some(2), &[]);
5767		assert_topics(&[1, 2], None, &[3]);
5768		assert_topics(&[99], None, &[]);
5769		assert_topics(&[0, 99], None, &[]);
5770		assert_topics(&[0, 1, 2, 3, 42], None, &[]);
5771	}
5772
5773	#[test]
5774	fn constraints() {
5775		let (store, _temp) = test_store();
5776
5777		store.submit_index.write().config.max_total_size = 3000;
5778		let source = StatementSource::Network;
5779		let ok = SubmitResult::New;
5780
5781		// Account 1 (limit = 1 msg, 1000 bytes)
5782
5783		// Oversized statement is not allowed. Limit for account 1 is 1 msg, 1000 bytes
5784		assert!(matches!(
5785			store.submit(statement(1, 1, Some(1), 2000), source),
5786			SubmitResult::Rejected(_)
5787		));
5788		assert_eq!(store.submit(statement(1, 1, Some(1), 500), source), ok);
5789		// Would not replace channel message with same priority
5790		assert!(matches!(
5791			store.submit(statement(1, 1, Some(1), 200), source),
5792			SubmitResult::Rejected(_)
5793		));
5794		assert_eq!(store.submit(statement(1, 2, Some(1), 600), source), ok);
5795		// Submit another message to another channel with lower priority. Should not be allowed
5796		// because msg count limit is 1
5797		assert!(matches!(
5798			store.submit(statement(1, 1, Some(2), 100), source),
5799			SubmitResult::Rejected(_)
5800		));
5801		assert_eq!(store.evicted_count(), 1);
5802
5803		// Account 2 (limit = 2 msg, 1000 bytes)
5804
5805		let s2_prio1 = statement(2, 1, None, 500);
5806		let s2_prio2 = statement(2, 2, None, 100);
5807		assert_eq!(store.submit(s2_prio1.clone(), source), ok);
5808		assert_eq!(store.submit(s2_prio2.clone(), source), ok);
5809		// Equal priority to lowest should be rejected
5810		assert!(matches!(
5811			store.submit(statement(2, 1, None, 50), source),
5812			SubmitResult::Rejected(RejectionReason::AccountFull { .. })
5813		));
5814		// Should evict priority 1
5815		let s2_prio3 = statement(2, 3, None, 500);
5816		assert_eq!(store.submit(s2_prio3.clone(), source), ok);
5817		assert_eq!(store.evicted_count(), 2);
5818		assert!(store.is_evicted(&s2_prio1.hash()));
5819		assert!(store.statement(&s2_prio1.hash()).unwrap().is_none());
5820		// Should evict all
5821		assert_eq!(store.submit(statement(2, 4, None, 1000), source), ok);
5822		assert_eq!(store.evicted_count(), 4);
5823		assert!(store.is_evicted(&s2_prio2.hash()));
5824		assert!(store.is_evicted(&s2_prio3.hash()));
5825
5826		// Account 3 (limit = 3 msg, 1000 bytes)
5827
5828		let s3_prio2 = statement(3, 2, Some(1), 300);
5829		let s3_prio3 = statement(3, 3, Some(2), 300);
5830		assert_eq!(store.submit(s3_prio2.clone(), source), ok);
5831		assert_eq!(store.submit(s3_prio3.clone(), source), ok);
5832		assert_eq!(store.submit(statement(3, 4, Some(3), 300), source), ok);
5833		// Should evict 2 and 3
5834		assert_eq!(store.submit(statement(3, 5, None, 500), source), ok);
5835		assert_eq!(store.evicted_count(), 6);
5836		assert!(store.is_evicted(&s3_prio2.hash()));
5837		assert!(store.is_evicted(&s3_prio3.hash()));
5838
5839		assert_eq!(store.total_size(), 2400);
5840		assert_eq!(store.statement_count(), 4);
5841
5842		// Should be over the global size limit
5843		assert!(matches!(
5844			store.submit(statement(1, 1, None, 700), source),
5845			SubmitResult::Rejected(_)
5846		));
5847		// Should be over the global count limit
5848		store.submit_index.write().config.max_total_statements = 4;
5849		assert!(matches!(
5850			store.submit(statement(1, 1, None, 100), source),
5851			SubmitResult::Rejected(_)
5852		));
5853
5854		let mut expected_statements = vec![
5855			statement(1, 2, Some(1), 600).hash(),
5856			statement(2, 4, None, 1000).hash(),
5857			statement(3, 4, Some(3), 300).hash(),
5858			statement(3, 5, None, 500).hash(),
5859		];
5860		expected_statements.sort();
5861		let mut statements: Vec<_> =
5862			store.statements().unwrap().into_iter().map(|(hash, _)| hash).collect();
5863		statements.sort();
5864		assert_eq!(expected_statements, statements);
5865	}
5866
5867	#[test]
5868	fn insufficient_remaining_account_bytes_is_data_too_large() {
5869		let (store, _temp) = test_store();
5870		let source = StatementSource::Network;
5871
5872		// Account 4 allows four statements and 1000 data bytes. The count limit has room, but the
5873		// lower-priority submission cannot evict the existing statement to obtain enough bytes.
5874		assert_eq!(store.submit(statement(4, 2, None, 900), source), SubmitResult::New);
5875		assert_eq!(
5876			store.submit(statement(4, 1, None, 200), source),
5877			SubmitResult::Rejected(RejectionReason::DataTooLarge {
5878				submitted_size: 200,
5879				available_size: 100,
5880			})
5881		);
5882	}
5883
5884	#[test]
5885	fn max_statement_size_for_gossiping() {
5886		let (store, _temp) = test_store();
5887		store.submit_index.write().config.max_total_size = 42 * crate::MAX_STATEMENT_SIZE;
5888
5889		assert_eq!(
5890			store.submit(
5891				statement(42, 1, Some(1), crate::MAX_STATEMENT_SIZE - 500),
5892				StatementSource::Local
5893			),
5894			SubmitResult::New
5895		);
5896
5897		assert!(matches!(
5898			store.submit(
5899				statement(42, 2, Some(1), 2 * crate::MAX_STATEMENT_SIZE),
5900				StatementSource::Local
5901			),
5902			SubmitResult::Invalid(_)
5903		));
5904	}
5905
5906	#[test]
5907	fn expired_statements_are_purged() {
5908		use super::DEFAULT_PURGE_AFTER_SEC;
5909		let (mut store, temp) = test_store();
5910		let mut statement = unsigned_statement(1, 1, Some(3), 100);
5911		store.set_time(0);
5912		statement.set_topic(0, topic(4));
5913		sign_with(&mut statement, 1);
5914		store.submit(statement.clone(), StatementSource::Network);
5915		assert_eq!(store.statement_count(), 1);
5916		store.remove(&statement.hash()).unwrap();
5917		assert_eq!(store.statement_count(), 0);
5918		assert_eq!(store.account_count(), 0);
5919		store.set_time(DEFAULT_PURGE_AFTER_SEC + 1);
5920		store.maintain();
5921		assert_eq!(store.evicted_count(), 0);
5922		let store = reopen(store, &temp);
5923		assert_eq!(store.statements().unwrap().len(), 0);
5924		assert_eq!(store.evicted_count(), 0);
5925	}
5926
5927	#[test]
5928	fn posted_clear_decrypts() {
5929		let (store, _temp) = test_store();
5930		let public = store
5931			.keystore
5932			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
5933			.unwrap();
5934		let statement1 = statement(1, 1, None, 100);
5935		let mut statement2 = unsigned_statement(1, 2, None, 0);
5936		let plain = b"The most valuable secret".to_vec();
5937		statement2.encrypt(&plain, &public).unwrap();
5938		sign_with(&mut statement2, 1);
5939		store.submit(statement1, StatementSource::Network);
5940		store.submit(statement2, StatementSource::Network);
5941		let posted_clear = store.posted_clear(&[], public.into()).unwrap();
5942		assert_eq!(posted_clear, vec![plain]);
5943	}
5944
5945	#[test]
5946	fn broadcasts_stmt_returns_encoded_statements() {
5947		let (store, _tmp) = test_store();
5948
5949		// no key, a topic other than 42
5950		let s0 = signed_statement_with_topics(0, &[topic(7)], None);
5951		// same, but with a topic = 42
5952		let s1 = signed_statement_with_topics(1, &[topic(42)], None);
5953		// has a decryption key -> must NOT be returned by broadcasts_stmt
5954		let s2 = signed_statement_with_topics(2, &[topic(42)], Some(dec_key(99)));
5955
5956		for s in [&s0, &s1, &s2] {
5957			store.submit(s.clone(), StatementSource::Network);
5958		}
5959
5960		// no topic filter
5961		let mut hashes: Vec<_> = store
5962			.broadcasts_stmt(&[])
5963			.unwrap()
5964			.into_iter()
5965			.map(|bytes| Statement::decode(&mut &bytes[..]).unwrap().hash())
5966			.collect();
5967		hashes.sort();
5968		let expected_hashes = {
5969			let mut e = vec![s0.hash(), s1.hash()];
5970			e.sort();
5971			e
5972		};
5973		assert_eq!(hashes, expected_hashes);
5974
5975		// filter on topic 42
5976		let got = store.broadcasts_stmt(&[topic(42)]).unwrap();
5977		assert_eq!(got.len(), 1);
5978		let st = Statement::decode(&mut &got[0][..]).unwrap();
5979		assert_eq!(st.hash(), s1.hash());
5980	}
5981
5982	#[test]
5983	fn posted_stmt_returns_encoded_statements_for_dest() {
5984		let (store, _tmp) = test_store();
5985
5986		let public1 = store
5987			.keystore
5988			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
5989			.unwrap();
5990		let dest: [u8; 32] = public1.into();
5991
5992		let public2 = store
5993			.keystore
5994			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
5995			.unwrap();
5996
5997		// A statement that does have dec_key = dest
5998		let mut s_with_key = unsigned_statement(1, 1, None, 0);
5999		let plain1 = b"The most valuable secret".to_vec();
6000		s_with_key.encrypt(&plain1, &public1).unwrap();
6001		sign_with(&mut s_with_key, 1);
6002
6003		// A statement with a different dec_key
6004		let mut s_other_key = unsigned_statement(2, 2, None, 0);
6005		let plain2 = b"The second most valuable secret".to_vec();
6006		s_other_key.encrypt(&plain2, &public2).unwrap();
6007		sign_with(&mut s_other_key, 2);
6008
6009		// Submit them all
6010		for s in [&s_with_key, &s_other_key] {
6011			store.submit(s.clone(), StatementSource::Network);
6012		}
6013
6014		// posted_stmt should only return the one with dec_key = dest
6015		let retrieved = store.posted_stmt(&[], dest).unwrap();
6016		assert_eq!(retrieved.len(), 1, "Only one statement has dec_key=dest");
6017
6018		// Re-decode that returned statement to confirm it is correct
6019		let returned_stmt = Statement::decode(&mut &retrieved[0][..]).unwrap();
6020		assert_eq!(
6021			returned_stmt.hash(),
6022			s_with_key.hash(),
6023			"Returned statement must match s_with_key"
6024		);
6025	}
6026
6027	#[test]
6028	fn posted_clear_stmt_returns_statement_followed_by_plain_data() {
6029		let (store, _tmp) = test_store();
6030
6031		let public1 = store
6032			.keystore
6033			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
6034			.unwrap();
6035		let dest: [u8; 32] = public1.into();
6036
6037		let public2 = store
6038			.keystore
6039			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
6040			.unwrap();
6041
6042		// A statement that does have dec_key = dest
6043		let mut s_with_key = unsigned_statement(1, 1, None, 0);
6044		let plain1 = b"The most valuable secret".to_vec();
6045		s_with_key.encrypt(&plain1, &public1).unwrap();
6046		sign_with(&mut s_with_key, 1);
6047
6048		// A statement with a different dec_key
6049		let mut s_other_key = unsigned_statement(2, 2, None, 0);
6050		let plain2 = b"The second most valuable secret".to_vec();
6051		s_other_key.encrypt(&plain2, &public2).unwrap();
6052		sign_with(&mut s_other_key, 2);
6053
6054		// Submit them all
6055		for s in [&s_with_key, &s_other_key] {
6056			store.submit(s.clone(), StatementSource::Network);
6057		}
6058
6059		// posted_stmt should only return the one with dec_key = dest
6060		let retrieved = store.posted_clear_stmt(&[], dest).unwrap();
6061		assert_eq!(retrieved.len(), 1, "Only one statement has dec_key=dest");
6062
6063		// We expect: [ encoded Statement ] + [ the decrypted bytes ]
6064		let encoded_stmt = s_with_key.encode();
6065		let stmt_len = encoded_stmt.len();
6066
6067		// 1) statement is first
6068		assert_eq!(&retrieved[0][..stmt_len], &encoded_stmt[..]);
6069
6070		// 2) followed by the decrypted payload
6071		let trailing = &retrieved[0][stmt_len..];
6072		assert_eq!(trailing, &plain1[..]);
6073	}
6074
6075	#[test]
6076	fn posted_clear_returns_plain_data_for_dest_and_topics() {
6077		let (store, _tmp) = test_store();
6078
6079		// prepare two key-pairs
6080		let public_dest = store
6081			.keystore
6082			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
6083			.unwrap();
6084		let dest: [u8; 32] = public_dest.into();
6085
6086		let public_other = store
6087			.keystore
6088			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
6089			.unwrap();
6090
6091		// statement that SHOULD be returned (matches dest & topic 42)
6092		let mut s_good = unsigned_statement(1, 1, None, 0);
6093		let plaintext_good = b"The most valuable secret".to_vec();
6094		s_good.encrypt(&plaintext_good, &public_dest).unwrap();
6095		s_good.set_topic(0, topic(42));
6096		sign_with(&mut s_good, 1);
6097
6098		// statement that should NOT be returned (same dest but different topic)
6099		let mut s_wrong_topic = unsigned_statement(2, 2, None, 0);
6100		s_wrong_topic.encrypt(b"Wrong topic", &public_dest).unwrap();
6101		s_wrong_topic.set_topic(0, topic(99));
6102		sign_with(&mut s_wrong_topic, 2);
6103
6104		// statement that should NOT be returned (different dest)
6105		let mut s_other_dest = unsigned_statement(3, 3, None, 0);
6106		s_other_dest.encrypt(b"Other dest", &public_other).unwrap();
6107		s_other_dest.set_topic(0, topic(42));
6108		sign_with(&mut s_other_dest, 3);
6109
6110		// submit all
6111		for s in [&s_good, &s_wrong_topic, &s_other_dest] {
6112			store.submit(s.clone(), StatementSource::Network);
6113		}
6114
6115		// call posted_clear with the topic filter and dest
6116		let retrieved = store.posted_clear(&[topic(42)], dest).unwrap();
6117
6118		// exactly one element, equal to the expected plaintext
6119		assert_eq!(retrieved, vec![plaintext_good]);
6120	}
6121
6122	#[test]
6123	fn already_expired_statement_is_rejected() {
6124		let (mut store, _temp) = test_store();
6125
6126		// Set current time to 1000 seconds
6127		store.set_time(1000);
6128
6129		// Create a statement that has already expired (expiration at 500 seconds, before current
6130		// time)
6131		let mut expired_statement = unsigned_statement(1, 1, None, 100);
6132		// set_expiry_from_parts: first arg is expiration timestamp in seconds, second is priority
6133		expired_statement.set_expiry_from_parts(500, 1);
6134		sign_with(&mut expired_statement, 1);
6135
6136		// Submit should fail with AlreadyExpired
6137		assert_eq!(
6138			store.submit(expired_statement, StatementSource::Network),
6139			SubmitResult::Invalid(InvalidReason::AlreadyExpired)
6140		);
6141
6142		// Verify the statement was not added
6143		assert_eq!(store.statements().unwrap().len(), 0);
6144
6145		// Now create a statement that is not expired (expiration at 2000 seconds, after current
6146		// time)
6147		let mut valid_statement = unsigned_statement(1, 1, None, 100);
6148		valid_statement.set_expiry_from_parts(2000, 1);
6149		sign_with(&mut valid_statement, 1);
6150
6151		// Submit should succeed
6152		assert_eq!(store.submit(valid_statement, StatementSource::Network), SubmitResult::New);
6153		assert_eq!(store.statements().unwrap().len(), 1);
6154	}
6155
6156	#[test]
6157	fn remove_by_covers_various_situations() {
6158		use sp_statement_store::{StatementSource, StatementStore, SubmitResult};
6159
6160		// Use a fresh store and fixed time so we can control purging.
6161		let (mut store, _temp) = test_store();
6162		store.set_time(0);
6163
6164		// Reuse helpers from this module.
6165		let t42 = topic(42);
6166		let k7 = dec_key(7);
6167
6168		// Account A = 4 (has per-account limits (4, 1000) in the mock runtime)
6169		// - Mix of topic, decryption-key and channel to exercise every index.
6170		let mut s_a1 = unsigned_statement(4, 10, Some(100), 100);
6171		s_a1.set_topic(0, t42);
6172		sign_with(&mut s_a1, 4);
6173		let h_a1 = s_a1.hash();
6174
6175		let mut s_a2 = unsigned_statement(4, 20, Some(200), 150);
6176		s_a2.set_decryption_key(k7);
6177		sign_with(&mut s_a2, 4);
6178		let h_a2 = s_a2.hash();
6179
6180		let s_a3 = statement(4, 30, None, 50);
6181		let h_a3 = s_a3.hash();
6182
6183		// Account B = 3 (control group that must remain untouched).
6184		let s_b1 = statement(3, 10, None, 100);
6185		let h_b1 = s_b1.hash();
6186
6187		let mut s_b2 = unsigned_statement(3, 15, Some(300), 100);
6188		s_b2.set_topic(0, t42);
6189		s_b2.set_decryption_key(k7);
6190		sign_with(&mut s_b2, 3);
6191		let h_b2 = s_b2.hash();
6192
6193		// Submit all statements.
6194		for s in [&s_a1, &s_a2, &s_a3, &s_b1, &s_b2] {
6195			assert_eq!(store.submit(s.clone(), StatementSource::Network), SubmitResult::New);
6196		}
6197
6198		// --- Pre-conditions: everything is indexed as expected.
6199		{
6200			assert_eq!(store.statement_count(), 5, "all 5 should be present");
6201			assert!(store.has_account(&account(4)));
6202			assert!(store.has_account(&account(3)));
6203			assert_eq!(store.total_size(), 100 + 150 + 50 + 100 + 100);
6204
6205			// Topic and key sets contain both A & B entries.
6206			assert!(store.index_has_topic(&t42, &h_a1) && store.index_has_topic(&t42, &h_b2));
6207			assert!(
6208				store.index_has_dec_key(&Some(k7), &h_a2) &&
6209					store.index_has_dec_key(&Some(k7), &h_b2)
6210			);
6211		}
6212
6213		// --- Action: remove all statements by Account A.
6214		store.remove_by(account(4)).expect("remove_by should succeed");
6215
6216		// --- Post-conditions: A's statements are gone and marked expired; B's remain.
6217		{
6218			// A's statements removed from DB view.
6219			for h in [h_a1, h_a2, h_a3] {
6220				assert!(store.statement(&h).unwrap().is_none(), "A's statement should be removed");
6221			}
6222
6223			// B's statements still present.
6224			for h in [h_b1, h_b2] {
6225				assert!(store.statement(&h).unwrap().is_some(), "B's statement should remain");
6226			}
6227
6228			// Account index updated.
6229			assert!(!store.has_account(&account(4)), "Account A must be gone");
6230			assert!(store.has_account(&account(3)), "Account B must remain");
6231			// Entry count & total_size reflect only B's data.
6232			assert_eq!(store.statement_count(), 2);
6233			assert_eq!(store.total_size(), 100 + 100);
6234
6235			// Removed statements are banned in the on-disk evicted journal.
6236			assert!(store.is_evicted(&h_a1));
6237			assert!(store.is_evicted(&h_a2));
6238			assert!(store.is_evicted(&h_a3));
6239			assert_eq!(store.evicted_count(), 3);
6240
6241			// Topic index: only B2 remains for topic 42.
6242			assert!(store.index_has_topic(&t42, &h_b2));
6243			assert!(!store.index_has_topic(&t42, &h_a1));
6244
6245			// Decryption-key index: only B2 remains for key 7.
6246			assert!(store.index_has_dec_key(&Some(k7), &h_b2));
6247			assert!(!store.index_has_dec_key(&Some(k7), &h_a2));
6248		}
6249
6250		// --- Idempotency: removing again is a no-op and should not error.
6251		store.remove_by(account(4)).expect("second remove_by should be a no-op");
6252
6253		// --- Purge: advance time beyond TTL and run maintenance; expired entries disappear.
6254		let purge_after = store.submit_index.read().config.purge_after_sec;
6255		store.set_time(purge_after + 1);
6256		store.maintain();
6257		assert_eq!(store.evicted_count(), 0, "expired entries should be purged");
6258
6259		// --- Reuse: Account A can submit again after purge.
6260		let s_new = statement(4, 40, None, 10);
6261		assert_eq!(store.submit(s_new, StatementSource::Network), SubmitResult::New);
6262	}
6263
6264	#[test]
6265	fn check_expiration_expires_statements_past_current_time() {
6266		let (mut store, _temp) = test_store();
6267
6268		// The check_expiration function compares Expiry(current_time << 32) against
6269		// Expiry(expiry) where expiry is the full 64-bit value with timestamp in high 32 bits.
6270		// Statements with expiration timestamp < current_time will be expired.
6271
6272		store.set_time(100);
6273
6274		// Create a statement that will expire at timestamp 500
6275		let mut expired_stmt = unsigned_statement(1, 1, None, 100);
6276		expired_stmt.set_expiry_from_parts(500, 1);
6277		sign_with(&mut expired_stmt, 1);
6278		let expired_hash = expired_stmt.hash();
6279		store.submit(expired_stmt, StatementSource::Network);
6280
6281		// Create a statement that won't expire (far future expiry)
6282		let valid_stmt = statement(2, 1, None, 100); // Uses u32::MAX as timestamp
6283		let valid_hash = valid_stmt.hash();
6284		store.submit(valid_stmt, StatementSource::Network);
6285
6286		// Verify both statements are in the store
6287		assert_eq!(store.statement_count(), 2);
6288
6289		// Advance time past the expiry of the first statement
6290		store.set_time(1000);
6291
6292		// The sweep should find and expire the statement
6293		store.enforce_limits();
6294
6295		// Naturally-expired statements are not added to the expired map (AlreadyExpired check
6296		// in submit rejects them without consulting the map)
6297		assert!(
6298			!store.is_evicted(&expired_hash),
6299			"Naturally expired statement must not be added to the expired map"
6300		);
6301		assert!(
6302			!store.has_statement(&expired_hash),
6303			"Expired statement should be removed from the store"
6304		);
6305
6306		// The valid statement should still be stored
6307		assert!(store.has_statement(&valid_hash), "Valid statement should still be stored");
6308		assert!(!store.is_evicted(&valid_hash), "Valid statement should not be expired");
6309	}
6310
6311	#[test]
6312	fn allowance_sweep_resumes_from_cursor_across_calls() {
6313		use std::time::Duration;
6314
6315		let (mut store, _temp) = test_store();
6316		store.set_time(0);
6317
6318		// Five accounts, each 200 data bytes over its 1000-byte allowance, so enforcement
6319		// evicts exactly one statement per account processed.
6320		for seed in 10u64..15 {
6321			store.force_insert(&statement(seed, 1, None, 600));
6322			store.force_insert(&statement(seed, 2, None, 600));
6323		}
6324		assert_eq!(store.statement_count(), 10);
6325		assert!(store.submit_index.read().allowance_cursor.is_none());
6326
6327		// With a budget of two accounts per call, the sweep needs three calls to cover all
6328		// five, resuming from the stored cursor each time.
6329		store.enforce_limits_bounded(usize::MAX, 2, Duration::from_secs(3600));
6330		assert_eq!(store.statement_count(), 8);
6331		assert!(store.submit_index.read().allowance_cursor.is_some());
6332
6333		store.enforce_limits_bounded(usize::MAX, 2, Duration::from_secs(3600));
6334		assert_eq!(store.statement_count(), 6);
6335		assert!(store.submit_index.read().allowance_cursor.is_some());
6336
6337		// The last call processes the fifth account, wraps, resets the cursor and refreshes
6338		// the account gauge with the number of accounts the pass has seen.
6339		store.enforce_limits_bounded(usize::MAX, 2, Duration::from_secs(3600));
6340		assert_eq!(store.statement_count(), 5);
6341		assert!(store.submit_index.read().allowance_cursor.is_none());
6342		assert_eq!(store.known_accounts_count.load(std::sync::atomic::Ordering::Relaxed), 5);
6343
6344		// A further unrestricted pass finds every account within its allowance.
6345		store.enforce_limits();
6346		assert_eq!(store.statement_count(), 5);
6347	}
6348
6349	#[test]
6350	fn allowance_eviction_budget_defers_the_residue_to_the_next_pass() {
6351		use std::time::Duration;
6352
6353		let (mut store, _temp) = test_store();
6354		store.set_time(0);
6355
6356		// Account 1's allowance is a single statement: three of the four must be evicted.
6357		for priority in 1..=4 {
6358			store.force_insert(&statement(1, priority, None, 100));
6359		}
6360		assert_eq!(store.statement_count(), 4);
6361
6362		// The per-call eviction budget stops enforcement mid-account. The cursor has already
6363		// moved past the account, so it is not revisited within the same pass...
6364		store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600));
6365		assert_eq!(store.statement_count(), 2);
6366
6367		// ...the pass first has to wrap, finding no further accounts...
6368		store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600));
6369		assert_eq!(store.statement_count(), 2);
6370		assert!(store.submit_index.read().allowance_cursor.is_none());
6371
6372		// ...and the next pass evicts the remaining excess statement.
6373		store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600));
6374		assert_eq!(store.statement_count(), 1);
6375	}
6376
6377	#[test]
6378	fn expiry_sweep_is_bounded_by_the_statement_budget() {
6379		use std::time::Duration;
6380
6381		let (mut store, _temp) = test_store();
6382		store.set_time(100);
6383
6384		// Five statements, all past their expiry once the clock advances.
6385		for seed in 1u64..=5 {
6386			let mut stmt = unsigned_statement(seed, 1, None, 100);
6387			stmt.set_expiry_from_parts(200, 1);
6388			sign_with(&mut stmt, seed);
6389			assert_eq!(store.submit(stmt, StatementSource::Network), SubmitResult::New);
6390		}
6391		store.set_time(300);
6392
6393		// Each call reaps at most the statement budget off the expiry index; the index itself
6394		// is the resume point, so the backlog drains across calls with no cursor involved.
6395		store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600));
6396		assert_eq!(store.statement_count(), 3);
6397		store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600));
6398		assert_eq!(store.statement_count(), 1);
6399		store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600));
6400		assert_eq!(store.statement_count(), 0);
6401		// Naturally expired statements are not banned via the evicted journal.
6402		assert_eq!(store.evicted_count(), 0);
6403	}
6404
6405	#[test]
6406	fn expiry_sweep_reports_the_remaining_backlog() {
6407		use std::time::Duration;
6408
6409		let (mut store, _temp) = test_store();
6410		store.set_time(100);
6411		for seed in 1u64..=3 {
6412			let mut stmt = unsigned_statement(seed, 1, None, 100);
6413			stmt.set_expiry_from_parts(200, 1);
6414			sign_with(&mut stmt, seed);
6415			assert_eq!(store.submit(stmt, StatementSource::Network), SubmitResult::New);
6416		}
6417		store.set_time(300);
6418
6419		// A budget of 2 leaves one statement, so the pass returns `true`.
6420		assert!(store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600)));
6421		assert_eq!(store.statement_count(), 1);
6422		// The next pass removes the last statement and returns `false`.
6423		assert!(!store.enforce_limits_bounded(2, usize::MAX, Duration::from_secs(3600)));
6424		assert_eq!(store.statement_count(), 0);
6425	}
6426
6427	#[test]
6428	fn expiry_sweep_leaves_inconsistent_data_in_place() {
6429		let (mut store, _temp) = test_store();
6430		store.set_time(100);
6431
6432		let expiry = crate::Expiry(200u64 << 32 | 1);
6433		let undecodable_hash = [0xAB_u8; 32];
6434		let undecodable_key = crate::expiry_index_key(expiry, &undecodable_hash);
6435		store
6436			.db
6437			.commit([
6438				(col::STATEMENTS, undecodable_hash.to_vec(), Some(vec![0xFF])),
6439				(col::INDEX_BY_EXPIRY, undecodable_key.clone(), Some(Vec::new())),
6440			])
6441			.unwrap();
6442
6443		// The sweep cannot remove the statement; the corruption is logged as an error and
6444		// everything is left exactly as it is, on every pass. Nothing was removed, so the sweep
6445		// reports no backlog instead of asking to be rerun forever.
6446		store.set_time(300);
6447		assert!(!store.enforce_limits());
6448		assert!(!store.enforce_limits());
6449		assert!(store.has_statement(&undecodable_hash));
6450		assert!(store.db.get(col::INDEX_BY_EXPIRY, &undecodable_key).unwrap().is_some());
6451
6452		// Same for an expiry row with no body behind it at all: the sweep reports it and leaves
6453		// it in place.
6454		let orphan_hash = [0xCD_u8; 32];
6455		let orphan_key = crate::expiry_index_key(expiry, &orphan_hash);
6456		store
6457			.db
6458			.commit([(col::INDEX_BY_EXPIRY, orphan_key.clone(), Some(Vec::new()))])
6459			.unwrap();
6460		assert!(!store.enforce_limits());
6461		assert!(!store.has_statement(&orphan_hash));
6462		assert!(store.db.get(col::INDEX_BY_EXPIRY, &orphan_key).unwrap().is_some());
6463	}
6464
6465	#[test]
6466	fn corrupt_account_index_key_does_not_end_account_enumeration() {
6467		let (store, _temp) = test_store();
6468		assert_eq!(
6469			store.submit(statement(1, 1, None, 1), StatementSource::Network),
6470			SubmitResult::New
6471		);
6472		assert_eq!(
6473			store.submit(statement(2, 1, None, 1), StatementSource::Network),
6474			SubmitResult::New
6475		);
6476		assert_eq!(store.account_count(), 2);
6477
6478		// Two unparseable keys: one sorting before every valid key (but after the scan's
6479		// starting cursor) and one sorting between the two accounts' rows. Both must be skipped
6480		// by account enumeration, not taken for the end of the index.
6481		let (first, second) = {
6482			let (a, b) = (account(1), account(2));
6483			if a < b {
6484				(a, b)
6485			} else {
6486				(b, a)
6487			}
6488		};
6489		let mut between = first.to_vec();
6490		between.extend_from_slice(&[0xFF; 41]);
6491		store
6492			.db
6493			.commit([
6494				(col::INDEX_BY_ACCOUNT, vec![0u8; 33], Some(Vec::new())),
6495				(col::INDEX_BY_ACCOUNT, between, Some(Vec::new())),
6496			])
6497			.unwrap();
6498
6499		assert_eq!(store.account_count(), 2);
6500		assert!(store.has_account(&first));
6501		assert!(store.has_account(&second));
6502
6503		// A full allowance pass still sees both accounts and reports the true account count.
6504		store.enforce_limits();
6505		assert_eq!(store.known_accounts_count.load(std::sync::atomic::Ordering::Relaxed), 2);
6506	}
6507
6508	#[test]
6509	fn concurrent_remove_and_resubmit_keep_query_bookkeeping_consistent() {
6510		// Exercises the #12624 interleaving: a `remove` racing a resubmission of the same
6511		// statement must never apply its query-index bookkeeping on top of the newer submit's.
6512		// The invariant below holds for any timing, so the test is deterministic even though
6513		// the race window itself is only hit probabilistically.
6514		use std::sync::Arc;
6515
6516		let (store, _temp) = test_store();
6517		let store = Arc::new(store);
6518		let mut stmt = unsigned_statement(1, 1, None, 100);
6519		stmt.set_topic(0, topic(7));
6520		sign_with(&mut stmt, 1);
6521		let hash = stmt.hash();
6522
6523		for _ in 0..200 {
6524			// The statement is live at the start of every round.
6525			if !store.has_statement(&hash) {
6526				assert_eq!(store.submit(stmt.clone(), StatementSource::Local), SubmitResult::New);
6527			}
6528			let remover = {
6529				let store = store.clone();
6530				std::thread::spawn(move || store.remove(&hash).expect("remove succeeds"))
6531			};
6532			let resubmitter = {
6533				let store = store.clone();
6534				let stmt = stmt.clone();
6535				std::thread::spawn(move || store.submit(stmt, StatementSource::Local))
6536			};
6537			remover.join().expect("remover joins");
6538			let _ = resubmitter.join().expect("resubmitter joins");
6539
6540			// Whatever the interleaving, the query-index bookkeeping must agree with the store.
6541			let query_index = store.query_index.read();
6542			let present = store.has_statement(&hash);
6543			assert_eq!(query_index.recent.contains_key(&hash), present);
6544			assert_eq!(
6545				query_index.topic_counts.get(&topic(7)).copied().unwrap_or(0),
6546				present as usize
6547			);
6548		}
6549	}
6550
6551	#[test]
6552	fn check_expiration_handles_multiple_statements_per_account() {
6553		let (mut store, _temp) = test_store();
6554		store.set_time(100);
6555
6556		// Create multiple statements for the same account with different expiry timestamps
6557		// Account 42 has limit of 42 statements
6558		let mut stmt1 = unsigned_statement(42, 1, Some(1), 100);
6559		stmt1.set_expiry_from_parts(200, 1); // Expires at timestamp 200
6560		sign_with(&mut stmt1, 42);
6561		let hash1 = stmt1.hash();
6562		store.submit(stmt1, StatementSource::Network);
6563
6564		let mut stmt2 = unsigned_statement(42, 2, Some(2), 100);
6565		stmt2.set_expiry_from_parts(300, 2); // Expires at timestamp 300
6566		sign_with(&mut stmt2, 42);
6567		let hash2 = stmt2.hash();
6568		store.submit(stmt2, StatementSource::Network);
6569
6570		let mut stmt3 = unsigned_statement(42, 3, Some(3), 100);
6571		stmt3.set_expiry_from_parts(500, 3); // Expires at timestamp 500
6572		sign_with(&mut stmt3, 42);
6573		let hash3 = stmt3.hash();
6574		store.submit(stmt3, StatementSource::Network);
6575
6576		// Verify all statements are in the store
6577		assert_eq!(store.statement_count(), 3);
6578
6579		// Advance time to 250 (stmt1 should expire since 250 > 200)
6580		store.set_time(250);
6581		store.enforce_limits();
6582
6583		{
6584			// Naturally expired statements are not added to the expired map.
6585			assert!(!store.is_evicted(&hash1), "stmt1 naturally expired, not in map");
6586			assert!(!store.is_evicted(&hash2), "stmt2 should not be expired yet");
6587			assert!(!store.is_evicted(&hash3), "stmt3 should not be expired yet");
6588			assert_eq!(store.statement_count(), 2);
6589		}
6590
6591		// Advance time to 400 (stmt2 should also expire since 400 > 300)
6592		store.set_time(400);
6593		store.enforce_limits();
6594
6595		{
6596			assert!(!store.is_evicted(&hash1));
6597			assert!(!store.is_evicted(&hash2), "stmt2 naturally expired, not in map");
6598			assert!(!store.is_evicted(&hash3), "stmt3 should not be expired yet");
6599			assert_eq!(store.statement_count(), 1);
6600		}
6601
6602		// Check again at time 600 (stmt3 should expire since 600 > 500)
6603		store.set_time(600);
6604		store.enforce_limits();
6605
6606		{
6607			assert!(!store.is_evicted(&hash1));
6608			assert!(!store.is_evicted(&hash2));
6609			assert!(!store.is_evicted(&hash3), "stmt3 naturally expired, not in map");
6610			assert_eq!(store.statement_count(), 0);
6611		}
6612	}
6613
6614	#[test]
6615	fn check_expiration_does_nothing_when_no_expired_statements() {
6616		let (mut store, _temp) = test_store();
6617		store.set_time(1000);
6618
6619		// Create statement with expiry far in the future
6620		// The statement() helper uses set_expiry_from_parts(u32::MAX, priority)
6621		let stmt = statement(1, 1, None, 100);
6622		let hash = stmt.hash();
6623		store.submit(stmt, StatementSource::Network);
6624
6625		// Check expiration - nothing should happen
6626		store.enforce_limits();
6627
6628		// Statement should still be there
6629		assert!(store.has_statement(&hash));
6630		assert!(!store.is_evicted(&hash));
6631		assert_eq!(store.statement_count(), 1);
6632		assert_eq!(store.evicted_count(), 0);
6633	}
6634
6635	#[test]
6636	fn check_expiration_correctly_updates_account_data() {
6637		let (mut store, _temp) = test_store();
6638		store.set_time(100);
6639
6640		// Create a statement with expiry at timestamp 200
6641		let mut stmt = unsigned_statement(1, 1, Some(1), 100);
6642		stmt.set_expiry_from_parts(200, 1);
6643		sign_with(&mut stmt, 1);
6644		let hash = stmt.hash();
6645		store.submit(stmt, StatementSource::Network);
6646
6647		// Verify account exists before expiration
6648		{
6649			assert!(store.has_account(&account(1)));
6650			assert_eq!(store.total_size(), 100);
6651		}
6652
6653		// Expire
6654		store.set_time(300);
6655		store.enforce_limits();
6656
6657		// Verify account is removed after its only statement expires
6658		{
6659			assert!(
6660				!store.has_account(&account(1)),
6661				"Account should be removed when all its statements expire"
6662			);
6663			assert_eq!(store.total_size(), 0, "Total size should be zero");
6664			assert!(!store.is_evicted(&hash), "Naturally expired, not in map");
6665		}
6666	}
6667
6668	#[test]
6669	fn check_expiration_clears_topic_and_key_indexes() {
6670		let (mut store, _temp) = test_store();
6671		store.set_time(100);
6672
6673		// Create a statement with topic and decryption key
6674		let mut stmt = unsigned_statement(1, 1, Some(1), 100);
6675		stmt.set_expiry_from_parts(200, 1);
6676		stmt.set_topic(0, topic(42));
6677		stmt.set_decryption_key(dec_key(7));
6678		sign_with(&mut stmt, 1);
6679		let hash = stmt.hash();
6680		store.submit(stmt, StatementSource::Network);
6681
6682		// Verify indexes are populated
6683		{
6684			assert!(store.index_has_topic(&topic(42), &hash));
6685			assert!(store.index_has_dec_key(&Some(dec_key(7)), &hash));
6686		}
6687
6688		// Expire
6689		store.set_time(300);
6690		store.enforce_limits();
6691
6692		// Verify indexes are cleared
6693		{
6694			assert!(!store.index_has_topic(&topic(42), &hash), "Topic index should be cleared");
6695			assert!(
6696				!store.index_has_dec_key(&Some(dec_key(7)), &hash),
6697				"Decryption key index should be cleared"
6698			);
6699			assert!(!store.is_evicted(&hash), "Naturally expired, not in map");
6700		}
6701	}
6702
6703	#[test]
6704	fn check_expiration_handles_empty_store() {
6705		let (mut store, _temp) = test_store();
6706		store.set_time(1000);
6707
6708		// With no statements, check_expiration should not panic
6709		store.enforce_limits();
6710
6711		// Second call should also work
6712		store.enforce_limits();
6713
6714		assert!(store.submit_index.read().allowance_cursor.is_none());
6715		assert_eq!(store.statement_count(), 0);
6716		assert_eq!(store.evicted_count(), 0);
6717	}
6718
6719	#[test]
6720	fn check_expiration_expires_properly_formatted_statements() {
6721		// With the fix (Expiry(current_time << 32)), check_expiration properly
6722		// compares timestamps and can expire statements submitted through normal flow.
6723
6724		let (mut store, _temp) = test_store();
6725		store.set_time(1000);
6726
6727		// Create a statement with expiration timestamp just 1 second in the future
6728		let mut stmt = unsigned_statement(1, 1, None, 100);
6729		stmt.set_expiry_from_parts(1001, 1); // Expires at timestamp 1001
6730		sign_with(&mut stmt, 1);
6731		let hash = stmt.hash();
6732		store.submit(stmt, StatementSource::Network);
6733
6734		assert_eq!(store.statement_count(), 1);
6735
6736		// Advance time past the expiration timestamp
6737		store.set_time(2000);
6738		store.enforce_limits();
6739
6740		// Statement SHOULD be expired because check_expiration now compares
6741		// Expiry(2000 << 32) against Expiry(1001 << 32 | 1), and
6742		// (2000 << 32) > (1001 << 32 | 1)
6743		assert!(
6744			!store.has_statement(&hash),
6745			"Statement should be removed from the store after expiration"
6746		);
6747		// Naturally expired: timestamp 1001 < current_time 2000, not added to expired map.
6748		assert!(!store.is_evicted(&hash), "Naturally expired, not in map");
6749	}
6750
6751	#[test]
6752	fn check_expiration_updates_database_columns() {
6753		// This test verifies that check_expiration properly updates the database.
6754		let (mut store, _temp) = test_store();
6755		store.set_time(100);
6756
6757		// Create a statement with expiry at timestamp 200
6758		let mut stmt = unsigned_statement(1, 1, None, 100);
6759		stmt.set_expiry_from_parts(200, 1);
6760		sign_with(&mut stmt, 1);
6761		let hash = stmt.hash();
6762		store.submit(stmt.clone(), StatementSource::Network);
6763
6764		// Verify statement is in the database
6765		let db_entry = store.db.get(col::STATEMENTS, &hash).unwrap();
6766		assert!(db_entry.is_some(), "Statement should be in col::STATEMENTS after submit");
6767
6768		// Advance time past expiry and run check_expiration
6769		store.set_time(300);
6770		store.enforce_limits();
6771
6772		// Verify the store state is updated correctly
6773		{
6774			assert_eq!(store.statement_count(), 0, "Statement should be removed from the store");
6775			// Naturally expired: not added to expired map, no need for suppression.
6776			assert!(
6777				!store.is_evicted(&hash),
6778				"Naturally expired statement must not be in the expired map"
6779			);
6780		}
6781
6782		let db_entry = store.db.get(col::STATEMENTS, &hash).unwrap();
6783		assert!(
6784			db_entry.is_none(),
6785			"Statement should be removed from col::STATEMENTS after expiration"
6786		);
6787
6788		// Naturally expired statements are not written to col::EXPIRED either, so that
6789		// the optimization survives node restarts.
6790		let expired_entry = store.db.get(col::EXPIRED, &hash).unwrap();
6791		assert!(expired_entry.is_none(), "Naturally expired: not written to col::EXPIRED");
6792	}
6793
6794	#[test]
6795	fn enforce_allowances_evicts_excess_statements() {
6796		// This test verifies that check_expiration correctly evicts statements
6797		// when statements exceed the current allowance. We directly insert into
6798		// the index (bypassing submit's validation) to simulate statements that
6799		// existed before allowances were reduced.
6800		let (mut store, _temp) = test_store();
6801		store.set_time(0);
6802
6803		// Account 4 has allowance (4 statements, 1000 bytes) from TestClient
6804		let s1 = statement(4, 10, None, 100); // lowest priority - will be evicted
6805		let s2 = statement(4, 20, None, 100);
6806		let s3 = statement(4, 30, None, 100);
6807		let s4 = statement(4, 40, None, 100);
6808		let s5 = statement(4, 50, None, 100); // highest priority
6809
6810		let h1 = s1.hash();
6811		let h5 = s5.hash();
6812
6813		// Directly insert into the store, bypassing `submit`'s allowance check
6814		for statement in [&s1, &s2, &s3, &s4, &s5] {
6815			store.force_insert(statement);
6816		}
6817
6818		// Verify initial state - all 5 should be present
6819		assert_eq!(store.statement_count(), 5);
6820		assert_eq!(store.total_size(), 500);
6821
6822		// Run check_expiration which handles both expiration and allowance enforcement
6823		// Since account 4 has max_count=4, one statement should be evicted
6824		store.enforce_limits();
6825
6826		// Should evict the lowest priority statement (s1)
6827		assert_eq!(store.statement_count(), 4, "Should have 4 statements after eviction");
6828		assert!(!store.has_statement(&h1), "Lowest priority should be evicted");
6829		assert!(store.has_statement(&h5), "Highest priority should remain");
6830		assert_eq!(store.total_size(), 400);
6831
6832		// Evicted statement should be marked as expired
6833		assert!(store.is_evicted(&h1));
6834	}
6835
6836	#[test]
6837	fn enforce_allowances_evicts_all_when_no_allowance_found() {
6838		let (mut store, _temp) = test_store();
6839		store.set_time(0);
6840
6841		// Account 0 has NO allowance in TestClient
6842		let s1 = statement(0, 10, None, 100);
6843		let s2 = statement(0, 20, None, 150);
6844
6845		let h1 = s1.hash();
6846		let h2 = s2.hash();
6847
6848		// Directly insert statements for account with no allowance
6849		store.force_insert(&s1);
6850		store.force_insert(&s2);
6851
6852		assert_eq!(store.statement_count(), 2);
6853
6854		// Run check_expiration - should evict ALL statements since no allowance exists
6855		store.enforce_limits();
6856
6857		assert_eq!(store.statement_count(), 0, "All statements should be evicted");
6858		assert!(!store.has_account(&account(0)), "Account should be removed");
6859		assert!(store.is_evicted(&h1));
6860		assert!(store.is_evicted(&h2));
6861	}
6862
6863	#[test]
6864	fn enforce_allowances_based_on_size() {
6865		// This test verifies that check_expiration evicts based on size limits.
6866		let (mut store, _temp) = test_store();
6867		store.set_time(0);
6868
6869		// Account 2 has allowance (2, 1000) from TestClient
6870		// Insert 2 statements that together exceed 1000 bytes
6871		let s1 = statement(2, 10, None, 600); // lowest priority
6872		let s2 = statement(2, 20, None, 600); // higher priority
6873
6874		let h1 = s1.hash();
6875		let h2 = s2.hash();
6876
6877		// Directly insert both statements (total 1200 bytes > 1000 limit)
6878		store.force_insert(&s1);
6879		store.force_insert(&s2);
6880
6881		assert_eq!(store.total_size(), 1200);
6882
6883		// Run check_expiration - should evict s1 to get under 1000 bytes
6884		store.enforce_limits();
6885
6886		assert_eq!(store.statement_count(), 1);
6887		assert!(store.has_statement(&h2), "Higher priority should remain");
6888		assert!(!store.has_statement(&h1), "Lower priority should be evicted");
6889		assert_eq!(store.total_size(), 600);
6890	}
6891
6892	#[test]
6893	fn enforce_allowances_takes_larger_of_best_and_finalized() {
6894		// (max_count, max_size) at the finalized and the best block: the count, then the size,
6895		// raised and lowered in a best block not finalized yet
6896		let cases = [
6897			((2, 1000), (3, 1000)),
6898			((3, 1000), (2, 1000)),
6899			((4, 200), (4, 300)),
6900			((4, 300), (4, 200)),
6901		];
6902		for (finalized, best) in cases {
6903			let (mut store, _temp) = test_store();
6904			store.set_time(0);
6905			store.read_allowance_fn = Box::new(move |_who: &AccountId, block: AllowanceBlock| {
6906				let (max_count, max_size) = match block {
6907					AllowanceBlock::Finalized => finalized,
6908					AllowanceBlock::Best => best,
6909				};
6910				Ok(Some(StatementAllowance::new(max_count, max_size)))
6911			});
6912			let statements = [10, 20, 30, 40].map(|priority| statement(7, priority, None, 100));
6913			for statement in &statements {
6914				store.force_insert(statement);
6915			}
6916
6917			store.enforce_limits();
6918
6919			assert_eq!(store.statement_count(), 3);
6920			assert!(store.is_evicted(&statements[0].hash()));
6921		}
6922	}
6923
6924	#[test]
6925	fn channel_replacement_only_higher_priority_succeeds() {
6926		let (store, _temp) = test_store();
6927		let source = StatementSource::Network;
6928
6929		// Account 1: max_count=1, max_size=1000
6930		// Submit channel 1 with priority 5
6931		let s1 = statement(1, 5, Some(1), 100);
6932		let h1 = s1.hash();
6933		assert_eq!(store.submit(s1, source), SubmitResult::New);
6934
6935		// Lower priority on same channel → ChannelPriorityTooLow
6936		let result = store.submit(statement(1, 3, Some(1), 100), source);
6937		assert!(
6938			matches!(result, SubmitResult::Rejected(RejectionReason::ChannelPriorityTooLow { .. })),
6939			"Lower priority should be rejected with ChannelPriorityTooLow, got: {result:?}"
6940		);
6941
6942		// Equal priority on same channel → ChannelPriorityTooLow (check is <=)
6943		// Use different data_len to get a distinct hash with same priority
6944		let result = store.submit(statement(1, 5, Some(1), 101), source);
6945		assert!(
6946			matches!(result, SubmitResult::Rejected(RejectionReason::ChannelPriorityTooLow { .. })),
6947			"Equal priority should be rejected with ChannelPriorityTooLow, got: {result:?}"
6948		);
6949
6950		// Higher priority on same channel → replaces
6951		let s2 = statement(1, 10, Some(1), 200);
6952		let h2 = s2.hash();
6953		assert_eq!(store.submit(s2, source), SubmitResult::New);
6954
6955		{
6956			assert_eq!(store.statement_count(), 1);
6957			assert!(!store.has_statement(&h1), "Old channel message should be gone");
6958			assert!(store.has_statement(&h2), "New channel message should exist");
6959			assert!(store.is_evicted(&h1), "Old should be in expired");
6960			assert_eq!(store.total_size(), 200);
6961		}
6962	}
6963
6964	#[test]
6965	fn submit_rejects_malformed_statements() {
6966		let (store, _temp) = test_store();
6967
6968		let mut base = Statement::new();
6969		base.set_expiry(u64::MAX);
6970		base.set_plain_data(vec![1]);
6971		base.set_topic(0, default_topic());
6972
6973		let ed_kp = sp_core::ed25519::Pair::from_string("//Alice", None).unwrap();
6974		let sr_kp = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap();
6975		let ecdsa_kp = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap();
6976
6977		assert_eq!(
6978			store.submit(base.clone(), StatementSource::Network),
6979			SubmitResult::Invalid(InvalidReason::NoProof)
6980		);
6981
6982		let bad_proofs = [
6983			Proof::Ed25519 { signature: [0xAB; 64], signer: ed_kp.public().0 },
6984			Proof::Sr25519 { signature: [0xCD; 64], signer: sr_kp.public().0 },
6985			Proof::Secp256k1Ecdsa { signature: [0xEF; 65], signer: ecdsa_kp.public().0 },
6986		];
6987		for proof in bad_proofs {
6988			let mut s = base.clone();
6989			s.set_proof(proof);
6990			assert_eq!(
6991				store.submit(s, StatementSource::Network),
6992				SubmitResult::Invalid(InvalidReason::BadProof)
6993			);
6994		}
6995
6996		let mut wrong_signer = base.clone();
6997		wrong_signer.sign_ed25519_private(&ed_kp);
6998		let alice_sig = match wrong_signer.proof().unwrap() {
6999			Proof::Ed25519 { signature, .. } => *signature,
7000			_ => panic!("expected Ed25519 proof after sign_ed25519_private"),
7001		};
7002		let bob_kp = sp_core::ed25519::Pair::from_string("//Bob", None).unwrap();
7003		wrong_signer.set_proof(Proof::Ed25519 { signature: alice_sig, signer: bob_kp.public().0 });
7004		assert_eq!(
7005			store.submit(wrong_signer, StatementSource::Network),
7006			SubmitResult::Invalid(InvalidReason::BadProof)
7007		);
7008	}
7009
7010	#[test]
7011	fn submit_rejects_statement_without_topics() {
7012		let (store, _temp) = test_store();
7013
7014		for source in [StatementSource::Network, StatementSource::Local, StatementSource::Chain] {
7015			let statement = signed_statement_with_topics(1, &[], None);
7016			assert_eq!(
7017				store.submit(statement, source),
7018				SubmitResult::Invalid(InvalidReason::NoTopics)
7019			);
7020		}
7021		assert_eq!(store.statements().unwrap().len(), 0);
7022	}
7023
7024	#[test]
7025	fn channel_replacement_with_size_increase_evicts_others() {
7026		let (store, _temp) = test_store();
7027		let source = StatementSource::Network;
7028
7029		// Account 3: max_count=3, max_size=1000
7030		// channel msg (200b) + two non-channel msgs (300b each) = 800b
7031		let s_ch = statement(3, 5, Some(1), 200);
7032		let s_low = statement(3, 2, None, 300);
7033		let s_mid = statement(3, 3, None, 300);
7034		let h_ch = s_ch.hash();
7035		let h_low = s_low.hash();
7036		let h_mid = s_mid.hash();
7037
7038		assert_eq!(store.submit(s_ch, source), SubmitResult::New);
7039		assert_eq!(store.submit(s_low, source), SubmitResult::New);
7040		assert_eq!(store.submit(s_mid, source), SubmitResult::New);
7041		assert_eq!(store.total_size(), 800);
7042
7043		// Replace channel with 600b message (priority 10 > 5)
7044		// Must evict lowest priority non-channel statement (priority 2) to fit
7045		let s_ch_big = statement(3, 10, Some(1), 600);
7046		let h_ch_big = s_ch_big.hash();
7047		assert_eq!(store.submit(s_ch_big, source), SubmitResult::New);
7048
7049		{
7050			assert_eq!(store.statement_count(), 2);
7051			assert!(!store.has_statement(&h_ch), "Old channel message replaced");
7052			assert!(!store.has_statement(&h_low), "Priority 2 evicted to fit size");
7053			assert!(store.has_statement(&h_mid), "Priority 3 should remain");
7054			assert!(store.has_statement(&h_ch_big), "New channel message added");
7055			assert_eq!(store.total_size(), 900); // 300 (mid) + 600 (new channel)
7056		}
7057	}
7058
7059	#[test]
7060	fn subscription_reconnect_receives_current_state() {
7061		use crate::StatementStoreSubscriptionApi;
7062		use sp_statement_store::OptimizedTopicFilter;
7063
7064		let (store, _temp) = test_store();
7065		let source = StatementSource::Local;
7066
7067		// Submit 3 statements
7068		for i in 0..3u8 {
7069			let res = store.submit(signed_statement(i), source);
7070			assert_eq!(res, SubmitResult::New);
7071		}
7072
7073		// First subscribe → should get 3 existing statements
7074		let (existing, sender, stream) =
7075			store.subscribe_statement(OptimizedTopicFilter::Any).unwrap();
7076		assert_eq!(existing.len(), 3, "First subscribe should return 3 existing statements");
7077
7078		// Drop stream
7079		drop(stream);
7080		drop(sender);
7081
7082		// Submit 2 more while disconnected
7083		for i in 3..5u8 {
7084			assert_eq!(store.submit(signed_statement(i), source), SubmitResult::New);
7085		}
7086		let (existing, sender, stream) =
7087			store.subscribe_statement(OptimizedTopicFilter::Any).unwrap();
7088		assert_eq!(existing.len(), 5, "Re-subscribe should return all 5 current statements");
7089
7090		// Drop and remove one statement
7091		drop(stream);
7092		drop(sender);
7093		let hash_to_remove = signed_statement(0).hash();
7094		store.remove(&hash_to_remove).unwrap();
7095
7096		// Re-subscribe → should get 4
7097		let (existing, _sender, _stream) =
7098			store.subscribe_statement(OptimizedTopicFilter::Any).unwrap();
7099		assert_eq!(existing.len(), 4, "Re-subscribe after removal should return 4 statements");
7100	}
7101
7102	#[test]
7103	fn subscription_reconnect_with_topic_filter() {
7104		use crate::StatementStoreSubscriptionApi;
7105		use sp_statement_store::OptimizedTopicFilter;
7106
7107		let (store, _temp) = test_store();
7108		let source = StatementSource::Local;
7109		let topic_a = topic(1);
7110		let topic_b = topic(2);
7111
7112		// s1: topic A only
7113		let s1 = signed_statement_with_topics(1, &[topic_a], None);
7114		// s2: topic B only
7115		let s2 = signed_statement_with_topics(2, &[topic_b], None);
7116		// s3: topics A + B
7117		let s3 = signed_statement_with_topics(3, &[topic_a, topic_b], None);
7118
7119		assert_eq!(store.submit(s1, source), SubmitResult::New);
7120		assert_eq!(store.submit(s2, source), SubmitResult::New);
7121		assert_eq!(store.submit(s3, source), SubmitResult::New);
7122
7123		// Subscribe with MatchAll([A]) → s1, s3
7124		let filter_a = OptimizedTopicFilter::MatchAll(std::collections::HashSet::from([topic_a]));
7125		let (existing, sender, stream) = store.subscribe_statement(filter_a.clone()).unwrap();
7126		assert_eq!(existing.len(), 2, "MatchAll([A]) should match s1 and s3");
7127
7128		// Drop and add s4 with topic A
7129		drop(sender);
7130		drop(stream);
7131		let s4 = signed_statement_with_topics(4, &[topic_a], None);
7132		assert_eq!(store.submit(s4, source), SubmitResult::New);
7133		// Re-subscribe with same filter → s1, s3, s4
7134		let (existing, sender, stream) = store.subscribe_statement(filter_a).unwrap();
7135		assert_eq!(existing.len(), 3, "Re-subscribe MatchAll([A]) should return s1, s3, s4");
7136
7137		// Drop and re-subscribe with different filter MatchAll([B]) → s2, s3
7138		drop(sender);
7139		drop(stream);
7140		let filter_b = OptimizedTopicFilter::MatchAll(std::collections::HashSet::from([topic_b]));
7141		let (existing, _sender, _stream) = store.subscribe_statement(filter_b).unwrap();
7142		assert_eq!(existing.len(), 2, "Re-subscribe MatchAll([B]) should return s2 and s3");
7143	}
7144
7145	#[tokio::test]
7146	async fn subscription_delivers_each_statement_exactly_once_across_boundary() {
7147		// Exactly-once: a statement existing before the subscription is delivered only through the
7148		// initial snapshot, and a statement submitted afterwards only through the live stream —
7149		// never both (which was the at-least-once regression) and never neither.
7150		use crate::StatementStoreSubscriptionApi;
7151		use futures::StreamExt;
7152		use sp_statement_store::{OptimizedTopicFilter, StatementEvent};
7153
7154		let (store, _temp) = test_store();
7155		let source = StatementSource::Local;
7156
7157		// Two statements exist before the subscription is created.
7158		let a = signed_statement(0);
7159		let b = signed_statement(1);
7160		assert_eq!(store.submit(a.clone(), source), SubmitResult::New);
7161		assert_eq!(store.submit(b.clone(), source), SubmitResult::New);
7162
7163		// The snapshot must contain exactly the pre-existing statements.
7164		let (existing, _sender, mut stream) =
7165			store.subscribe_statement(OptimizedTopicFilter::Any).unwrap();
7166		let mut snapshot: Vec<Statement> = existing
7167			.iter()
7168			.map(|bytes| Statement::decode(&mut &bytes[..]).unwrap())
7169			.collect();
7170		snapshot.sort_by_key(|s| s.hash());
7171		let mut expected_snapshot = vec![a.clone(), b.clone()];
7172		expected_snapshot.sort_by_key(|s| s.hash());
7173		assert_eq!(
7174			snapshot, expected_snapshot,
7175			"snapshot must contain exactly the pre-existing statements"
7176		);
7177
7178		// A statement submitted after the subscription must arrive on the live stream, exactly
7179		// once.
7180		let c = signed_statement(2);
7181		assert_eq!(store.submit(c.clone(), source), SubmitResult::New);
7182
7183		let event = tokio::time::timeout(std::time::Duration::from_secs(5), stream.next())
7184			.await
7185			.expect("live statement should arrive within the timeout")
7186			.expect("stream should yield an event");
7187		let StatementEvent::NewStatements { statements, .. } = event;
7188		let live: Vec<Statement> = statements
7189			.iter()
7190			.map(|bytes| Statement::decode(&mut &bytes.0[..]).unwrap())
7191			.collect();
7192		assert_eq!(
7193			live,
7194			vec![c.clone()],
7195			"live stream must deliver exactly the post-subscribe statement"
7196		);
7197
7198		// No duplicate: neither the new statement nor the snapshot statements are delivered again.
7199		assert!(
7200			tokio::time::timeout(std::time::Duration::from_millis(500), stream.next())
7201				.await
7202				.is_err(),
7203			"no further (duplicate) statements must be delivered"
7204		);
7205	}
7206
7207	#[test]
7208	fn subscription_snapshot_deduplicates_multi_topic_match_any() {
7209		// A `MatchAny` snapshot must contain a statement matching several of the filter's topics
7210		// only once, not once per matching topic.
7211		use crate::StatementStoreSubscriptionApi;
7212		use sp_statement_store::OptimizedTopicFilter;
7213
7214		let (store, _temp) = test_store();
7215		let topic_a = topic(1);
7216		let topic_b = topic(2);
7217
7218		// A statement carrying BOTH topics.
7219		let s = signed_statement_with_topics(1, &[topic_a, topic_b], None);
7220		assert_eq!(store.submit(s, StatementSource::Local), SubmitResult::New);
7221
7222		let filter =
7223			OptimizedTopicFilter::MatchAny(std::collections::HashSet::from([topic_a, topic_b]));
7224		let (existing, _sender, _stream) = store.subscribe_statement(filter).unwrap();
7225		assert_eq!(
7226			existing.len(),
7227			1,
7228			"MatchAny snapshot must not duplicate a multi-topic statement"
7229		);
7230	}
7231
7232	#[tokio::test]
7233	async fn subscription_match_all_delivers_exactly_once_across_boundary() {
7234		// The `MatchAll` snapshot is enumerated authoritatively from disk, so a matching statement
7235		// present before the subscription is delivered via the snapshot (never lost to the
7236		// in-memory counters/cache lagging a commit), while one submitted afterwards is delivered
7237		// live exactly once.
7238		use crate::StatementStoreSubscriptionApi;
7239		use futures::StreamExt;
7240		use sp_statement_store::{OptimizedTopicFilter, StatementEvent};
7241
7242		let (store, _temp) = test_store();
7243		let source = StatementSource::Local;
7244		let t = topic(7);
7245
7246		// Two matching statements exist before the subscription.
7247		let a = signed_statement_with_topics(0, &[t], None);
7248		let b = signed_statement_with_topics(1, &[t], None);
7249		assert_eq!(store.submit(a, source), SubmitResult::New);
7250		assert_eq!(store.submit(b, source), SubmitResult::New);
7251
7252		let filter = OptimizedTopicFilter::MatchAll(std::collections::HashSet::from([t]));
7253		let (existing, _sender, mut stream) = store.subscribe_statement(filter).unwrap();
7254		assert_eq!(
7255			existing.len(),
7256			2,
7257			"MatchAll snapshot must contain both pre-existing statements"
7258		);
7259
7260		// A matching statement submitted afterwards must arrive live, exactly once.
7261		let c = signed_statement_with_topics(2, &[t], None);
7262		assert_eq!(store.submit(c.clone(), source), SubmitResult::New);
7263
7264		let event = tokio::time::timeout(std::time::Duration::from_secs(5), stream.next())
7265			.await
7266			.expect("live statement should arrive within the timeout")
7267			.expect("stream should yield an event");
7268		let StatementEvent::NewStatements { statements, .. } = event;
7269		let live: Vec<Statement> = statements
7270			.iter()
7271			.map(|bytes| Statement::decode(&mut &bytes.0[..]).unwrap())
7272			.collect();
7273		assert_eq!(
7274			live,
7275			vec![c],
7276			"MatchAll live stream must deliver exactly the post-subscribe statement"
7277		);
7278
7279		assert!(
7280			tokio::time::timeout(std::time::Duration::from_millis(500), stream.next())
7281				.await
7282				.is_err(),
7283			"no further (duplicate) statements must be delivered"
7284		);
7285	}
7286
7287	#[tokio::test]
7288	async fn subscription_no_loss_or_duplicate_under_concurrent_submits() {
7289		// Race a stream of submissions against the subscription registration: whatever the
7290		// interleaving, every matching statement must be delivered exactly once across the snapshot
7291		// and the live stream — no loss (the bug the on-disk `MatchAll` snapshot could cause) and
7292		// no duplicate (the original at-least-once regression). This assertion holds for any
7293		// timing, so the test is deterministic even though the race window is hit
7294		// non-deterministically.
7295		use crate::StatementStoreSubscriptionApi;
7296		use futures::StreamExt;
7297		use sp_statement_store::{OptimizedTopicFilter, StatementEvent};
7298		use std::collections::HashSet;
7299
7300		let (store, _temp) = test_store();
7301		let store = std::sync::Arc::new(store);
7302		let t = topic(9);
7303		// Keep well under SUBSCRIPTION_BUFFER_SIZE (128) so the live channel never overflows (which
7304		// would auto-unsubscribe and legitimately drop statements).
7305		const N: u8 = 60;
7306
7307		let all: Vec<Statement> =
7308			(0..N).map(|i| signed_statement_with_topics(i, &[t], None)).collect();
7309		let all_hashes: HashSet<_> = all.iter().map(|s| s.hash()).collect();
7310
7311		// A handful exist before subscribing; the rest are submitted concurrently with the
7312		// subscribe.
7313		let split = 10usize;
7314		for s in &all[..split] {
7315			assert_eq!(store.submit(s.clone(), StatementSource::Local), SubmitResult::New);
7316		}
7317		let store2 = store.clone();
7318		let rest: Vec<Statement> = all[split..].to_vec();
7319		let submitter = std::thread::spawn(move || {
7320			for s in rest {
7321				let _ = store2.submit(s, StatementSource::Local);
7322			}
7323		});
7324
7325		let filter = OptimizedTopicFilter::MatchAll(HashSet::from([t]));
7326		let (existing, _sender, mut stream) = store.subscribe_statement(filter).unwrap();
7327
7328		submitter.join().unwrap();
7329
7330		// Everything delivered so far, snapshot first.
7331		let mut seen = existing
7332			.iter()
7333			.map(|b| Statement::decode(&mut &b[..]).unwrap().hash())
7334			.collect::<Vec<_>>();
7335		// Drain the live stream until every statement is accounted for (or a timeout on loss).
7336		while seen.len() < N as usize {
7337			match tokio::time::timeout(std::time::Duration::from_secs(5), stream.next()).await {
7338				Ok(Some(StatementEvent::NewStatements { statements, .. })) => {
7339					for b in statements {
7340						seen.push(Statement::decode(&mut &b.0[..]).unwrap().hash());
7341					}
7342				},
7343				_ => break,
7344			}
7345		}
7346
7347		let seen_set: HashSet<_> = seen.iter().copied().collect();
7348		assert_eq!(
7349			seen.len(),
7350			N as usize,
7351			"each statement must be delivered exactly once (got {} deliveries for {} statements — loss or duplicate)",
7352			seen.len(),
7353			N
7354		);
7355		assert_eq!(seen_set, all_hashes, "delivered set must equal submitted set");
7356	}
7357
7358	// Tests for the multi-filter subscription API (`MultiFilterSubscriptionApi` /
7359	// `create_subscription`), as opposed to the single-filter `subscribe_statement` tests above.
7360	mod multi_filter {
7361		use super::*;
7362		use crate::{
7363			MultiFilterEventStream, MultiFilterSubscriptionApi, MultiFilterSubscriptionEvent,
7364		};
7365		use futures::StreamExt;
7366		use sp_statement_store::OptimizedTopicFilter;
7367		use std::{collections::HashSet, sync::Arc, time::Duration};
7368
7369		fn arc_test_store() -> (Arc<Store>, tempfile::TempDir) {
7370			let (store, dir) = test_store();
7371			(Arc::new(store), dir)
7372		}
7373
7374		async fn drain_all(
7375			stream: &mut MultiFilterEventStream,
7376			idle: Duration,
7377		) -> Vec<MultiFilterSubscriptionEvent> {
7378			let mut events = Vec::new();
7379			while let Ok(Some(event)) = tokio::time::timeout(idle, stream.next()).await {
7380				events.push(event);
7381			}
7382			events
7383		}
7384
7385		#[test]
7386		fn replay_watermark_excludes_later_admissions() {
7387			let (store, _dir) = test_store();
7388			let before = signed_statement(1);
7389			let after = signed_statement(2);
7390			assert_eq!(store.submit(before.clone(), StatementSource::Local), SubmitResult::New);
7391
7392			let mut watermark = None;
7393			assert!(store
7394				.register_replay(&mut |captured| {
7395					watermark = Some(captured);
7396					true
7397				})
7398				.unwrap()
7399				.is_some());
7400			assert_eq!(store.submit(after.clone(), StatementSource::Local), SubmitResult::New);
7401
7402			let replay =
7403				store.replay_batch(&OptimizedTopicFilter::Any, 0, watermark.unwrap()).unwrap();
7404			let hashes: HashSet<_> = replay
7405				.statements
7406				.iter()
7407				.map(|encoded| Statement::decode(&mut encoded.as_slice()).unwrap().hash())
7408				.collect();
7409			assert!(replay.done);
7410			assert!(hashes.contains(&before.hash()));
7411			assert!(!hashes.contains(&after.hash()));
7412		}
7413
7414		#[tokio::test]
7415		async fn add_filter_replays_snapshot_and_delivers_later_submissions_live() {
7416			let (store, _dir) = arc_test_store();
7417			let (handle, mut stream) = store.create_subscription();
7418
7419			const NUM_STATEMENTS: u8 = 50;
7420			const NUM_PRE_FILTER: u8 = 20;
7421
7422			// Statements stored before the filter is attached; the replay must cover exactly these.
7423			for i in 0..NUM_PRE_FILTER {
7424				let stmt = signed_statement(i);
7425				assert_eq!(store.submit(stmt, StatementSource::Local), SubmitResult::New);
7426			}
7427
7428			let filter_id = handle.add_filter(OptimizedTopicFilter::Any).unwrap();
7429
7430			// The watermark is captured atomically with the filter registration, so statements
7431			// submitted after `add_filter` returns sit above it and arrive as live events only.
7432			for i in NUM_PRE_FILTER..NUM_STATEMENTS {
7433				let stmt = signed_statement(i);
7434				assert_eq!(store.submit(stmt, StatementSource::Local), SubmitResult::New);
7435			}
7436
7437			let mut snapshot_hashes: HashSet<[u8; 32]> = HashSet::new();
7438			let mut live_with_filter: HashSet<[u8; 32]> = HashSet::new();
7439			for event in drain_all(&mut stream, Duration::from_millis(300)).await {
7440				match event {
7441					MultiFilterSubscriptionEvent::ReplayStatements { statements, .. } => {
7442						snapshot_hashes.extend(
7443							statements
7444								.iter()
7445								.map(|bytes| Statement::decode(&mut &bytes[..]).unwrap().hash()),
7446						);
7447					},
7448					MultiFilterSubscriptionEvent::NewStatement(event)
7449						if event.matched_filter_ids.contains(&filter_id) =>
7450					{
7451						live_with_filter.insert(event.hash);
7452					},
7453					_ => {},
7454				}
7455			}
7456
7457			let expected_replayed: HashSet<[u8; 32]> =
7458				(0..NUM_PRE_FILTER).map(|i| signed_statement(i).hash()).collect();
7459			let expected_live: HashSet<[u8; 32]> =
7460				(NUM_PRE_FILTER..NUM_STATEMENTS).map(|i| signed_statement(i).hash()).collect();
7461
7462			assert_eq!(snapshot_hashes, expected_replayed);
7463			assert_eq!(live_with_filter, expected_live);
7464		}
7465	}
7466}