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
79const DEFAULT_PURGE_AFTER_SEC: u64 = 2 * 24 * 60 * 60; const DEFAULT_MAX_TOTAL_STATEMENTS: usize = 8192;
81const DEFAULT_MAX_TOTAL_SIZE: usize = 64 * 1024 * 1024;
82
83const MAINTENANCE_PERIOD: std::time::Duration = std::time::Duration::from_secs(30);
84
85mod col {
86 pub const META: u8 = 0;
87 pub const STATEMENTS: u8 = 1;
88 pub const EXPIRED: u8 = 2;
89
90 pub const COUNT: u8 = 3;
91}
92
93#[derive(Eq, PartialEq, Debug, Ord, PartialOrd, Clone, Copy)]
94struct Priority(u32);
95
96#[derive(PartialEq, Eq)]
97struct PriorityKey {
98 hash: Hash,
99 priority: Priority,
100}
101
102impl PartialOrd for PriorityKey {
103 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
104 Some(self.cmp(other))
105 }
106}
107
108impl Ord for PriorityKey {
109 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
110 self.priority.cmp(&other.priority).then_with(|| self.hash.cmp(&other.hash))
111 }
112}
113
114#[derive(PartialEq, Eq)]
115struct ChannelEntry {
116 hash: Hash,
117 priority: Priority,
118}
119
120#[derive(Default)]
121struct StatementsForAccount {
122 by_priority: BTreeMap<PriorityKey, (Option<Channel>, usize)>,
124 channels: HashMap<Channel, ChannelEntry>,
126 data_size: usize,
128}
129
130pub struct Options {
132 max_total_statements: usize,
135 max_total_size: usize,
138 purge_after_sec: u64,
140}
141
142impl Default for Options {
143 fn default() -> Self {
144 Options {
145 max_total_statements: DEFAULT_MAX_TOTAL_STATEMENTS,
146 max_total_size: DEFAULT_MAX_TOTAL_SIZE,
147 purge_after_sec: DEFAULT_PURGE_AFTER_SEC,
148 }
149 }
150}
151
152#[derive(Default)]
153struct Index {
154 by_topic: HashMap<Topic, HashSet<Hash>>,
155 by_dec_key: HashMap<Option<DecryptionKey>, HashSet<Hash>>,
156 topics_and_keys: HashMap<Hash, ([Option<Topic>; MAX_TOPICS], Option<DecryptionKey>)>,
157 entries: HashMap<Hash, (AccountId, Priority, usize)>,
158 expired: HashMap<Hash, u64>, accounts: HashMap<AccountId, StatementsForAccount>,
160 options: Options,
161 total_size: usize,
162}
163
164struct ClientWrapper<Block, Client> {
165 client: Arc<Client>,
166 _block: std::marker::PhantomData<Block>,
167}
168
169impl<Block, Client> ClientWrapper<Block, Client>
170where
171 Block: BlockT,
172 Block::Hash: From<BlockHash>,
173 Client: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
174 Client::Api: ValidateStatement<Block>,
175{
176 fn validate_statement(
177 &self,
178 block: Option<BlockHash>,
179 source: StatementSource,
180 statement: Statement,
181 ) -> std::result::Result<ValidStatement, InvalidStatement> {
182 let api = self.client.runtime_api();
183 let block = block.map(Into::into).unwrap_or_else(|| {
184 self.client.info().finalized_hash
186 });
187 api.validate_statement(block, source, statement)
188 .map_err(|_| InvalidStatement::InternalError)?
189 }
190}
191
192pub struct Store {
194 db: parity_db::Db,
195 index: RwLock<Index>,
196 validate_fn: Box<
197 dyn Fn(
198 Option<BlockHash>,
199 StatementSource,
200 Statement,
201 ) -> std::result::Result<ValidStatement, InvalidStatement>
202 + Send
203 + Sync,
204 >,
205 keystore: Arc<LocalKeystore>,
206 time_override: Option<u64>,
208 metrics: PrometheusMetrics,
209}
210
211enum IndexQuery {
212 Unknown,
213 Exists,
214 Expired,
215}
216
217enum MaybeInserted {
218 Inserted(HashSet<Hash>),
219 Ignored,
220}
221
222impl Index {
223 fn new(options: Options) -> Index {
224 Index { options, ..Default::default() }
225 }
226
227 fn insert_new(&mut self, hash: Hash, account: AccountId, statement: &Statement) {
228 let mut all_topics = [None; MAX_TOPICS];
229 let mut nt = 0;
230 while let Some(t) = statement.topic(nt) {
231 self.by_topic.entry(t).or_default().insert(hash);
232 all_topics[nt] = Some(t);
233 nt += 1;
234 }
235 let key = statement.decryption_key();
236 self.by_dec_key.entry(key).or_default().insert(hash);
237 if nt > 0 || key.is_some() {
238 self.topics_and_keys.insert(hash, (all_topics, key));
239 }
240 let priority = Priority(statement.priority().unwrap_or(0));
241 self.entries.insert(hash, (account, priority, statement.data_len()));
242 self.total_size += statement.data_len();
243 let account_info = self.accounts.entry(account).or_default();
244 account_info.data_size += statement.data_len();
245 if let Some(channel) = statement.channel() {
246 account_info.channels.insert(channel, ChannelEntry { hash, priority });
247 }
248 account_info
249 .by_priority
250 .insert(PriorityKey { hash, priority }, (statement.channel(), statement.data_len()));
251 }
252
253 fn query(&self, hash: &Hash) -> IndexQuery {
254 if self.entries.contains_key(hash) {
255 return IndexQuery::Exists
256 }
257 if self.expired.contains_key(hash) {
258 return IndexQuery::Expired
259 }
260 IndexQuery::Unknown
261 }
262
263 fn insert_expired(&mut self, hash: Hash, timestamp: u64) {
264 self.expired.insert(hash, timestamp);
265 }
266
267 fn iterate_with(
268 &self,
269 key: Option<DecryptionKey>,
270 match_all_topics: &[Topic],
271 mut f: impl FnMut(&Hash) -> Result<()>,
272 ) -> Result<()> {
273 let empty = HashSet::new();
274 let mut sets: [&HashSet<Hash>; MAX_TOPICS + 1] = [∅ MAX_TOPICS + 1];
275 if match_all_topics.len() > MAX_TOPICS {
276 return Ok(())
277 }
278 let key_set = self.by_dec_key.get(&key);
279 if key_set.map_or(0, |s| s.len()) == 0 {
280 return Ok(())
282 }
283 sets[0] = key_set.expect("Function returns if key_set is None");
284 for (i, t) in match_all_topics.iter().enumerate() {
285 let set = self.by_topic.get(t);
286 if set.map_or(0, |s| s.len()) == 0 {
287 return Ok(())
289 }
290 sets[i + 1] = set.expect("Function returns if set is None");
291 }
292 let sets = &mut sets[0..match_all_topics.len() + 1];
293 sets.sort_by_key(|s| s.len());
295 for item in sets[0] {
296 if sets[1..].iter().all(|set| set.contains(item)) {
297 log::trace!(
298 target: LOG_TARGET,
299 "Iterating by topic/key: statement {:?}",
300 HexDisplay::from(item)
301 );
302 f(item)?
303 }
304 }
305 Ok(())
306 }
307
308 fn maintain(&mut self, current_time: u64) -> Vec<Hash> {
309 let mut purged = Vec::new();
311 self.expired.retain(|hash, timestamp| {
312 if *timestamp + self.options.purge_after_sec <= current_time {
313 purged.push(*hash);
314 log::trace!(target: LOG_TARGET, "Purged statement {:?}", HexDisplay::from(hash));
315 false
316 } else {
317 true
318 }
319 });
320 purged
321 }
322
323 fn make_expired(&mut self, hash: &Hash, current_time: u64) -> bool {
324 if let Some((account, priority, len)) = self.entries.remove(hash) {
325 self.total_size -= len;
326 if let Some((topics, key)) = self.topics_and_keys.remove(hash) {
327 for t in topics.into_iter().flatten() {
328 if let std::collections::hash_map::Entry::Occupied(mut set) =
329 self.by_topic.entry(t)
330 {
331 set.get_mut().remove(hash);
332 if set.get().is_empty() {
333 set.remove_entry();
334 }
335 }
336 }
337 if let std::collections::hash_map::Entry::Occupied(mut set) =
338 self.by_dec_key.entry(key)
339 {
340 set.get_mut().remove(hash);
341 if set.get().is_empty() {
342 set.remove_entry();
343 }
344 }
345 }
346 self.expired.insert(*hash, current_time);
347 if let std::collections::hash_map::Entry::Occupied(mut account_rec) =
348 self.accounts.entry(account)
349 {
350 let key = PriorityKey { hash: *hash, priority };
351 if let Some((channel, len)) = account_rec.get_mut().by_priority.remove(&key) {
352 account_rec.get_mut().data_size -= len;
353 if let Some(channel) = channel {
354 account_rec.get_mut().channels.remove(&channel);
355 }
356 }
357 if account_rec.get().by_priority.is_empty() {
358 account_rec.remove_entry();
359 }
360 }
361 log::trace!(target: LOG_TARGET, "Expired statement {:?}", HexDisplay::from(hash));
362 true
363 } else {
364 false
365 }
366 }
367
368 fn insert(
369 &mut self,
370 hash: Hash,
371 statement: &Statement,
372 account: &AccountId,
373 validation: &ValidStatement,
374 current_time: u64,
375 ) -> MaybeInserted {
376 let statement_len = statement.data_len();
377 if statement_len > validation.max_size as usize {
378 log::debug!(
379 target: LOG_TARGET,
380 "Ignored oversize message: {:?} ({} bytes)",
381 HexDisplay::from(&hash),
382 statement_len,
383 );
384 return MaybeInserted::Ignored
385 }
386
387 let mut evicted = HashSet::new();
388 let mut would_free_size = 0;
389 let priority = Priority(statement.priority().unwrap_or(0));
390 let (max_size, max_count) = (validation.max_size as usize, validation.max_count as usize);
391 if let Some(account_rec) = self.accounts.get(account) {
395 if let Some(channel) = statement.channel() {
396 if let Some(channel_record) = account_rec.channels.get(&channel) {
397 if priority <= channel_record.priority {
398 log::debug!(
400 target: LOG_TARGET,
401 "Ignored lower priority channel message: {:?} {:?} <= {:?}",
402 HexDisplay::from(&hash),
403 priority,
404 channel_record.priority,
405 );
406 return MaybeInserted::Ignored
407 } else {
408 log::debug!(
411 target: LOG_TARGET,
412 "Replacing higher priority channel message: {:?} ({:?}) > {:?} ({:?})",
413 HexDisplay::from(&hash),
414 priority,
415 HexDisplay::from(&channel_record.hash),
416 channel_record.priority,
417 );
418 let key = PriorityKey {
419 hash: channel_record.hash,
420 priority: channel_record.priority,
421 };
422 if let Some((_channel, len)) = account_rec.by_priority.get(&key) {
423 would_free_size += *len;
424 evicted.insert(channel_record.hash);
425 }
426 }
427 }
428 }
429 for (entry, (_, len)) in account_rec.by_priority.iter() {
431 if (account_rec.data_size - would_free_size + statement_len <= max_size) &&
432 account_rec.by_priority.len() + 1 - evicted.len() <= max_count
433 {
434 break
436 }
437 if evicted.contains(&entry.hash) {
438 continue
440 }
441 if entry.priority >= priority {
442 log::debug!(
443 target: LOG_TARGET,
444 "Ignored message due to constraints {:?} {:?} < {:?}",
445 HexDisplay::from(&hash),
446 priority,
447 entry.priority,
448 );
449 return MaybeInserted::Ignored
450 }
451 evicted.insert(entry.hash);
452 would_free_size += len;
453 }
454 }
455 if !((self.total_size - would_free_size + statement_len <= self.options.max_total_size) &&
457 self.entries.len() + 1 - evicted.len() <= self.options.max_total_statements)
458 {
459 log::debug!(
460 target: LOG_TARGET,
461 "Ignored statement {} because the store is full (size={}, count={})",
462 HexDisplay::from(&hash),
463 self.total_size,
464 self.entries.len(),
465 );
466 return MaybeInserted::Ignored
467 }
468
469 for h in &evicted {
470 self.make_expired(h, current_time);
471 }
472 self.insert_new(hash, *account, statement);
473 MaybeInserted::Inserted(evicted)
474 }
475}
476
477impl Store {
478 pub fn new_shared<Block, Client>(
481 path: &std::path::Path,
482 options: Options,
483 client: Arc<Client>,
484 keystore: Arc<LocalKeystore>,
485 prometheus: Option<&PrometheusRegistry>,
486 task_spawner: &dyn SpawnNamed,
487 ) -> Result<Arc<Store>>
488 where
489 Block: BlockT,
490 Block::Hash: From<BlockHash>,
491 Client: ProvideRuntimeApi<Block>
492 + HeaderBackend<Block>
493 + sc_client_api::ExecutorProvider<Block>
494 + Send
495 + Sync
496 + 'static,
497 Client::Api: ValidateStatement<Block>,
498 {
499 let store = Arc::new(Self::new(path, options, client, keystore, prometheus)?);
500
501 let worker_store = store.clone();
503 task_spawner.spawn(
504 "statement-store-maintenance",
505 Some("statement-store"),
506 Box::pin(async move {
507 let mut interval = tokio::time::interval(MAINTENANCE_PERIOD);
508 loop {
509 interval.tick().await;
510 worker_store.maintain();
511 }
512 }),
513 );
514
515 Ok(store)
516 }
517
518 fn new<Block, Client>(
521 path: &std::path::Path,
522 options: Options,
523 client: Arc<Client>,
524 keystore: Arc<LocalKeystore>,
525 prometheus: Option<&PrometheusRegistry>,
526 ) -> Result<Store>
527 where
528 Block: BlockT,
529 Block::Hash: From<BlockHash>,
530 Client: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
531 Client::Api: ValidateStatement<Block>,
532 {
533 let mut path: std::path::PathBuf = path.into();
534 path.push("statements");
535
536 let mut config = parity_db::Options::with_columns(&path, col::COUNT);
537
538 let statement_col = &mut config.columns[col::STATEMENTS as usize];
539 statement_col.ref_counted = false;
540 statement_col.preimage = true;
541 statement_col.uniform = true;
542 let db = parity_db::Db::open_or_create(&config).map_err(|e| Error::Db(e.to_string()))?;
543 match db.get(col::META, &KEY_VERSION).map_err(|e| Error::Db(e.to_string()))? {
544 Some(version) => {
545 let version = u32::from_le_bytes(
546 version
547 .try_into()
548 .map_err(|_| Error::Db("Error reading database version".into()))?,
549 );
550 if version != CURRENT_VERSION {
551 return Err(Error::Db(format!("Unsupported database version: {version}")))
552 }
553 },
554 None => {
555 db.commit([(
556 col::META,
557 KEY_VERSION.to_vec(),
558 Some(CURRENT_VERSION.to_le_bytes().to_vec()),
559 )])
560 .map_err(|e| Error::Db(e.to_string()))?;
561 },
562 }
563
564 let validator = ClientWrapper { client, _block: Default::default() };
565 let validate_fn = Box::new(move |block, source, statement| {
566 validator.validate_statement(block, source, statement)
567 });
568
569 let store = Store {
570 db,
571 index: RwLock::new(Index::new(options)),
572 validate_fn,
573 keystore,
574 time_override: None,
575 metrics: PrometheusMetrics::new(prometheus),
576 };
577 store.populate()?;
578 Ok(store)
579 }
580
581 fn populate(&self) -> Result<()> {
586 {
587 let mut index = self.index.write();
588 self.db
589 .iter_column_while(col::STATEMENTS, |item| {
590 let statement = item.value;
591 if let Ok(statement) = Statement::decode(&mut statement.as_slice()) {
592 let hash = statement.hash();
593 log::trace!(
594 target: LOG_TARGET,
595 "Statement loaded {:?}",
596 HexDisplay::from(&hash)
597 );
598 if let Some(account_id) = statement.account_id() {
599 index.insert_new(hash, account_id, &statement);
600 } else {
601 log::debug!(
602 target: LOG_TARGET,
603 "Error decoding statement loaded from the DB: {:?}",
604 HexDisplay::from(&hash)
605 );
606 }
607 }
608 true
609 })
610 .map_err(|e| Error::Db(e.to_string()))?;
611 self.db
612 .iter_column_while(col::EXPIRED, |item| {
613 let expired_info = item.value;
614 if let Ok((hash, timestamp)) =
615 <(Hash, u64)>::decode(&mut expired_info.as_slice())
616 {
617 log::trace!(
618 target: LOG_TARGET,
619 "Statement loaded (expired): {:?}",
620 HexDisplay::from(&hash)
621 );
622 index.insert_expired(hash, timestamp);
623 }
624 true
625 })
626 .map_err(|e| Error::Db(e.to_string()))?;
627 }
628
629 self.maintain();
630 Ok(())
631 }
632
633 fn collect_statements<R>(
634 &self,
635 key: Option<DecryptionKey>,
636 match_all_topics: &[Topic],
637 mut f: impl FnMut(Statement) -> Option<R>,
638 ) -> Result<Vec<R>> {
639 let mut result = Vec::new();
640 let index = self.index.read();
641 index.iterate_with(key, match_all_topics, |hash| {
642 match self.db.get(col::STATEMENTS, hash).map_err(|e| Error::Db(e.to_string()))? {
643 Some(entry) => {
644 if let Ok(statement) = Statement::decode(&mut entry.as_slice()) {
645 if let Some(data) = f(statement) {
646 result.push(data);
647 }
648 } else {
649 log::warn!(
651 target: LOG_TARGET,
652 "Corrupt statement {:?}",
653 HexDisplay::from(hash)
654 );
655 }
656 },
657 None => {
658 log::warn!(
660 target: LOG_TARGET,
661 "Missing statement {:?}",
662 HexDisplay::from(hash)
663 );
664 },
665 }
666 Ok(())
667 })?;
668 Ok(result)
669 }
670
671 pub fn maintain(&self) {
673 log::trace!(target: LOG_TARGET, "Started store maintenance");
674 let deleted = self.index.write().maintain(self.timestamp());
675 let deleted: Vec<_> =
676 deleted.into_iter().map(|hash| (col::EXPIRED, hash.to_vec(), None)).collect();
677 let count = deleted.len() as u64;
678 if let Err(e) = self.db.commit(deleted) {
679 log::warn!(target: LOG_TARGET, "Error writing to the statement database: {:?}", e);
680 } else {
681 self.metrics.report(|metrics| metrics.statements_pruned.inc_by(count));
682 }
683 log::trace!(
684 target: LOG_TARGET,
685 "Completed store maintenance. Purged: {}, Active: {}, Expired: {}",
686 count,
687 self.index.read().entries.len(),
688 self.index.read().expired.len()
689 );
690 }
691
692 fn timestamp(&self) -> u64 {
693 self.time_override.unwrap_or_else(|| {
694 std::time::SystemTime::now()
695 .duration_since(std::time::UNIX_EPOCH)
696 .unwrap_or_default()
697 .as_secs()
698 })
699 }
700
701 #[cfg(test)]
702 fn set_time(&mut self, time: u64) {
703 self.time_override = Some(time);
704 }
705
706 pub fn as_statement_store_ext(self: Arc<Self>) -> StatementStoreExt {
708 StatementStoreExt::new(self)
709 }
710}
711
712impl StatementStore for Store {
713 fn statements(&self) -> Result<Vec<(Hash, Statement)>> {
715 let index = self.index.read();
716 let mut result = Vec::with_capacity(index.entries.len());
717 for h in self.index.read().entries.keys() {
718 let encoded = self.db.get(col::STATEMENTS, h).map_err(|e| Error::Db(e.to_string()))?;
719 if let Some(encoded) = encoded {
720 if let Ok(statement) = Statement::decode(&mut encoded.as_slice()) {
721 let hash = statement.hash();
722 result.push((hash, statement));
723 }
724 }
725 }
726 Ok(result)
727 }
728
729 fn statement(&self, hash: &Hash) -> Result<Option<Statement>> {
731 Ok(
732 match self
733 .db
734 .get(col::STATEMENTS, hash.as_slice())
735 .map_err(|e| Error::Db(e.to_string()))?
736 {
737 Some(entry) => {
738 log::trace!(
739 target: LOG_TARGET,
740 "Queried statement {:?}",
741 HexDisplay::from(hash)
742 );
743 Some(
744 Statement::decode(&mut entry.as_slice())
745 .map_err(|e| Error::Decode(e.to_string()))?,
746 )
747 },
748 None => {
749 log::trace!(
750 target: LOG_TARGET,
751 "Queried missing statement {:?}",
752 HexDisplay::from(hash)
753 );
754 None
755 },
756 },
757 )
758 }
759
760 fn broadcasts(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>> {
763 self.collect_statements(None, match_all_topics, |statement| statement.into_data())
764 }
765
766 fn posted(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
770 self.collect_statements(Some(dest), match_all_topics, |statement| statement.into_data())
771 }
772
773 fn posted_clear(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>> {
776 self.collect_statements(Some(dest), match_all_topics, |statement| {
777 if let (Some(key), Some(_)) = (statement.decryption_key(), statement.data()) {
778 let public: sp_core::ed25519::Public = UncheckedFrom::unchecked_from(key);
779 let public: sp_statement_store::ed25519::Public = public.into();
780 match self.keystore.key_pair::<sp_statement_store::ed25519::Pair>(&public) {
781 Err(e) => {
782 log::debug!(
783 target: LOG_TARGET,
784 "Keystore error: {:?}, for statement {:?}",
785 e,
786 HexDisplay::from(&statement.hash())
787 );
788 None
789 },
790 Ok(None) => {
791 log::debug!(
792 target: LOG_TARGET,
793 "Keystore is missing key for statement {:?}",
794 HexDisplay::from(&statement.hash())
795 );
796 None
797 },
798 Ok(Some(pair)) => match statement.decrypt_private(&pair.into_inner()) {
799 Ok(r) => r,
800 Err(e) => {
801 log::debug!(
802 target: LOG_TARGET,
803 "Decryption error: {:?}, for statement {:?}",
804 e,
805 HexDisplay::from(&statement.hash())
806 );
807 None
808 },
809 },
810 }
811 } else {
812 None
813 }
814 })
815 }
816
817 fn submit(&self, statement: Statement, source: StatementSource) -> SubmitResult {
819 let hash = statement.hash();
820 match self.index.read().query(&hash) {
821 IndexQuery::Expired =>
822 if !source.can_be_resubmitted() {
823 return SubmitResult::KnownExpired
824 },
825 IndexQuery::Exists =>
826 if !source.can_be_resubmitted() {
827 return SubmitResult::Known
828 },
829 IndexQuery::Unknown => {},
830 }
831
832 let Some(account_id) = statement.account_id() else {
833 log::debug!(
834 target: LOG_TARGET,
835 "Statement validation failed: Missing proof ({:?})",
836 HexDisplay::from(&hash),
837 );
838 self.metrics.report(|metrics| metrics.validations_invalid.inc());
839 return SubmitResult::Bad("No statement proof")
840 };
841
842 let at_block = if let Some(Proof::OnChain { block_hash, .. }) = statement.proof() {
844 Some(*block_hash)
845 } else {
846 None
847 };
848 let validation_result = (self.validate_fn)(at_block, source, statement.clone());
849 let validation = match validation_result {
850 Ok(validation) => validation,
851 Err(InvalidStatement::BadProof) => {
852 log::debug!(
853 target: LOG_TARGET,
854 "Statement validation failed: BadProof, {:?}",
855 HexDisplay::from(&hash),
856 );
857 self.metrics.report(|metrics| metrics.validations_invalid.inc());
858 return SubmitResult::Bad("Bad statement proof")
859 },
860 Err(InvalidStatement::NoProof) => {
861 log::debug!(
862 target: LOG_TARGET,
863 "Statement validation failed: NoProof, {:?}",
864 HexDisplay::from(&hash),
865 );
866 self.metrics.report(|metrics| metrics.validations_invalid.inc());
867 return SubmitResult::Bad("Missing statement proof")
868 },
869 Err(InvalidStatement::InternalError) =>
870 return SubmitResult::InternalError(Error::Runtime),
871 };
872
873 let current_time = self.timestamp();
874 let mut commit = Vec::new();
875 {
876 let mut index = self.index.write();
877
878 let evicted =
879 match index.insert(hash, &statement, &account_id, &validation, current_time) {
880 MaybeInserted::Ignored => return SubmitResult::Ignored,
881 MaybeInserted::Inserted(evicted) => evicted,
882 };
883
884 commit.push((col::STATEMENTS, hash.to_vec(), Some(statement.encode())));
885 for hash in evicted {
886 commit.push((col::STATEMENTS, hash.to_vec(), None));
887 commit.push((col::EXPIRED, hash.to_vec(), Some((hash, current_time).encode())));
888 }
889 if let Err(e) = self.db.commit(commit) {
890 log::debug!(
891 target: LOG_TARGET,
892 "Statement validation failed: database error {}, {:?}",
893 e,
894 statement
895 );
896 return SubmitResult::InternalError(Error::Db(e.to_string()))
897 }
898 } self.metrics.report(|metrics| metrics.submitted_statements.inc());
900 let network_priority = NetworkPriority::High;
901 log::trace!(target: LOG_TARGET, "Statement submitted: {:?}", HexDisplay::from(&hash));
902 SubmitResult::New(network_priority)
903 }
904
905 fn remove(&self, hash: &Hash) -> Result<()> {
907 let current_time = self.timestamp();
908 {
909 let mut index = self.index.write();
910 if index.make_expired(hash, current_time) {
911 let commit = [
912 (col::STATEMENTS, hash.to_vec(), None),
913 (col::EXPIRED, hash.to_vec(), Some((hash, current_time).encode())),
914 ];
915 if let Err(e) = self.db.commit(commit) {
916 log::debug!(
917 target: LOG_TARGET,
918 "Error removing statement: database error {}, {:?}",
919 e,
920 HexDisplay::from(hash),
921 );
922 return Err(Error::Db(e.to_string()))
923 }
924 }
925 }
926 Ok(())
927 }
928}
929
930#[cfg(test)]
931mod tests {
932 use crate::Store;
933 use sc_keystore::Keystore;
934 use sp_core::Pair;
935 use sp_statement_store::{
936 runtime_api::{InvalidStatement, ValidStatement, ValidateStatement},
937 AccountId, Channel, DecryptionKey, NetworkPriority, Proof, SignatureVerificationResult,
938 Statement, StatementSource, StatementStore, SubmitResult, Topic,
939 };
940
941 type Extrinsic = sp_runtime::OpaqueExtrinsic;
942 type Hash = sp_core::H256;
943 type Hashing = sp_runtime::traits::BlakeTwo256;
944 type BlockNumber = u64;
945 type Header = sp_runtime::generic::Header<BlockNumber, Hashing>;
946 type Block = sp_runtime::generic::Block<Header, Extrinsic>;
947
948 const CORRECT_BLOCK_HASH: [u8; 32] = [1u8; 32];
949
950 #[derive(Clone)]
951 pub(crate) struct TestClient;
952
953 pub(crate) struct RuntimeApi {
954 _inner: TestClient,
955 }
956
957 impl sp_api::ProvideRuntimeApi<Block> for TestClient {
958 type Api = RuntimeApi;
959 fn runtime_api(&self) -> sp_api::ApiRef<Self::Api> {
960 RuntimeApi { _inner: self.clone() }.into()
961 }
962 }
963
964 sp_api::mock_impl_runtime_apis! {
965 impl ValidateStatement<Block> for RuntimeApi {
966 fn validate_statement(
967 _source: StatementSource,
968 statement: Statement,
969 ) -> std::result::Result<ValidStatement, InvalidStatement> {
970 use crate::tests::account;
971 match statement.verify_signature() {
972 SignatureVerificationResult::Valid(_) => Ok(ValidStatement{max_count: 100, max_size: 1000}),
973 SignatureVerificationResult::Invalid => Err(InvalidStatement::BadProof),
974 SignatureVerificationResult::NoSignature => {
975 if let Some(Proof::OnChain { block_hash, .. }) = statement.proof() {
976 if block_hash == &CORRECT_BLOCK_HASH {
977 let (max_count, max_size) = match statement.account_id() {
978 Some(a) if a == account(1) => (1, 1000),
979 Some(a) if a == account(2) => (2, 1000),
980 Some(a) if a == account(3) => (3, 1000),
981 Some(a) if a == account(4) => (4, 1000),
982 _ => (2, 2000),
983 };
984 Ok(ValidStatement{ max_count, max_size })
985 } else {
986 Err(InvalidStatement::BadProof)
987 }
988 } else {
989 Err(InvalidStatement::BadProof)
990 }
991 }
992 }
993 }
994 }
995 }
996
997 impl sp_blockchain::HeaderBackend<Block> for TestClient {
998 fn header(&self, _hash: Hash) -> sp_blockchain::Result<Option<Header>> {
999 unimplemented!()
1000 }
1001 fn info(&self) -> sp_blockchain::Info<Block> {
1002 sp_blockchain::Info {
1003 best_hash: CORRECT_BLOCK_HASH.into(),
1004 best_number: 0,
1005 genesis_hash: Default::default(),
1006 finalized_hash: CORRECT_BLOCK_HASH.into(),
1007 finalized_number: 1,
1008 finalized_state: None,
1009 number_leaves: 0,
1010 block_gap: None,
1011 }
1012 }
1013 fn status(&self, _hash: Hash) -> sp_blockchain::Result<sp_blockchain::BlockStatus> {
1014 unimplemented!()
1015 }
1016 fn number(&self, _hash: Hash) -> sp_blockchain::Result<Option<BlockNumber>> {
1017 unimplemented!()
1018 }
1019 fn hash(&self, _number: BlockNumber) -> sp_blockchain::Result<Option<Hash>> {
1020 unimplemented!()
1021 }
1022 }
1023
1024 fn test_store() -> (Store, tempfile::TempDir) {
1025 sp_tracing::init_for_tests();
1026 let temp_dir = tempfile::Builder::new().tempdir().expect("Error creating test dir");
1027
1028 let client = std::sync::Arc::new(TestClient);
1029 let mut path: std::path::PathBuf = temp_dir.path().into();
1030 path.push("db");
1031 let keystore = std::sync::Arc::new(sc_keystore::LocalKeystore::in_memory());
1032 let store = Store::new(&path, Default::default(), client, keystore, None).unwrap();
1033 (store, temp_dir) }
1035
1036 fn signed_statement(data: u8) -> Statement {
1037 signed_statement_with_topics(data, &[], None)
1038 }
1039
1040 fn signed_statement_with_topics(
1041 data: u8,
1042 topics: &[Topic],
1043 dec_key: Option<DecryptionKey>,
1044 ) -> Statement {
1045 let mut statement = Statement::new();
1046 statement.set_plain_data(vec![data]);
1047 for i in 0..topics.len() {
1048 statement.set_topic(i, topics[i]);
1049 }
1050 if let Some(key) = dec_key {
1051 statement.set_decryption_key(key);
1052 }
1053 let kp = sp_core::ed25519::Pair::from_string("//Alice", None).unwrap();
1054 statement.sign_ed25519_private(&kp);
1055 statement
1056 }
1057
1058 fn topic(data: u64) -> Topic {
1059 let mut topic: Topic = Default::default();
1060 topic[0..8].copy_from_slice(&data.to_le_bytes());
1061 topic
1062 }
1063
1064 fn dec_key(data: u64) -> DecryptionKey {
1065 let mut dec_key: DecryptionKey = Default::default();
1066 dec_key[0..8].copy_from_slice(&data.to_le_bytes());
1067 dec_key
1068 }
1069
1070 fn account(id: u64) -> AccountId {
1071 let mut account: AccountId = Default::default();
1072 account[0..8].copy_from_slice(&id.to_le_bytes());
1073 account
1074 }
1075
1076 fn channel(id: u64) -> Channel {
1077 let mut channel: Channel = Default::default();
1078 channel[0..8].copy_from_slice(&id.to_le_bytes());
1079 channel
1080 }
1081
1082 fn statement(account_id: u64, priority: u32, c: Option<u64>, data_len: usize) -> Statement {
1083 let mut statement = Statement::new();
1084 let mut data = Vec::new();
1085 data.resize(data_len, 0);
1086 statement.set_plain_data(data);
1087 statement.set_priority(priority);
1088 if let Some(c) = c {
1089 statement.set_channel(channel(c));
1090 }
1091 statement.set_proof(Proof::OnChain {
1092 block_hash: CORRECT_BLOCK_HASH,
1093 who: account(account_id),
1094 event_index: 0,
1095 });
1096 statement
1097 }
1098
1099 #[test]
1100 fn submit_one() {
1101 let (store, _temp) = test_store();
1102 let statement0 = signed_statement(0);
1103 assert_eq!(
1104 store.submit(statement0, StatementSource::Network),
1105 SubmitResult::New(NetworkPriority::High)
1106 );
1107 let unsigned = statement(0, 1, None, 0);
1108 assert_eq!(
1109 store.submit(unsigned, StatementSource::Network),
1110 SubmitResult::New(NetworkPriority::High)
1111 );
1112 }
1113
1114 #[test]
1115 fn save_and_load_statements() {
1116 let (store, temp) = test_store();
1117 let statement0 = signed_statement(0);
1118 let statement1 = signed_statement(1);
1119 let statement2 = signed_statement(2);
1120 assert_eq!(
1121 store.submit(statement0.clone(), StatementSource::Network),
1122 SubmitResult::New(NetworkPriority::High)
1123 );
1124 assert_eq!(
1125 store.submit(statement1.clone(), StatementSource::Network),
1126 SubmitResult::New(NetworkPriority::High)
1127 );
1128 assert_eq!(
1129 store.submit(statement2.clone(), StatementSource::Network),
1130 SubmitResult::New(NetworkPriority::High)
1131 );
1132 assert_eq!(store.statements().unwrap().len(), 3);
1133 assert_eq!(store.broadcasts(&[]).unwrap().len(), 3);
1134 assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1.clone()));
1135 let keystore = store.keystore.clone();
1136 drop(store);
1137
1138 let client = std::sync::Arc::new(TestClient);
1139 let mut path: std::path::PathBuf = temp.path().into();
1140 path.push("db");
1141 let store = Store::new(&path, Default::default(), client, keystore, None).unwrap();
1142 assert_eq!(store.statements().unwrap().len(), 3);
1143 assert_eq!(store.broadcasts(&[]).unwrap().len(), 3);
1144 assert_eq!(store.statement(&statement1.hash()).unwrap(), Some(statement1));
1145 }
1146
1147 #[test]
1148 fn search_by_topic_and_key() {
1149 let (store, _temp) = test_store();
1150 let statement0 = signed_statement(0);
1151 let statement1 = signed_statement_with_topics(1, &[topic(0)], None);
1152 let statement2 = signed_statement_with_topics(2, &[topic(0), topic(1)], Some(dec_key(2)));
1153 let statement3 = signed_statement_with_topics(3, &[topic(0), topic(1), topic(2)], None);
1154 let statement4 =
1155 signed_statement_with_topics(4, &[topic(0), topic(42), topic(2), topic(3)], None);
1156 let statements = vec![statement0, statement1, statement2, statement3, statement4];
1157 for s in &statements {
1158 store.submit(s.clone(), StatementSource::Network);
1159 }
1160
1161 let assert_topics = |topics: &[u64], key: Option<u64>, expected: &[u8]| {
1162 let key = key.map(dec_key);
1163 let topics: Vec<_> = topics.iter().map(|t| topic(*t)).collect();
1164 let mut got_vals: Vec<_> = if let Some(key) = key {
1165 store.posted(&topics, key).unwrap().into_iter().map(|d| d[0]).collect()
1166 } else {
1167 store.broadcasts(&topics).unwrap().into_iter().map(|d| d[0]).collect()
1168 };
1169 got_vals.sort();
1170 assert_eq!(expected.to_vec(), got_vals);
1171 };
1172
1173 assert_topics(&[], None, &[0, 1, 3, 4]);
1174 assert_topics(&[], Some(2), &[2]);
1175 assert_topics(&[0], None, &[1, 3, 4]);
1176 assert_topics(&[1], None, &[3]);
1177 assert_topics(&[2], None, &[3, 4]);
1178 assert_topics(&[3], None, &[4]);
1179 assert_topics(&[42], None, &[4]);
1180
1181 assert_topics(&[0, 1], None, &[3]);
1182 assert_topics(&[0, 1], Some(2), &[2]);
1183 assert_topics(&[0, 1, 99], Some(2), &[]);
1184 assert_topics(&[1, 2], None, &[3]);
1185 assert_topics(&[99], None, &[]);
1186 assert_topics(&[0, 99], None, &[]);
1187 assert_topics(&[0, 1, 2, 3, 42], None, &[]);
1188 }
1189
1190 #[test]
1191 fn constraints() {
1192 let (store, _temp) = test_store();
1193
1194 store.index.write().options.max_total_size = 3000;
1195 let source = StatementSource::Network;
1196 let ok = SubmitResult::New(NetworkPriority::High);
1197 let ignored = SubmitResult::Ignored;
1198
1199 assert_eq!(store.submit(statement(1, 1, Some(1), 2000), source), ignored);
1203 assert_eq!(store.submit(statement(1, 1, Some(1), 500), source), ok);
1204 assert_eq!(store.submit(statement(1, 1, Some(1), 200), source), ignored);
1206 assert_eq!(store.submit(statement(1, 2, Some(1), 600), source), ok);
1207 assert_eq!(store.submit(statement(1, 1, Some(2), 100), source), ignored);
1210 assert_eq!(store.index.read().expired.len(), 1);
1211
1212 assert_eq!(store.submit(statement(2, 1, None, 500), source), ok);
1215 assert_eq!(store.submit(statement(2, 2, None, 100), source), ok);
1216 assert_eq!(store.submit(statement(2, 3, None, 500), source), ok);
1218 assert_eq!(store.index.read().expired.len(), 2);
1219 assert_eq!(store.submit(statement(2, 4, None, 1000), source), ok);
1221 assert_eq!(store.index.read().expired.len(), 4);
1222
1223 assert_eq!(store.submit(statement(3, 2, Some(1), 300), source), ok);
1226 assert_eq!(store.submit(statement(3, 3, Some(2), 300), source), ok);
1227 assert_eq!(store.submit(statement(3, 4, Some(3), 300), source), ok);
1228 assert_eq!(store.submit(statement(3, 5, None, 500), source), ok);
1230 assert_eq!(store.index.read().expired.len(), 6);
1231
1232 assert_eq!(store.index.read().total_size, 2400);
1233 assert_eq!(store.index.read().entries.len(), 4);
1234
1235 assert_eq!(store.submit(statement(1, 1, None, 700), source), ignored);
1237 store.index.write().options.max_total_statements = 4;
1239 assert_eq!(store.submit(statement(1, 1, None, 100), source), ignored);
1240
1241 let mut expected_statements = vec![
1242 statement(1, 2, Some(1), 600).hash(),
1243 statement(2, 4, None, 1000).hash(),
1244 statement(3, 4, Some(3), 300).hash(),
1245 statement(3, 5, None, 500).hash(),
1246 ];
1247 expected_statements.sort();
1248 let mut statements: Vec<_> =
1249 store.statements().unwrap().into_iter().map(|(hash, _)| hash).collect();
1250 statements.sort();
1251 assert_eq!(expected_statements, statements);
1252 }
1253
1254 #[test]
1255 fn expired_statements_are_purged() {
1256 use super::DEFAULT_PURGE_AFTER_SEC;
1257 let (mut store, temp) = test_store();
1258 let mut statement = statement(1, 1, Some(3), 100);
1259 store.set_time(0);
1260 statement.set_topic(0, topic(4));
1261 store.submit(statement.clone(), StatementSource::Network);
1262 assert_eq!(store.index.read().entries.len(), 1);
1263 store.remove(&statement.hash()).unwrap();
1264 assert_eq!(store.index.read().entries.len(), 0);
1265 assert_eq!(store.index.read().accounts.len(), 0);
1266 store.set_time(DEFAULT_PURGE_AFTER_SEC + 1);
1267 store.maintain();
1268 assert_eq!(store.index.read().expired.len(), 0);
1269 let keystore = store.keystore.clone();
1270 drop(store);
1271
1272 let client = std::sync::Arc::new(TestClient);
1273 let mut path: std::path::PathBuf = temp.path().into();
1274 path.push("db");
1275 let store = Store::new(&path, Default::default(), client, keystore, None).unwrap();
1276 assert_eq!(store.statements().unwrap().len(), 0);
1277 assert_eq!(store.index.read().expired.len(), 0);
1278 }
1279
1280 #[test]
1281 fn posted_clear_decrypts() {
1282 let (store, _temp) = test_store();
1283 let public = store
1284 .keystore
1285 .ed25519_generate_new(sp_core::crypto::key_types::STATEMENT, None)
1286 .unwrap();
1287 let statement1 = statement(1, 1, None, 100);
1288 let mut statement2 = statement(1, 2, None, 0);
1289 let plain = b"The most valuable secret".to_vec();
1290 statement2.encrypt(&plain, &public).unwrap();
1291 store.submit(statement1, StatementSource::Network);
1292 store.submit(statement2, StatementSource::Network);
1293 let posted_clear = store.posted_clear(&[], public.into()).unwrap();
1294 assert_eq!(posted_clear, vec![plain]);
1295 }
1296}