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//! Disk-backed statement store.
20//!
21//! This module contains an implementation of `sp_statement_store::StatementStore` which is backed
22//! by a database.
23//!
24//! Constraint management.
25//!
26//! Each time a new statement is inserted into the store, it is first validated with the runtime
27//! Validation function computes `global_priority`, 'max_count' and `max_size` for a statement.
28//! The following constraints are then checked:
29//! * For a given account id, there may be at most `max_count` statements with `max_size` total data
30//!   size. To satisfy this, statements for this account ID are removed from the store starting with
31//!   the lowest priority until a constraint is satisfied.
32//! * There may not be more than `MAX_TOTAL_STATEMENTS` total statements with `MAX_TOTAL_SIZE` size.
33//!   To satisfy this, statements are removed from the store starting with the lowest
34//!   `global_priority` until a constraint is satisfied.
35//!
36//! When a new statement is inserted that would not satisfy constraints in the first place, no
37//! statements are deleted and `Ignored` result is returned.
38//! The order in which statements with the same priority are deleted is unspecified.
39//!
40//! Statement expiration.
41//!
42//! Each time a statement is removed from the store (Either evicted by higher priority statement or
43//! explicitly with the `remove` function) the statement is marked as expired. Expired statements
44//! can't be added to the store for `Options::purge_after_sec` seconds. This is to prevent old
45//! statements from being propagated on the network.
46
47#![warn(missing_docs)]
48#![warn(unused_extern_crates)]
49
50mod metrics;
51
52pub use sp_statement_store::{Error, StatementStore, MAX_TOPICS};
53
54use metrics::MetricsLink as PrometheusMetrics;
55use parking_lot::RwLock;
56use prometheus_endpoint::Registry as PrometheusRegistry;
57use sc_keystore::LocalKeystore;
58use sp_api::ProvideRuntimeApi;
59use sp_blockchain::HeaderBackend;
60use sp_core::{crypto::UncheckedFrom, hexdisplay::HexDisplay, traits::SpawnNamed, Decode, Encode};
61use sp_runtime::traits::Block as BlockT;
62use sp_statement_store::{
63	runtime_api::{
64		InvalidStatement, StatementSource, StatementStoreExt, ValidStatement, ValidateStatement,
65	},
66	AccountId, BlockHash, Channel, DecryptionKey, Hash, NetworkPriority, Proof, Result, Statement,
67	SubmitResult, Topic,
68};
69use std::{
70	collections::{BTreeMap, HashMap, HashSet},
71	sync::Arc,
72};
73
74const KEY_VERSION: &[u8] = b"version".as_slice();
75const CURRENT_VERSION: u32 = 1;
76
77const LOG_TARGET: &str = "statement-store";
78
79/// The amount of time an expired statement is kept before it is removed from the store entirely.
80pub const DEFAULT_PURGE_AFTER_SEC: u64 = 2 * 24 * 60 * 60; //48h
81/// The maximum number of statements the statement store can hold.
82pub const DEFAULT_MAX_TOTAL_STATEMENTS: usize = 4 * 1024 * 1024; // ~4 million
83/// The maximum amount of data the statement store can hold, regardless of the number of
84/// statements from which the data originates.
85pub const DEFAULT_MAX_TOTAL_SIZE: usize = 2 * 1024 * 1024 * 1024; // 2GiB
86/// The maximum size of a single statement in bytes.
87/// Accounts for the 1-byte vector length prefix when statements are gossiped as `Vec<Statement>`.
88pub const MAX_STATEMENT_SIZE: usize =
89	sc_network_statement::config::MAX_STATEMENT_NOTIFICATION_SIZE as usize - 1;
90
91const MAINTENANCE_PERIOD: std::time::Duration = std::time::Duration::from_secs(30);
92
93mod col {
94	pub const META: u8 = 0;
95	pub const STATEMENTS: u8 = 1;
96	pub const EXPIRED: u8 = 2;
97
98	pub const COUNT: u8 = 3;
99}
100
101#[derive(Eq, PartialEq, Debug, Ord, PartialOrd, Clone, Copy)]
102struct Priority(u32);
103
104#[derive(PartialEq, Eq)]
105struct PriorityKey {
106	hash: Hash,
107	priority: Priority,
108}
109
110impl PartialOrd for PriorityKey {
111	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
112		Some(self.cmp(other))
113	}
114}
115
116impl Ord for PriorityKey {
117	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
118		self.priority.cmp(&other.priority).then_with(|| self.hash.cmp(&other.hash))
119	}
120}
121
122#[derive(PartialEq, Eq)]
123struct ChannelEntry {
124	hash: Hash,
125	priority: Priority,
126}
127
128#[derive(Default)]
129struct StatementsForAccount {
130	// Statements ordered by priority.
131	by_priority: BTreeMap<PriorityKey, (Option<Channel>, usize)>,
132	// Channel to statement map. Only one statement per channel is allowed.
133	channels: HashMap<Channel, ChannelEntry>,
134	// Sum of all `Data` field sizes.
135	data_size: usize,
136}
137
138/// Store configuration
139pub struct Options {
140	/// Maximum statement allowed in the store. Once this limit is reached lower-priority
141	/// statements may be evicted.
142	max_total_statements: usize,
143	/// Maximum total data size allowed in the store. Once this limit is reached lower-priority
144	/// statements may be evicted.
145	max_total_size: usize,
146	/// Number of seconds for which removed statements won't be allowed to be added back in.
147	purge_after_sec: u64,
148}
149
150impl Default for Options {
151	fn default() -> Self {
152		Options {
153			max_total_statements: DEFAULT_MAX_TOTAL_STATEMENTS,
154			max_total_size: DEFAULT_MAX_TOTAL_SIZE,
155			purge_after_sec: DEFAULT_PURGE_AFTER_SEC,
156		}
157	}
158}
159
160#[derive(Default)]
161struct Index {
162	recent: HashSet<Hash>,
163	by_topic: HashMap<Topic, HashSet<Hash>>,
164	by_dec_key: HashMap<Option<DecryptionKey>, HashSet<Hash>>,
165	topics_and_keys: HashMap<Hash, ([Option<Topic>; MAX_TOPICS], Option<DecryptionKey>)>,
166	entries: HashMap<Hash, (AccountId, Priority, usize)>,
167	expired: HashMap<Hash, u64>, // Value is expiration timestamp.
168	accounts: HashMap<AccountId, StatementsForAccount>,
169	options: Options,
170	total_size: usize,
171}
172
173struct ClientWrapper<Block, Client> {
174	client: Arc<Client>,
175	_block: std::marker::PhantomData<Block>,
176}
177
178impl<Block, Client> ClientWrapper<Block, Client>
179where
180	Block: BlockT,
181	Block::Hash: From<BlockHash>,
182	Client: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
183	Client::Api: ValidateStatement<Block>,
184{
185	fn validate_statement(
186		&self,
187		block: Option<BlockHash>,
188		source: StatementSource,
189		statement: Statement,
190	) -> std::result::Result<ValidStatement, InvalidStatement> {
191		let api = self.client.runtime_api();
192		let block = block.map(Into::into).unwrap_or_else(|| {
193			// Validate against the finalized state.
194			self.client.info().finalized_hash
195		});
196		api.validate_statement(block, source, statement)
197			.map_err(|_| InvalidStatement::InternalError)?
198	}
199}
200
201/// Statement store.
202pub struct Store {
203	db: parity_db::Db,
204	index: RwLock<Index>,
205	validate_fn: Box<
206		dyn Fn(
207				Option<BlockHash>,
208				StatementSource,
209				Statement,
210			) -> std::result::Result<ValidStatement, InvalidStatement>
211			+ Send
212			+ Sync,
213	>,
214	keystore: Arc<LocalKeystore>,
215	// Used for testing
216	time_override: Option<u64>,
217	metrics: PrometheusMetrics,
218}
219
220enum IndexQuery {
221	Unknown,
222	Exists,
223	Expired,
224}
225
226enum MaybeInserted {
227	Inserted(HashSet<Hash>),
228	Ignored,
229}
230
231impl Index {
232	fn new(options: Options) -> Index {
233		Index { options, ..Default::default() }
234	}
235
236	fn insert_new(&mut self, hash: Hash, account: AccountId, statement: &Statement) {
237		let mut all_topics = [None; MAX_TOPICS];
238		let mut nt = 0;
239		while let Some(t) = statement.topic(nt) {
240			self.by_topic.entry(t).or_default().insert(hash);
241			all_topics[nt] = Some(t);
242			nt += 1;
243		}
244		let key = statement.decryption_key();
245		self.by_dec_key.entry(key).or_default().insert(hash);
246		if nt > 0 || key.is_some() {
247			self.topics_and_keys.insert(hash, (all_topics, key));
248		}
249		let priority = Priority(statement.priority().unwrap_or(0));
250		self.entries.insert(hash, (account, priority, statement.data_len()));
251		self.recent.insert(hash);
252		self.total_size += statement.data_len();
253		let account_info = self.accounts.entry(account).or_default();
254		account_info.data_size += statement.data_len();
255		if let Some(channel) = statement.channel() {
256			account_info.channels.insert(channel, ChannelEntry { hash, priority });
257		}
258		account_info
259			.by_priority
260			.insert(PriorityKey { hash, priority }, (statement.channel(), statement.data_len()));
261	}
262
263	fn query(&self, hash: &Hash) -> IndexQuery {
264		if self.entries.contains_key(hash) {
265			return IndexQuery::Exists
266		}
267		if self.expired.contains_key(hash) {
268			return IndexQuery::Expired
269		}
270		IndexQuery::Unknown
271	}
272
273	fn insert_expired(&mut self, hash: Hash, timestamp: u64) {
274		self.expired.insert(hash, timestamp);
275	}
276
277	fn iterate_with(
278		&self,
279		key: Option<DecryptionKey>,
280		match_all_topics: &[Topic],
281		mut f: impl FnMut(&Hash) -> Result<()>,
282	) -> Result<()> {
283		let empty = HashSet::new();
284		let mut sets: [&HashSet<Hash>; MAX_TOPICS + 1] = [&empty; MAX_TOPICS + 1];
285		if match_all_topics.len() > MAX_TOPICS {
286			return Ok(())
287		}
288		let key_set = self.by_dec_key.get(&key);
289		if key_set.map_or(0, |s| s.len()) == 0 {
290			// Key does not exist in the index.
291			return Ok(())
292		}
293		sets[0] = key_set.expect("Function returns if key_set is None");
294		for (i, t) in match_all_topics.iter().enumerate() {
295			let set = self.by_topic.get(t);
296			if set.map_or(0, |s| s.len()) == 0 {
297				// At least one of the match_all_topics does not exist in the index.
298				return Ok(())
299			}
300			sets[i + 1] = set.expect("Function returns if set is None");
301		}
302		let sets = &mut sets[0..match_all_topics.len() + 1];
303		// Start with the smallest topic set or the key set.
304		sets.sort_by_key(|s| s.len());
305		for item in sets[0] {
306			if sets[1..].iter().all(|set| set.contains(item)) {
307				log::trace!(
308					target: LOG_TARGET,
309					"Iterating by topic/key: statement {:?}",
310					HexDisplay::from(item)
311				);
312				f(item)?
313			}
314		}
315		Ok(())
316	}
317
318	fn maintain(&mut self, current_time: u64) -> Vec<Hash> {
319		// Purge previously expired messages.
320		let mut purged = Vec::new();
321		self.expired.retain(|hash, timestamp| {
322			if *timestamp + self.options.purge_after_sec <= current_time {
323				purged.push(*hash);
324				log::trace!(target: LOG_TARGET, "Purged statement {:?}", HexDisplay::from(hash));
325				false
326			} else {
327				true
328			}
329		});
330		purged
331	}
332
333	fn take_recent(&mut self) -> HashSet<Hash> {
334		std::mem::take(&mut self.recent)
335	}
336
337	fn make_expired(&mut self, hash: &Hash, current_time: u64) -> bool {
338		if let Some((account, priority, len)) = self.entries.remove(hash) {
339			self.total_size -= len;
340			if let Some((topics, key)) = self.topics_and_keys.remove(hash) {
341				for t in topics.into_iter().flatten() {
342					if let std::collections::hash_map::Entry::Occupied(mut set) =
343						self.by_topic.entry(t)
344					{
345						set.get_mut().remove(hash);
346						if set.get().is_empty() {
347							set.remove_entry();
348						}
349					}
350				}
351				if let std::collections::hash_map::Entry::Occupied(mut set) =
352					self.by_dec_key.entry(key)
353				{
354					set.get_mut().remove(hash);
355					if set.get().is_empty() {
356						set.remove_entry();
357					}
358				}
359			}
360			let _ = self.recent.remove(hash);
361			self.expired.insert(*hash, current_time);
362			if let std::collections::hash_map::Entry::Occupied(mut account_rec) =
363				self.accounts.entry(account)
364			{
365				let key = PriorityKey { hash: *hash, priority };
366				if let Some((channel, len)) = account_rec.get_mut().by_priority.remove(&key) {
367					account_rec.get_mut().data_size -= len;
368					if let Some(channel) = channel {
369						account_rec.get_mut().channels.remove(&channel);
370					}
371				}
372				if account_rec.get().by_priority.is_empty() {
373					account_rec.remove_entry();
374				}
375			}
376			log::trace!(target: LOG_TARGET, "Expired statement {:?}", HexDisplay::from(hash));
377			true
378		} else {
379			false
380		}
381	}
382
383	fn insert(
384		&mut self,
385		hash: Hash,
386		statement: &Statement,
387		account: &AccountId,
388		validation: &ValidStatement,
389		current_time: u64,
390	) -> MaybeInserted {
391		let statement_len = statement.data_len();
392		if statement_len > validation.max_size as usize {
393			log::debug!(
394				target: LOG_TARGET,
395				"Ignored oversize message: {:?} ({} bytes)",
396				HexDisplay::from(&hash),
397				statement_len,
398			);
399			return MaybeInserted::Ignored
400		}
401
402		let mut evicted = HashSet::new();
403		let mut would_free_size = 0;
404		let priority = Priority(statement.priority().unwrap_or(0));
405		let (max_size, max_count) = (validation.max_size as usize, validation.max_count as usize);
406		// It may happen that we can't delete enough lower priority messages
407		// to satisfy size constraints. We check for that before deleting anything,
408		// taking into account channel message replacement.
409		if let Some(account_rec) = self.accounts.get(account) {
410			if let Some(channel) = statement.channel() {
411				if let Some(channel_record) = account_rec.channels.get(&channel) {
412					if priority <= channel_record.priority {
413						// Trying to replace channel message with lower priority
414						log::debug!(
415							target: LOG_TARGET,
416							"Ignored lower priority channel message: {:?} {:?} <= {:?}",
417							HexDisplay::from(&hash),
418							priority,
419							channel_record.priority,
420						);
421						return MaybeInserted::Ignored
422					} else {
423						// Would replace channel message. Still need to check for size constraints
424						// below.
425						log::debug!(
426							target: LOG_TARGET,
427							"Replacing higher priority channel message: {:?} ({:?}) > {:?} ({:?})",
428							HexDisplay::from(&hash),
429							priority,
430							HexDisplay::from(&channel_record.hash),
431							channel_record.priority,
432						);
433						let key = PriorityKey {
434							hash: channel_record.hash,
435							priority: channel_record.priority,
436						};
437						if let Some((_channel, len)) = account_rec.by_priority.get(&key) {
438							would_free_size += *len;
439							evicted.insert(channel_record.hash);
440						}
441					}
442				}
443			}
444			// Check if we can evict enough lower priority statements to satisfy constraints
445			for (entry, (_, len)) in account_rec.by_priority.iter() {
446				if (account_rec.data_size - would_free_size + statement_len <= max_size) &&
447					account_rec.by_priority.len() + 1 - evicted.len() <= max_count
448				{
449					// Satisfied
450					break
451				}
452				if evicted.contains(&entry.hash) {
453					// Already accounted for above
454					continue
455				}
456				if entry.priority >= priority {
457					log::debug!(
458						target: LOG_TARGET,
459						"Ignored message due to constraints {:?} {:?} < {:?}",
460						HexDisplay::from(&hash),
461						priority,
462						entry.priority,
463					);
464					return MaybeInserted::Ignored
465				}
466				evicted.insert(entry.hash);
467				would_free_size += len;
468			}
469		}
470		// Now check global constraints as well.
471		if !((self.total_size - would_free_size + statement_len <= self.options.max_total_size) &&
472			self.entries.len() + 1 - evicted.len() <= self.options.max_total_statements)
473		{
474			log::debug!(
475				target: LOG_TARGET,
476				"Ignored statement {} because the store is full (size={}, count={})",
477				HexDisplay::from(&hash),
478				self.total_size,
479				self.entries.len(),
480			);
481			return MaybeInserted::Ignored
482		}
483
484		for h in &evicted {
485			self.make_expired(h, current_time);
486		}
487		self.insert_new(hash, *account, statement);
488		MaybeInserted::Inserted(evicted)
489	}
490}
491
492impl Store {
493	/// Create a new shared store instance. There should only be one per process.
494	/// `path` will be used to open a statement database or create a new one if it does not exist.
495	pub fn new_shared<Block, Client>(
496		path: &std::path::Path,
497		options: Options,
498		client: Arc<Client>,
499		keystore: Arc<LocalKeystore>,
500		prometheus: Option<&PrometheusRegistry>,
501		task_spawner: &dyn SpawnNamed,
502	) -> Result<Arc<Store>>
503	where
504		Block: BlockT,
505		Block::Hash: From<BlockHash>,
506		Client: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
507		Client::Api: ValidateStatement<Block>,
508	{
509		let store = Arc::new(Self::new(path, options, client, keystore, prometheus)?);
510
511		// Perform periodic statement store maintenance
512		let worker_store = store.clone();
513		task_spawner.spawn(
514			"statement-store-maintenance",
515			Some("statement-store"),
516			Box::pin(async move {
517				let mut interval = tokio::time::interval(MAINTENANCE_PERIOD);
518				loop {
519					interval.tick().await;
520					worker_store.maintain();
521				}
522			}),
523		);
524
525		Ok(store)
526	}
527
528	/// Create a new instance.
529	/// `path` will be used to open a statement database or create a new one if it does not exist.
530	fn new<Block, Client>(
531		path: &std::path::Path,
532		options: Options,
533		client: Arc<Client>,
534		keystore: Arc<LocalKeystore>,
535		prometheus: Option<&PrometheusRegistry>,
536	) -> Result<Store>
537	where
538		Block: BlockT,
539		Block::Hash: From<BlockHash>,
540		Client: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
541		Client::Api: ValidateStatement<Block>,
542	{
543		let mut path: std::path::PathBuf = path.into();
544		path.push("statements");
545
546		let mut config = parity_db::Options::with_columns(&path, col::COUNT);
547
548		let statement_col = &mut config.columns[col::STATEMENTS as usize];
549		statement_col.ref_counted = false;
550		statement_col.preimage = true;
551		statement_col.uniform = true;
552		let db = parity_db::Db::open_or_create(&config).map_err(|e| Error::Db(e.to_string()))?;
553		match db.get(col::META, &KEY_VERSION).map_err(|e| Error::Db(e.to_string()))? {
554			Some(version) => {
555				let version = u32::from_le_bytes(
556					version
557						.try_into()
558						.map_err(|_| Error::Db("Error reading database version".into()))?,
559				);
560				if version != CURRENT_VERSION {
561					return Err(Error::Db(format!("Unsupported database version: {version}")))
562				}
563			},
564			None => {
565				db.commit([(
566					col::META,
567					KEY_VERSION.to_vec(),
568					Some(CURRENT_VERSION.to_le_bytes().to_vec()),
569				)])
570				.map_err(|e| Error::Db(e.to_string()))?;
571			},
572		}
573
574		let validator = ClientWrapper { client, _block: Default::default() };
575		let validate_fn = Box::new(move |block, source, statement| {
576			validator.validate_statement(block, source, statement)
577		});
578
579		let store = Store {
580			db,
581			index: RwLock::new(Index::new(options)),
582			validate_fn,
583			keystore,
584			time_override: None,
585			metrics: PrometheusMetrics::new(prometheus),
586		};
587		store.populate()?;
588		Ok(store)
589	}
590
591	/// Create memory index from the data.
592	// This may be moved to a background thread if it slows startup too much.
593	// This function should only be used on startup. There should be no other DB operations when
594	// iterating the index.
595	fn populate(&self) -> Result<()> {
596		{
597			let mut index = self.index.write();
598			self.db
599				.iter_column_while(col::STATEMENTS, |item| {
600					let statement = item.value;
601					if let Ok(statement) = Statement::decode(&mut statement.as_slice()) {
602						let hash = statement.hash();
603						log::trace!(
604							target: LOG_TARGET,
605							"Statement loaded {:?}",
606							HexDisplay::from(&hash)
607						);
608						if let Some(account_id) = statement.account_id() {
609							index.insert_new(hash, account_id, &statement);
610						} else {
611							log::debug!(
612								target: LOG_TARGET,
613								"Error decoding statement loaded from the DB: {:?}",
614								HexDisplay::from(&hash)
615							);
616						}
617					}
618					true
619				})
620				.map_err(|e| Error::Db(e.to_string()))?;
621			self.db
622				.iter_column_while(col::EXPIRED, |item| {
623					let expired_info = item.value;
624					if let Ok((hash, timestamp)) =
625						<(Hash, u64)>::decode(&mut expired_info.as_slice())
626					{
627						log::trace!(
628							target: LOG_TARGET,
629							"Statement loaded (expired): {:?}",
630							HexDisplay::from(&hash)
631						);
632						index.insert_expired(hash, timestamp);
633					}
634					true
635				})
636				.map_err(|e| Error::Db(e.to_string()))?;
637		}
638
639		self.maintain();
640		Ok(())
641	}
642
643	fn collect_statements<R>(
644		&self,
645		key: Option<DecryptionKey>,
646		match_all_topics: &[Topic],
647		mut f: impl FnMut(Statement) -> Option<R>,
648	) -> Result<Vec<R>> {
649		let mut result = Vec::new();
650		let index = self.index.read();
651		index.iterate_with(key, match_all_topics, |hash| {
652			match self.db.get(col::STATEMENTS, hash).map_err(|e| Error::Db(e.to_string()))? {
653				Some(entry) => {
654					if let Ok(statement) = Statement::decode(&mut entry.as_slice()) {
655						if let Some(data) = f(statement) {
656							result.push(data);
657						}
658					} else {
659						// DB inconsistency
660						log::warn!(
661							target: LOG_TARGET,
662							"Corrupt statement {:?}",
663							HexDisplay::from(hash)
664						);
665					}
666				},
667				None => {
668					// DB inconsistency
669					log::warn!(
670						target: LOG_TARGET,
671						"Missing statement {:?}",
672						HexDisplay::from(hash)
673					);
674				},
675			}
676			Ok(())
677		})?;
678		Ok(result)
679	}
680
681	/// Perform periodic store maintenance
682	pub fn maintain(&self) {
683		log::trace!(target: LOG_TARGET, "Started store maintenance");
684		let (deleted, active_count, expired_count): (Vec<_>, usize, usize) = {
685			let mut index = self.index.write();
686			let deleted = index.maintain(self.timestamp());
687			(deleted, index.entries.len(), index.expired.len())
688		};
689		let deleted: Vec<_> =
690			deleted.into_iter().map(|hash| (col::EXPIRED, hash.to_vec(), None)).collect();
691		let deleted_count = deleted.len() as u64;
692		if let Err(e) = self.db.commit(deleted) {
693			log::warn!(target: LOG_TARGET, "Error writing to the statement database: {:?}", e);
694		} else {
695			self.metrics.report(|metrics| metrics.statements_pruned.inc_by(deleted_count));
696		}
697		log::trace!(
698			target: LOG_TARGET,
699			"Completed store maintenance. Purged: {}, Active: {}, Expired: {}",
700			deleted_count,
701			active_count,
702			expired_count
703		);
704	}
705
706	fn timestamp(&self) -> u64 {
707		self.time_override.unwrap_or_else(|| {
708			std::time::SystemTime::now()
709				.duration_since(std::time::UNIX_EPOCH)
710				.unwrap_or_default()
711				.as_secs()
712		})
713	}
714
715	#[cfg(test)]
716	fn set_time(&mut self, time: u64) {
717		self.time_override = Some(time);
718	}
719
720	/// Returns `self` as [`StatementStoreExt`].
721	pub fn as_statement_store_ext(self: Arc<Self>) -> StatementStoreExt {
722		StatementStoreExt::new(self)
723	}
724
725	/// Return information of all known statements whose decryption key is identified as
726	/// `dest`. The key must be available to the client.
727	fn posted_clear_inner<R>(
728		&self,
729		match_all_topics: &[Topic],
730		dest: [u8; 32],
731		// Map the statement and the decrypted data to the desired result.
732		mut map_f: impl FnMut(Statement, Vec<u8>) -> R,
733	) -> Result<Vec<R>> {
734		self.collect_statements(Some(dest), match_all_topics, |statement| {
735			if let (Some(key), Some(_)) = (statement.decryption_key(), statement.data()) {
736				let public: sp_core::ed25519::Public = UncheckedFrom::unchecked_from(key);
737				let public: sp_statement_store::ed25519::Public = public.into();
738				match self.keystore.key_pair::<sp_statement_store::ed25519::Pair>(&public) {
739					Err(e) => {
740						log::debug!(
741							target: LOG_TARGET,
742							"Keystore error: {:?}, for statement {:?}",
743							e,
744							HexDisplay::from(&statement.hash())
745						);
746						None
747					},
748					Ok(None) => {
749						log::debug!(
750							target: LOG_TARGET,
751							"Keystore is missing key for statement {:?}",
752							HexDisplay::from(&statement.hash())
753						);
754						None
755					},
756					Ok(Some(pair)) => match statement.decrypt_private(&pair.into_inner()) {
757						Ok(r) => r.map(|data| map_f(statement, data)),
758						Err(e) => {
759							log::debug!(
760								target: LOG_TARGET,
761								"Decryption error: {:?}, for statement {:?}",
762								e,
763								HexDisplay::from(&statement.hash())
764							);
765							None
766						},
767					},
768				}
769			} else {
770				None
771			}
772		})
773	}
774}
775
776impl StatementStore for Store {
777	/// Return all statements.
778	fn statements(&self) -> Result<Vec<(Hash, Statement)>> {
779		let index = self.index.read();
780		let mut result = Vec::with_capacity(index.entries.len());
781		for hash in index.entries.keys().cloned() {
782			let Some(encoded) =
783				self.db.get(col::STATEMENTS, &hash).map_err(|e| Error::Db(e.to_string()))?
784			else {
785				continue
786			};
787			if let Ok(statement) = Statement::decode(&mut encoded.as_slice()) {
788				result.push((hash, statement));
789			}
790		}
791		Ok(result)
792	}
793
794	fn take_recent_statements(&self) -> Result<Vec<(Hash, Statement)>> {
795		let mut index = self.index.write();
796		let recent = index.take_recent();
797		let mut result = Vec::with_capacity(recent.len());
798		for hash in recent {
799			let Some(encoded) =
800				self.db.get(col::STATEMENTS, &hash).map_err(|e| Error::Db(e.to_string()))?
801			else {
802				continue
803			};
804			if let Ok(statement) = Statement::decode(&mut encoded.as_slice()) {
805				result.push((hash, statement));
806			}
807		}
808		Ok(result)
809	}
810
811	/// Returns a statement by hash.
812	fn statement(&self, hash: &Hash) -> Result<Option<Statement>> {
813		Ok(
814			match self
815				.db
816				.get(col::STATEMENTS, hash.as_slice())
817				.map_err(|e| Error::Db(e.to_string()))?
818			{
819				Some(entry) => {
820					log::trace!(
821						target: LOG_TARGET,
822						"Queried statement {:?}",
823						HexDisplay::from(hash)
824					);
825					Some(
826						Statement::decode(&mut entry.as_slice())
827							.map_err(|e| Error::Decode(e.to_string()))?,
828					)
829				},
830				None => {
831					log::trace!(
832						target: LOG_TARGET,
833						"Queried missing statement {:?}",
834						HexDisplay::from(hash)
835					);
836					None
837				},
838			},
839		)
840	}
841
842	fn has_statement(&self, hash: &Hash) -> bool {
843		self.index.read().entries.contains_key(hash)
844	}
845
846	/// Return the data of all known statements which include all topics and have no `DecryptionKey`
847	/// field.
848	fn broadcasts(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>> {
849		self.collect_statements(None, match_all_topics, |statement| statement.into_data())
850	}
851
852	/// Return the data of all known statements whose decryption key is identified as `dest` (this
853	/// will generally be the public key or a hash thereof for symmetric ciphers, or a hash of the
854	/// private key for symmetric ciphers).
855	fn posted(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
856		self.collect_statements(Some(dest), match_all_topics, |statement| statement.into_data())
857	}
858
859	/// Return the decrypted data of all known statements whose decryption key is identified as
860	/// `dest`. The key must be available to the client.
861	fn posted_clear(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
862		self.posted_clear_inner(match_all_topics, dest, |_statement, data| data)
863	}
864
865	/// Return all known statements which include all topics and have no `DecryptionKey`
866	/// field.
867	fn broadcasts_stmt(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>> {
868		self.collect_statements(None, match_all_topics, |statement| Some(statement.encode()))
869	}
870
871	/// Return all known statements whose decryption key is identified as `dest` (this
872	/// will generally be the public key or a hash thereof for symmetric ciphers, or a hash of the
873	/// private key for symmetric ciphers).
874	fn posted_stmt(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
875		self.collect_statements(Some(dest), match_all_topics, |statement| Some(statement.encode()))
876	}
877
878	/// Return the statement and the decrypted data of all known statements whose decryption key is
879	/// identified as `dest`. The key must be available to the client.
880	fn posted_clear_stmt(
881		&self,
882		match_all_topics: &[Topic],
883		dest: [u8; 32],
884	) -> Result<Vec<Vec<u8>>> {
885		self.posted_clear_inner(match_all_topics, dest, |statement, data| {
886			let mut res = Vec::with_capacity(statement.size_hint() + data.len());
887			statement.encode_to(&mut res);
888			res.extend_from_slice(&data);
889			res
890		})
891	}
892
893	/// Submit a statement to the store. Validates the statement and returns validation result.
894	fn submit(&self, statement: Statement, source: StatementSource) -> SubmitResult {
895		let hash = statement.hash();
896		let encoded_size = statement.encoded_size();
897		if encoded_size > MAX_STATEMENT_SIZE {
898			log::debug!(
899				target: LOG_TARGET,
900				"Statement is too big for propogation: {:?} ({}/{} bytes)",
901				HexDisplay::from(&hash),
902				statement.encoded_size(),
903				MAX_STATEMENT_SIZE
904			);
905			return SubmitResult::Ignored
906		}
907
908		match self.index.read().query(&hash) {
909			IndexQuery::Expired =>
910				if !source.can_be_resubmitted() {
911					return SubmitResult::KnownExpired
912				},
913			IndexQuery::Exists =>
914				if !source.can_be_resubmitted() {
915					return SubmitResult::Known
916				},
917			IndexQuery::Unknown => {},
918		}
919
920		let Some(account_id) = statement.account_id() else {
921			log::debug!(
922				target: LOG_TARGET,
923				"Statement validation failed: Missing proof ({:?})",
924				HexDisplay::from(&hash),
925			);
926			self.metrics.report(|metrics| metrics.validations_invalid.inc());
927			return SubmitResult::Bad("No statement proof")
928		};
929
930		// Validate.
931		let at_block = if let Some(Proof::OnChain { block_hash, .. }) = statement.proof() {
932			Some(*block_hash)
933		} else {
934			None
935		};
936		let validation_result = (self.validate_fn)(at_block, source, statement.clone());
937		let validation = match validation_result {
938			Ok(validation) => validation,
939			Err(InvalidStatement::BadProof) => {
940				log::debug!(
941					target: LOG_TARGET,
942					"Statement validation failed: BadProof, {:?}",
943					HexDisplay::from(&hash),
944				);
945				self.metrics.report(|metrics| metrics.validations_invalid.inc());
946				return SubmitResult::Bad("Bad statement proof")
947			},
948			Err(InvalidStatement::NoProof) => {
949				log::debug!(
950					target: LOG_TARGET,
951					"Statement validation failed: NoProof, {:?}",
952					HexDisplay::from(&hash),
953				);
954				self.metrics.report(|metrics| metrics.validations_invalid.inc());
955				return SubmitResult::Bad("Missing statement proof")
956			},
957			Err(InvalidStatement::InternalError) =>
958				return SubmitResult::InternalError(Error::Runtime),
959		};
960
961		let current_time = self.timestamp();
962		let mut commit = Vec::new();
963		{
964			let mut index = self.index.write();
965
966			let evicted =
967				match index.insert(hash, &statement, &account_id, &validation, current_time) {
968					MaybeInserted::Ignored => return SubmitResult::Ignored,
969					MaybeInserted::Inserted(evicted) => evicted,
970				};
971
972			commit.push((col::STATEMENTS, hash.to_vec(), Some(statement.encode())));
973			for hash in evicted {
974				commit.push((col::STATEMENTS, hash.to_vec(), None));
975				commit.push((col::EXPIRED, hash.to_vec(), Some((hash, current_time).encode())));
976			}
977			if let Err(e) = self.db.commit(commit) {
978				log::debug!(
979					target: LOG_TARGET,
980					"Statement validation failed: database error {}, {:?}",
981					e,
982					statement
983				);
984				return SubmitResult::InternalError(Error::Db(e.to_string()))
985			}
986		} // Release index lock
987		self.metrics.report(|metrics| metrics.submitted_statements.inc());
988		let network_priority = NetworkPriority::High;
989		log::trace!(target: LOG_TARGET, "Statement submitted: {:?}", HexDisplay::from(&hash));
990		SubmitResult::New(network_priority)
991	}
992
993	/// Remove a statement by hash.
994	fn remove(&self, hash: &Hash) -> Result<()> {
995		let current_time = self.timestamp();
996		{
997			let mut index = self.index.write();
998			if index.make_expired(hash, current_time) {
999				let commit = [
1000					(col::STATEMENTS, hash.to_vec(), None),
1001					(col::EXPIRED, hash.to_vec(), Some((hash, current_time).encode())),
1002				];
1003				if let Err(e) = self.db.commit(commit) {
1004					log::debug!(
1005						target: LOG_TARGET,
1006						"Error removing statement: database error {}, {:?}",
1007						e,
1008						HexDisplay::from(hash),
1009					);
1010					return Err(Error::Db(e.to_string()))
1011				}
1012			}
1013		}
1014		Ok(())
1015	}
1016
1017	/// Remove all statements by an account.
1018	fn remove_by(&self, who: [u8; 32]) -> Result<()> {
1019		let mut index = self.index.write();
1020		let mut evicted = Vec::new();
1021		if let Some(account_rec) = index.accounts.get(&who) {
1022			evicted.extend(account_rec.by_priority.keys().map(|k| k.hash));
1023		}
1024
1025		let current_time = self.timestamp();
1026		let mut commit = Vec::new();
1027		for hash in evicted {
1028			index.make_expired(&hash, current_time);
1029			commit.push((col::STATEMENTS, hash.to_vec(), None));
1030			commit.push((col::EXPIRED, hash.to_vec(), Some((hash, current_time).encode())));
1031		}
1032		self.db.commit(commit).map_err(|e| {
1033			log::debug!(
1034				target: LOG_TARGET,
1035				"Error removing statement: database error {}, remove by {:?}",
1036				e,
1037				HexDisplay::from(&who),
1038			);
1039
1040			Error::Db(e.to_string())
1041		})
1042	}
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047	use crate::Store;
1048	use sc_keystore::Keystore;
1049	use sp_core::{Decode, Encode, Pair};
1050	use sp_statement_store::{
1051		runtime_api::{InvalidStatement, ValidStatement, ValidateStatement},
1052		AccountId, Channel, DecryptionKey, NetworkPriority, Proof, SignatureVerificationResult,
1053		Statement, StatementSource, StatementStore, SubmitResult, Topic,
1054	};
1055
1056	type Extrinsic = sp_runtime::OpaqueExtrinsic;
1057	type Hash = sp_core::H256;
1058	type Hashing = sp_runtime::traits::BlakeTwo256;
1059	type BlockNumber = u64;
1060	type Header = sp_runtime::generic::Header<BlockNumber, Hashing>;
1061	type Block = sp_runtime::generic::Block<Header, Extrinsic>;
1062
1063	const CORRECT_BLOCK_HASH: [u8; 32] = [1u8; 32];
1064
1065	#[derive(Clone)]
1066	pub(crate) struct TestClient;
1067
1068	pub(crate) struct RuntimeApi {
1069		_inner: TestClient,
1070	}
1071
1072	impl sp_api::ProvideRuntimeApi<Block> for TestClient {
1073		type Api = RuntimeApi;
1074		fn runtime_api(&self) -> sp_api::ApiRef<Self::Api> {
1075			RuntimeApi { _inner: self.clone() }.into()
1076		}
1077	}
1078
1079	sp_api::mock_impl_runtime_apis! {
1080		impl ValidateStatement<Block> for RuntimeApi {
1081			fn validate_statement(
1082				_source: StatementSource,
1083				statement: Statement,
1084			) -> std::result::Result<ValidStatement, InvalidStatement> {
1085				use crate::tests::account;
1086				match statement.verify_signature() {
1087					SignatureVerificationResult::Valid(_) => Ok(ValidStatement{max_count: 100, max_size: 1000}),
1088					SignatureVerificationResult::Invalid => Err(InvalidStatement::BadProof),
1089					SignatureVerificationResult::NoSignature => {
1090						if let Some(Proof::OnChain { block_hash, .. }) = statement.proof() {
1091							if block_hash == &CORRECT_BLOCK_HASH {
1092								let (max_count, max_size) = match statement.account_id() {
1093									Some(a) if a == account(1) => (1, 1000),
1094									Some(a) if a == account(2) => (2, 1000),
1095									Some(a) if a == account(3) => (3, 1000),
1096									Some(a) if a == account(4) => (4, 1000),
1097									Some(a) if a == account(42) => (42, 42 * crate::MAX_STATEMENT_SIZE as u32),
1098									_ => (2, 2000),
1099								};
1100								Ok(ValidStatement{ max_count, max_size })
1101							} else {
1102								Err(InvalidStatement::BadProof)
1103							}
1104						} else {
1105							Err(InvalidStatement::BadProof)
1106						}
1107					}
1108				}
1109			}
1110		}
1111	}
1112
1113	impl sp_blockchain::HeaderBackend<Block> for TestClient {
1114		fn header(&self, _hash: Hash) -> sp_blockchain::Result<Option<Header>> {
1115			unimplemented!()
1116		}
1117		fn info(&self) -> sp_blockchain::Info<Block> {
1118			sp_blockchain::Info {
1119				best_hash: CORRECT_BLOCK_HASH.into(),
1120				best_number: 0,
1121				genesis_hash: Default::default(),
1122				finalized_hash: CORRECT_BLOCK_HASH.into(),
1123				finalized_number: 1,
1124				finalized_state: None,
1125				number_leaves: 0,
1126				block_gap: None,
1127			}
1128		}
1129		fn status(&self, _hash: Hash) -> sp_blockchain::Result<sp_blockchain::BlockStatus> {
1130			unimplemented!()
1131		}
1132		fn number(&self, _hash: Hash) -> sp_blockchain::Result<Option<BlockNumber>> {
1133			unimplemented!()
1134		}
1135		fn hash(&self, _number: BlockNumber) -> sp_blockchain::Result<Option<Hash>> {
1136			unimplemented!()
1137		}
1138	}
1139
1140	fn test_store() -> (Store, tempfile::TempDir) {
1141		sp_tracing::init_for_tests();
1142		let temp_dir = tempfile::Builder::new().tempdir().expect("Error creating test dir");
1143
1144		let client = std::sync::Arc::new(TestClient);
1145		let mut path: std::path::PathBuf = temp_dir.path().into();
1146		path.push("db");
1147		let keystore = std::sync::Arc::new(sc_keystore::LocalKeystore::in_memory());
1148		let store = Store::new(&path, Default::default(), client, keystore, None).unwrap();
1149		(store, temp_dir) // return order is important. Store must be dropped before TempDir
1150	}
1151
1152	fn signed_statement(data: u8) -> Statement {
1153		signed_statement_with_topics(data, &[], None)
1154	}
1155
1156	fn signed_statement_with_topics(
1157		data: u8,
1158		topics: &[Topic],
1159		dec_key: Option<DecryptionKey>,
1160	) -> Statement {
1161		let mut statement = Statement::new();
1162		statement.set_plain_data(vec![data]);
1163		for i in 0..topics.len() {
1164			statement.set_topic(i, topics[i]);
1165		}
1166		if let Some(key) = dec_key {
1167			statement.set_decryption_key(key);
1168		}
1169		let kp = sp_core::ed25519::Pair::from_string("//Alice", None).unwrap();
1170		statement.sign_ed25519_private(&kp);
1171		statement
1172	}
1173
1174	fn topic(data: u64) -> Topic {
1175		let mut topic: Topic = Default::default();
1176		topic[0..8].copy_from_slice(&data.to_le_bytes());
1177		topic
1178	}
1179
1180	fn dec_key(data: u64) -> DecryptionKey {
1181		let mut dec_key: DecryptionKey = Default::default();
1182		dec_key[0..8].copy_from_slice(&data.to_le_bytes());
1183		dec_key
1184	}
1185
1186	fn account(id: u64) -> AccountId {
1187		let mut account: AccountId = Default::default();
1188		account[0..8].copy_from_slice(&id.to_le_bytes());
1189		account
1190	}
1191
1192	fn channel(id: u64) -> Channel {
1193		let mut channel: Channel = Default::default();
1194		channel[0..8].copy_from_slice(&id.to_le_bytes());
1195		channel
1196	}
1197
1198	fn statement(account_id: u64, priority: u32, c: Option<u64>, data_len: usize) -> Statement {
1199		let mut statement = Statement::new();
1200		let mut data = Vec::new();
1201		data.resize(data_len, 0);
1202		statement.set_plain_data(data);
1203		statement.set_priority(priority);
1204		if let Some(c) = c {
1205			statement.set_channel(channel(c));
1206		}
1207		statement.set_proof(Proof::OnChain {
1208			block_hash: CORRECT_BLOCK_HASH,
1209			who: account(account_id),
1210			event_index: 0,
1211		});
1212		statement
1213	}
1214
1215	#[test]
1216	fn submit_one() {
1217		let (store, _temp) = test_store();
1218		let statement0 = signed_statement(0);
1219		assert_eq!(
1220			store.submit(statement0, StatementSource::Network),
1221			SubmitResult::New(NetworkPriority::High)
1222		);
1223		let unsigned = statement(0, 1, None, 0);
1224		assert_eq!(
1225			store.submit(unsigned, StatementSource::Network),
1226			SubmitResult::New(NetworkPriority::High)
1227		);
1228	}
1229
1230	#[test]
1231	fn save_and_load_statements() {
1232		let (store, temp) = test_store();
1233		let statement0 = signed_statement(0);
1234		let statement1 = signed_statement(1);
1235		let statement2 = signed_statement(2);
1236		assert_eq!(
1237			store.submit(statement0.clone(), StatementSource::Network),
1238			SubmitResult::New(NetworkPriority::High)
1239		);
1240		assert_eq!(
1241			store.submit(statement1.clone(), StatementSource::Network),
1242			SubmitResult::New(NetworkPriority::High)
1243		);
1244		assert_eq!(
1245			store.submit(statement2.clone(), StatementSource::Network),
1246			SubmitResult::New(NetworkPriority::High)
1247		);
1248		assert_eq!(store.statements().unwrap().len(), 3);
1249		assert_eq!(store.broadcasts(&[]).unwrap().len(), 3);
1250		assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1.clone()));
1251		let keystore = store.keystore.clone();
1252		drop(store);
1253
1254		let client = std::sync::Arc::new(TestClient);
1255		let mut path: std::path::PathBuf = temp.path().into();
1256		path.push("db");
1257		let store = Store::new(&path, Default::default(), client, keystore, None).unwrap();
1258		assert_eq!(store.statements().unwrap().len(), 3);
1259		assert_eq!(store.broadcasts(&[]).unwrap().len(), 3);
1260		assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1));
1261	}
1262
1263	#[test]
1264	fn take_recent_statements_clears_index() {
1265		let (store, _temp) = test_store();
1266		let statement0 = signed_statement(0);
1267		let statement1 = signed_statement(1);
1268		let statement2 = signed_statement(2);
1269		let statement3 = signed_statement(3);
1270
1271		let _ = store.submit(statement0.clone(), StatementSource::Local);
1272		let _ = store.submit(statement1.clone(), StatementSource::Local);
1273		let _ = store.submit(statement2.clone(), StatementSource::Local);
1274
1275		let recent1 = store.take_recent_statements().unwrap();
1276		let (recent1_hashes, recent1_statements): (Vec<_>, Vec<_>) = recent1.into_iter().unzip();
1277		let expected1 = vec![statement0, statement1, statement2];
1278		assert!(expected1.iter().all(|s| recent1_hashes.contains(&s.hash())));
1279		assert!(expected1.iter().all(|s| recent1_statements.contains(s)));
1280
1281		// Recent statements are cleared.
1282		let recent2 = store.take_recent_statements().unwrap();
1283		assert_eq!(recent2.len(), 0);
1284
1285		store.submit(statement3.clone(), StatementSource::Network);
1286
1287		let recent3 = store.take_recent_statements().unwrap();
1288		let (recent3_hashes, recent3_statements): (Vec<_>, Vec<_>) = recent3.into_iter().unzip();
1289		let expected3 = vec![statement3];
1290		assert!(expected3.iter().all(|s| recent3_hashes.contains(&s.hash())));
1291		assert!(expected3.iter().all(|s| recent3_statements.contains(s)));
1292
1293		// Recent statements are cleared, but statements remain in the store.
1294		assert_eq!(store.statements().unwrap().len(), 4);
1295	}
1296
1297	#[test]
1298	fn search_by_topic_and_key() {
1299		let (store, _temp) = test_store();
1300		let statement0 = signed_statement(0);
1301		let statement1 = signed_statement_with_topics(1, &[topic(0)], None);
1302		let statement2 = signed_statement_with_topics(2, &[topic(0), topic(1)], Some(dec_key(2)));
1303		let statement3 = signed_statement_with_topics(3, &[topic(0), topic(1), topic(2)], None);
1304		let statement4 =
1305			signed_statement_with_topics(4, &[topic(0), topic(42), topic(2), topic(3)], None);
1306		let statements = vec![statement0, statement1, statement2, statement3, statement4];
1307		for s in &statements {
1308			store.submit(s.clone(), StatementSource::Network);
1309		}
1310
1311		let assert_topics = |topics: &[u64], key: Option<u64>, expected: &[u8]| {
1312			let key = key.map(dec_key);
1313			let topics: Vec<_> = topics.iter().map(|t| topic(*t)).collect();
1314			let mut got_vals: Vec<_> = if let Some(key) = key {
1315				store.posted(&topics, key).unwrap().into_iter().map(|d| d[0]).collect()
1316			} else {
1317				store.broadcasts(&topics).unwrap().into_iter().map(|d| d[0]).collect()
1318			};
1319			got_vals.sort();
1320			assert_eq!(expected.to_vec(), got_vals);
1321		};
1322
1323		assert_topics(&[], None, &[0, 1, 3, 4]);
1324		assert_topics(&[], Some(2), &[2]);
1325		assert_topics(&[0], None, &[1, 3, 4]);
1326		assert_topics(&[1], None, &[3]);
1327		assert_topics(&[2], None, &[3, 4]);
1328		assert_topics(&[3], None, &[4]);
1329		assert_topics(&[42], None, &[4]);
1330
1331		assert_topics(&[0, 1], None, &[3]);
1332		assert_topics(&[0, 1], Some(2), &[2]);
1333		assert_topics(&[0, 1, 99], Some(2), &[]);
1334		assert_topics(&[1, 2], None, &[3]);
1335		assert_topics(&[99], None, &[]);
1336		assert_topics(&[0, 99], None, &[]);
1337		assert_topics(&[0, 1, 2, 3, 42], None, &[]);
1338	}
1339
1340	#[test]
1341	fn constraints() {
1342		let (store, _temp) = test_store();
1343
1344		store.index.write().options.max_total_size = 3000;
1345		let source = StatementSource::Network;
1346		let ok = SubmitResult::New(NetworkPriority::High);
1347		let ignored = SubmitResult::Ignored;
1348
1349		// Account 1 (limit = 1 msg, 1000 bytes)
1350
1351		// Oversized statement is not allowed. Limit for account 1 is 1 msg, 1000 bytes
1352		assert_eq!(store.submit(statement(1, 1, Some(1), 2000), source), ignored);
1353		assert_eq!(store.submit(statement(1, 1, Some(1), 500), source), ok);
1354		// Would not replace channel message with same priority
1355		assert_eq!(store.submit(statement(1, 1, Some(1), 200), source), ignored);
1356		assert_eq!(store.submit(statement(1, 2, Some(1), 600), source), ok);
1357		// Submit another message to another channel with lower priority. Should not be allowed
1358		// because msg count limit is 1
1359		assert_eq!(store.submit(statement(1, 1, Some(2), 100), source), ignored);
1360		assert_eq!(store.index.read().expired.len(), 1);
1361
1362		// Account 2 (limit = 2 msg, 1000 bytes)
1363
1364		assert_eq!(store.submit(statement(2, 1, None, 500), source), ok);
1365		assert_eq!(store.submit(statement(2, 2, None, 100), source), ok);
1366		// Should evict priority 1
1367		assert_eq!(store.submit(statement(2, 3, None, 500), source), ok);
1368		assert_eq!(store.index.read().expired.len(), 2);
1369		// Should evict all
1370		assert_eq!(store.submit(statement(2, 4, None, 1000), source), ok);
1371		assert_eq!(store.index.read().expired.len(), 4);
1372
1373		// Account 3 (limit = 3 msg, 1000 bytes)
1374
1375		assert_eq!(store.submit(statement(3, 2, Some(1), 300), source), ok);
1376		assert_eq!(store.submit(statement(3, 3, Some(2), 300), source), ok);
1377		assert_eq!(store.submit(statement(3, 4, Some(3), 300), source), ok);
1378		// Should evict 2 and 3
1379		assert_eq!(store.submit(statement(3, 5, None, 500), source), ok);
1380		assert_eq!(store.index.read().expired.len(), 6);
1381
1382		assert_eq!(store.index.read().total_size, 2400);
1383		assert_eq!(store.index.read().entries.len(), 4);
1384
1385		// Should be over the global size limit
1386		assert_eq!(store.submit(statement(1, 1, None, 700), source), ignored);
1387		// Should be over the global count limit
1388		store.index.write().options.max_total_statements = 4;
1389		assert_eq!(store.submit(statement(1, 1, None, 100), source), ignored);
1390
1391		let mut expected_statements = vec![
1392			statement(1, 2, Some(1), 600).hash(),
1393			statement(2, 4, None, 1000).hash(),
1394			statement(3, 4, Some(3), 300).hash(),
1395			statement(3, 5, None, 500).hash(),
1396		];
1397		expected_statements.sort();
1398		let mut statements: Vec<_> =
1399			store.statements().unwrap().into_iter().map(|(hash, _)| hash).collect();
1400		statements.sort();
1401		assert_eq!(expected_statements, statements);
1402	}
1403
1404	#[test]
1405	fn max_statement_size_for_gossiping() {
1406		let (store, _temp) = test_store();
1407		store.index.write().options.max_total_size = 42 * crate::MAX_STATEMENT_SIZE;
1408
1409		assert_eq!(
1410			store.submit(
1411				statement(42, 1, Some(1), crate::MAX_STATEMENT_SIZE - 500),
1412				StatementSource::Local
1413			),
1414			SubmitResult::New(NetworkPriority::High)
1415		);
1416
1417		assert_eq!(
1418			store.submit(
1419				statement(42, 2, Some(1), 2 * crate::MAX_STATEMENT_SIZE),
1420				StatementSource::Local
1421			),
1422			SubmitResult::Ignored
1423		);
1424	}
1425
1426	#[test]
1427	fn expired_statements_are_purged() {
1428		use super::DEFAULT_PURGE_AFTER_SEC;
1429		let (mut store, temp) = test_store();
1430		let mut statement = statement(1, 1, Some(3), 100);
1431		store.set_time(0);
1432		statement.set_topic(0, topic(4));
1433		store.submit(statement.clone(), StatementSource::Network);
1434		assert_eq!(store.index.read().entries.len(), 1);
1435		store.remove(&statement.hash()).unwrap();
1436		assert_eq!(store.index.read().entries.len(), 0);
1437		assert_eq!(store.index.read().accounts.len(), 0);
1438		store.set_time(DEFAULT_PURGE_AFTER_SEC + 1);
1439		store.maintain();
1440		assert_eq!(store.index.read().expired.len(), 0);
1441		let keystore = store.keystore.clone();
1442		drop(store);
1443
1444		let client = std::sync::Arc::new(TestClient);
1445		let mut path: std::path::PathBuf = temp.path().into();
1446		path.push("db");
1447		let store = Store::new(&path, Default::default(), client, keystore, None).unwrap();
1448		assert_eq!(store.statements().unwrap().len(), 0);
1449		assert_eq!(store.index.read().expired.len(), 0);
1450	}
1451
1452	#[test]
1453	fn posted_clear_decrypts() {
1454		let (store, _temp) = test_store();
1455		let public = store
1456			.keystore
1457			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1458			.unwrap();
1459		let statement1 = statement(1, 1, None, 100);
1460		let mut statement2 = statement(1, 2, None, 0);
1461		let plain = b"The most valuable secret".to_vec();
1462		statement2.encrypt(&plain, &public).unwrap();
1463		store.submit(statement1, StatementSource::Network);
1464		store.submit(statement2, StatementSource::Network);
1465		let posted_clear = store.posted_clear(&[], public.into()).unwrap();
1466		assert_eq!(posted_clear, vec![plain]);
1467	}
1468
1469	#[test]
1470	fn broadcasts_stmt_returns_encoded_statements() {
1471		let (store, _tmp) = test_store();
1472
1473		// no key, no topic
1474		let s0 = signed_statement_with_topics(0, &[], None);
1475		// same, but with a topic = 42
1476		let s1 = signed_statement_with_topics(1, &[topic(42)], None);
1477		// has a decryption key -> must NOT be returned by broadcasts_stmt
1478		let s2 = signed_statement_with_topics(2, &[topic(42)], Some(dec_key(99)));
1479
1480		for s in [&s0, &s1, &s2] {
1481			store.submit(s.clone(), StatementSource::Network);
1482		}
1483
1484		// no topic filter
1485		let mut hashes: Vec<_> = store
1486			.broadcasts_stmt(&[])
1487			.unwrap()
1488			.into_iter()
1489			.map(|bytes| Statement::decode(&mut &bytes[..]).unwrap().hash())
1490			.collect();
1491		hashes.sort();
1492		let expected_hashes = {
1493			let mut e = vec![s0.hash(), s1.hash()];
1494			e.sort();
1495			e
1496		};
1497		assert_eq!(hashes, expected_hashes);
1498
1499		// filter on topic 42
1500		let got = store.broadcasts_stmt(&[topic(42)]).unwrap();
1501		assert_eq!(got.len(), 1);
1502		let st = Statement::decode(&mut &got[0][..]).unwrap();
1503		assert_eq!(st.hash(), s1.hash());
1504	}
1505
1506	#[test]
1507	fn posted_stmt_returns_encoded_statements_for_dest() {
1508		let (store, _tmp) = test_store();
1509
1510		let public1 = store
1511			.keystore
1512			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1513			.unwrap();
1514		let dest: [u8; 32] = public1.into();
1515
1516		let public2 = store
1517			.keystore
1518			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1519			.unwrap();
1520
1521		// A statement that does have dec_key = dest
1522		let mut s_with_key = statement(1, 1, None, 0);
1523		let plain1 = b"The most valuable secret".to_vec();
1524		s_with_key.encrypt(&plain1, &public1).unwrap();
1525
1526		// A statement with a different dec_key
1527		let mut s_other_key = statement(2, 2, None, 0);
1528		let plain2 = b"The second most valuable secret".to_vec();
1529		s_other_key.encrypt(&plain2, &public2).unwrap();
1530
1531		// Submit them all
1532		for s in [&s_with_key, &s_other_key] {
1533			store.submit(s.clone(), StatementSource::Network);
1534		}
1535
1536		// posted_stmt should only return the one with dec_key = dest
1537		let retrieved = store.posted_stmt(&[], dest).unwrap();
1538		assert_eq!(retrieved.len(), 1, "Only one statement has dec_key=dest");
1539
1540		// Re-decode that returned statement to confirm it is correct
1541		let returned_stmt = Statement::decode(&mut &retrieved[0][..]).unwrap();
1542		assert_eq!(
1543			returned_stmt.hash(),
1544			s_with_key.hash(),
1545			"Returned statement must match s_with_key"
1546		);
1547	}
1548
1549	#[test]
1550	fn posted_clear_stmt_returns_statement_followed_by_plain_data() {
1551		let (store, _tmp) = test_store();
1552
1553		let public1 = store
1554			.keystore
1555			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1556			.unwrap();
1557		let dest: [u8; 32] = public1.into();
1558
1559		let public2 = store
1560			.keystore
1561			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1562			.unwrap();
1563
1564		// A statement that does have dec_key = dest
1565		let mut s_with_key = statement(1, 1, None, 0);
1566		let plain1 = b"The most valuable secret".to_vec();
1567		s_with_key.encrypt(&plain1, &public1).unwrap();
1568
1569		// A statement with a different dec_key
1570		let mut s_other_key = statement(2, 2, None, 0);
1571		let plain2 = b"The second most valuable secret".to_vec();
1572		s_other_key.encrypt(&plain2, &public2).unwrap();
1573
1574		// Submit them all
1575		for s in [&s_with_key, &s_other_key] {
1576			store.submit(s.clone(), StatementSource::Network);
1577		}
1578
1579		// posted_stmt should only return the one with dec_key = dest
1580		let retrieved = store.posted_clear_stmt(&[], dest).unwrap();
1581		assert_eq!(retrieved.len(), 1, "Only one statement has dec_key=dest");
1582
1583		// We expect: [ encoded Statement ] + [ the decrypted bytes ]
1584		let encoded_stmt = s_with_key.encode();
1585		let stmt_len = encoded_stmt.len();
1586
1587		// 1) statement is first
1588		assert_eq!(&retrieved[0][..stmt_len], &encoded_stmt[..]);
1589
1590		// 2) followed by the decrypted payload
1591		let trailing = &retrieved[0][stmt_len..];
1592		assert_eq!(trailing, &plain1[..]);
1593	}
1594
1595	#[test]
1596	fn posted_clear_returns_plain_data_for_dest_and_topics() {
1597		let (store, _tmp) = test_store();
1598
1599		// prepare two key-pairs
1600		let public_dest = store
1601			.keystore
1602			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1603			.unwrap();
1604		let dest: [u8; 32] = public_dest.into();
1605
1606		let public_other = store
1607			.keystore
1608			.ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1609			.unwrap();
1610
1611		// statement that SHOULD be returned (matches dest & topic 42)
1612		let mut s_good = statement(1, 1, None, 0);
1613		let plaintext_good = b"The most valuable secret".to_vec();
1614		s_good.encrypt(&plaintext_good, &public_dest).unwrap();
1615		s_good.set_topic(0, topic(42));
1616
1617		// statement that should NOT be returned (same dest but different topic)
1618		let mut s_wrong_topic = statement(2, 2, None, 0);
1619		s_wrong_topic.encrypt(b"Wrong topic", &public_dest).unwrap();
1620		s_wrong_topic.set_topic(0, topic(99));
1621
1622		// statement that should NOT be returned (different dest)
1623		let mut s_other_dest = statement(3, 3, None, 0);
1624		s_other_dest.encrypt(b"Other dest", &public_other).unwrap();
1625		s_other_dest.set_topic(0, topic(42));
1626
1627		// submit all
1628		for s in [&s_good, &s_wrong_topic, &s_other_dest] {
1629			store.submit(s.clone(), StatementSource::Network);
1630		}
1631
1632		// call posted_clear with the topic filter and dest
1633		let retrieved = store.posted_clear(&[topic(42)], dest).unwrap();
1634
1635		// exactly one element, equal to the expected plaintext
1636		assert_eq!(retrieved, vec![plaintext_good]);
1637	}
1638
1639	#[test]
1640	fn remove_by_covers_various_situations() {
1641		use sp_statement_store::{StatementSource, StatementStore, SubmitResult};
1642
1643		// Use a fresh store and fixed time so we can control purging.
1644		let (mut store, _temp) = test_store();
1645		store.set_time(0);
1646
1647		// Reuse helpers from this module.
1648		let t42 = topic(42);
1649		let k7 = dec_key(7);
1650
1651		// Account A = 4 (has per-account limits (4, 1000) in the mock runtime)
1652		// - Mix of topic, decryption-key and channel to exercise every index.
1653		let mut s_a1 = statement(4, 10, Some(100), 100);
1654		s_a1.set_topic(0, t42);
1655		let h_a1 = s_a1.hash();
1656
1657		let mut s_a2 = statement(4, 20, Some(200), 150);
1658		s_a2.set_decryption_key(k7);
1659		let h_a2 = s_a2.hash();
1660
1661		let s_a3 = statement(4, 30, None, 50);
1662		let h_a3 = s_a3.hash();
1663
1664		// Account B = 3 (control group that must remain untouched).
1665		let s_b1 = statement(3, 10, None, 100);
1666		let h_b1 = s_b1.hash();
1667
1668		let mut s_b2 = statement(3, 15, Some(300), 100);
1669		s_b2.set_topic(0, t42);
1670		s_b2.set_decryption_key(k7);
1671		let h_b2 = s_b2.hash();
1672
1673		// Submit all statements.
1674		for s in [&s_a1, &s_a2, &s_a3, &s_b1, &s_b2] {
1675			assert!(matches!(
1676				store.submit(s.clone(), StatementSource::Network),
1677				SubmitResult::New(_)
1678			));
1679		}
1680
1681		// --- Pre-conditions: everything is indexed as expected.
1682		{
1683			let idx = store.index.read();
1684			assert_eq!(idx.entries.len(), 5, "all 5 should be present");
1685			assert!(idx.accounts.contains_key(&account(4)));
1686			assert!(idx.accounts.contains_key(&account(3)));
1687			assert_eq!(idx.total_size, 100 + 150 + 50 + 100 + 100);
1688
1689			// Topic and key sets contain both A & B entries.
1690			let set_t = idx.by_topic.get(&t42).expect("topic set exists");
1691			assert!(set_t.contains(&h_a1) && set_t.contains(&h_b2));
1692
1693			let set_k = idx.by_dec_key.get(&Some(k7)).expect("key set exists");
1694			assert!(set_k.contains(&h_a2) && set_k.contains(&h_b2));
1695		}
1696
1697		// --- Action: remove all statements by Account A.
1698		store.remove_by(account(4)).expect("remove_by should succeed");
1699
1700		// --- Post-conditions: A's statements are gone and marked expired; B's remain.
1701		{
1702			// A's statements removed from DB view.
1703			for h in [h_a1, h_a2, h_a3] {
1704				assert!(store.statement(&h).unwrap().is_none(), "A's statement should be removed");
1705			}
1706
1707			// B's statements still present.
1708			for h in [h_b1, h_b2] {
1709				assert!(store.statement(&h).unwrap().is_some(), "B's statement should remain");
1710			}
1711
1712			let idx = store.index.read();
1713
1714			// Account map updated.
1715			assert!(!idx.accounts.contains_key(&account(4)), "Account A must be gone");
1716			assert!(idx.accounts.contains_key(&account(3)), "Account B must remain");
1717
1718			// Removed statements are marked expired.
1719			assert!(idx.expired.contains_key(&h_a1));
1720			assert!(idx.expired.contains_key(&h_a2));
1721			assert!(idx.expired.contains_key(&h_a3));
1722			assert_eq!(idx.expired.len(), 3);
1723
1724			// Entry count & total_size reflect only B's data.
1725			assert_eq!(idx.entries.len(), 2);
1726			assert_eq!(idx.total_size, 100 + 100);
1727
1728			// Topic index: only B2 remains for topic 42.
1729			let set_t = idx.by_topic.get(&t42).expect("topic set exists");
1730			assert!(set_t.contains(&h_b2));
1731			assert!(!set_t.contains(&h_a1));
1732
1733			// Decryption-key index: only B2 remains for key 7.
1734			let set_k = idx.by_dec_key.get(&Some(k7)).expect("key set exists");
1735			assert!(set_k.contains(&h_b2));
1736			assert!(!set_k.contains(&h_a2));
1737		}
1738
1739		// --- Idempotency: removing again is a no-op and should not error.
1740		store.remove_by(account(4)).expect("second remove_by should be a no-op");
1741
1742		// --- Purge: advance time beyond TTL and run maintenance; expired entries disappear.
1743		let purge_after = store.index.read().options.purge_after_sec;
1744		store.set_time(purge_after + 1);
1745		store.maintain();
1746		assert_eq!(store.index.read().expired.len(), 0, "expired entries should be purged");
1747
1748		// --- Reuse: Account A can submit again after purge.
1749		let s_new = statement(4, 40, None, 10);
1750		assert!(matches!(store.submit(s_new, StatementSource::Network), SubmitResult::New(_)));
1751	}
1752}