1#![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
79pub const DEFAULT_PURGE_AFTER_SEC: u64 = 2 * 24 * 60 * 60; pub const DEFAULT_MAX_TOTAL_STATEMENTS: usize = 4 * 1024 * 1024; pub const DEFAULT_MAX_TOTAL_SIZE: usize = 2 * 1024 * 1024 * 1024; pub 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 by_priority: BTreeMap<PriorityKey, (Option<Channel>, usize)>,
132 channels: HashMap<Channel, ChannelEntry>,
134 data_size: usize,
136}
137
138pub struct Options {
140 max_total_statements: usize,
143 max_total_size: usize,
146 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>, 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 self.client.info().finalized_hash
195 });
196 api.validate_statement(block, source, statement)
197 .map_err(|_| InvalidStatement::InternalError)?
198 }
199}
200
201pub 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 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] = [∅ 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 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 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 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 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 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 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 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 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 break
451 }
452 if evicted.contains(&entry.hash) {
453 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 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 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 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 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 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 log::warn!(
661 target: LOG_TARGET,
662 "Corrupt statement {:?}",
663 HexDisplay::from(hash)
664 );
665 }
666 },
667 None => {
668 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 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 pub fn as_statement_store_ext(self: Arc<Self>) -> StatementStoreExt {
722 StatementStoreExt::new(self)
723 }
724
725 fn posted_clear_inner<R>(
728 &self,
729 match_all_topics: &[Topic],
730 dest: [u8; 32],
731 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 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 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 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 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 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 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 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 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 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 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 } 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 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 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) }
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 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 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 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 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 assert_eq!(store.submit(statement(1, 1, Some(2), 100), source), ignored);
1360 assert_eq!(store.index.read().expired.len(), 1);
1361
1362 assert_eq!(store.submit(statement(2, 1, None, 500), source), ok);
1365 assert_eq!(store.submit(statement(2, 2, None, 100), source), ok);
1366 assert_eq!(store.submit(statement(2, 3, None, 500), source), ok);
1368 assert_eq!(store.index.read().expired.len(), 2);
1369 assert_eq!(store.submit(statement(2, 4, None, 1000), source), ok);
1371 assert_eq!(store.index.read().expired.len(), 4);
1372
1373 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 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 assert_eq!(store.submit(statement(1, 1, None, 700), source), ignored);
1387 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 let s0 = signed_statement_with_topics(0, &[], None);
1475 let s1 = signed_statement_with_topics(1, &[topic(42)], None);
1477 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 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 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 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 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 for s in [&s_with_key, &s_other_key] {
1533 store.submit(s.clone(), StatementSource::Network);
1534 }
1535
1536 let retrieved = store.posted_stmt(&[], dest).unwrap();
1538 assert_eq!(retrieved.len(), 1, "Only one statement has dec_key=dest");
1539
1540 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 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 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 for s in [&s_with_key, &s_other_key] {
1576 store.submit(s.clone(), StatementSource::Network);
1577 }
1578
1579 let retrieved = store.posted_clear_stmt(&[], dest).unwrap();
1581 assert_eq!(retrieved.len(), 1, "Only one statement has dec_key=dest");
1582
1583 let encoded_stmt = s_with_key.encode();
1585 let stmt_len = encoded_stmt.len();
1586
1587 assert_eq!(&retrieved[0][..stmt_len], &encoded_stmt[..]);
1589
1590 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 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 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 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 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 for s in [&s_good, &s_wrong_topic, &s_other_dest] {
1629 store.submit(s.clone(), StatementSource::Network);
1630 }
1631
1632 let retrieved = store.posted_clear(&[topic(42)], dest).unwrap();
1634
1635 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 let (mut store, _temp) = test_store();
1645 store.set_time(0);
1646
1647 let t42 = topic(42);
1649 let k7 = dec_key(7);
1650
1651 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 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 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 {
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 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 store.remove_by(account(4)).expect("remove_by should succeed");
1699
1700 {
1702 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 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 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 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 assert_eq!(idx.entries.len(), 2);
1726 assert_eq!(idx.total_size, 100 + 100);
1727
1728 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 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 store.remove_by(account(4)).expect("second remove_by should be a no-op");
1741
1742 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 let s_new = statement(4, 40, None, 10);
1750 assert!(matches!(store.submit(s_new, StatementSource::Network), SubmitResult::New(_)));
1751 }
1752}