sp_statement_store/store_api.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18pub use crate::runtime_api::StatementSource;
19use crate::{Hash, Statement, Topic, MAX_ANY_TOPICS, MAX_TOPICS};
20use sp_core::{bounded_vec::BoundedVec, Bytes, ConstU32};
21use std::collections::HashSet;
22
23/// Identifier for a filter attached to a multi-filter subscription
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct FilterId(u64);
26
27impl FilterId {
28 /// Creates a filter id from its numeric representation
29 pub fn new(id: u64) -> Self {
30 FilterId(id)
31 }
32
33 /// Returns the numeric representation of this filter id
34 pub fn as_u64(&self) -> u64 {
35 self.0
36 }
37}
38
39/// Live statement event emitted by a multi-filter subscription
40#[derive(Debug, Clone)]
41pub struct LiveStatementEvent {
42 /// Hash of the statement
43 pub hash: Hash,
44 /// SCALE-encoded statement bytes
45 pub encoded: Vec<u8>,
46 /// Filter ids that matched the statement
47 pub matched_filter_ids: Vec<FilterId>,
48}
49
50/// Statement store error.
51#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub enum Error {
54 /// Database error.
55 #[error("Database error: {0:?}")]
56 Db(String),
57 /// Decoding error
58 #[error("Decoding error: {0:?}")]
59 Decode(String),
60 /// Error reading from storage.
61 #[error("Storage error: {0:?}")]
62 Storage(String),
63 /// Invalid configuration.
64 #[error("Invalid configuration: {0}")]
65 InvalidConfig(String),
66}
67
68/// Filter for subscribing to statements with different topics.
69#[derive(Debug, Clone)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
72pub enum TopicFilter {
73 /// Matches all topics.
74 Any,
75 /// Matches only statements including all of the given topics.
76 /// Bytes are expected to be a 32-byte topic. Up to [`MAX_TOPICS`] topics can be provided.
77 MatchAll(BoundedVec<Topic, ConstU32<{ MAX_TOPICS as u32 }>>),
78 /// Matches statements including any of the given topics.
79 /// Bytes are expected to be a 32-byte topic. Up to [`MAX_ANY_TOPICS`] topics can be provided.
80 MatchAny(BoundedVec<Topic, ConstU32<{ MAX_ANY_TOPICS as u32 }>>),
81}
82
83/// Topic filter for statement subscriptions, optimized for matching.
84#[derive(Clone, Debug)]
85pub enum OptimizedTopicFilter {
86 /// Matches all topics.
87 Any,
88 /// Matches only statements including all of the given topics.
89 /// Up to `4` topics can be provided.
90 MatchAll(HashSet<Topic>),
91 /// Matches statements including any of the given topics.
92 /// Up to `128` topics can be provided.
93 MatchAny(HashSet<Topic>),
94}
95
96impl OptimizedTopicFilter {
97 /// Check if the statement matches the filter.
98 pub fn matches(&self, statement: &Statement) -> bool {
99 match self {
100 OptimizedTopicFilter::Any => true,
101 OptimizedTopicFilter::MatchAll(topics) => {
102 topics.iter().all(|topic| statement.topics().contains(topic))
103 },
104 OptimizedTopicFilter::MatchAny(topics) => {
105 statement.topics().iter().any(|topic| topics.contains(topic))
106 },
107 }
108 }
109}
110
111// Convert TopicFilter to CheckedTopicFilter.
112impl From<TopicFilter> for OptimizedTopicFilter {
113 fn from(filter: TopicFilter) -> Self {
114 match filter {
115 TopicFilter::Any => OptimizedTopicFilter::Any,
116 TopicFilter::MatchAll(topics) => {
117 let mut parsed_topics = HashSet::with_capacity(topics.len());
118 for topic in topics {
119 parsed_topics.insert(topic);
120 }
121 OptimizedTopicFilter::MatchAll(parsed_topics)
122 },
123 TopicFilter::MatchAny(topics) => {
124 let mut parsed_topics = HashSet::with_capacity(topics.len());
125 for topic in topics {
126 parsed_topics.insert(topic);
127 }
128 OptimizedTopicFilter::MatchAny(parsed_topics)
129 },
130 }
131 }
132}
133
134/// Reason why a statement was rejected from the store.
135#[derive(Debug, Clone, Eq, PartialEq)]
136#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
137#[cfg_attr(feature = "serde", serde(tag = "reason", rename_all = "camelCase"))]
138pub enum RejectionReason {
139 /// Statement data exceeds the maximum allowed size for the account.
140 DataTooLarge {
141 /// The size of the submitted statement data.
142 submitted_size: usize,
143 /// Still available data size for the account.
144 available_size: usize,
145 },
146 /// Attempting to replace a channel message with lower or equal expiry.
147 ChannelPriorityTooLow {
148 /// The expiry of the submitted statement.
149 submitted_expiry: u64,
150 /// The minimum expiry of the existing channel message.
151 min_expiry: u64,
152 },
153 /// Account reached its statement limit and submitted expiry is too low to evict existing.
154 AccountFull {
155 /// The expiry of the submitted statement.
156 submitted_expiry: u64,
157 /// The minimum expiry of the existing statement.
158 min_expiry: u64,
159 },
160 /// The global statement store is full and cannot accept new statements.
161 StoreFull,
162 /// The size limit of the retention track the statement would be kept on is reached.
163 TrackFull,
164 /// Account has no allowance set.
165 NoAllowance,
166}
167
168impl RejectionReason {
169 /// Returns a short string label suitable for use in metrics.
170 pub fn label(&self) -> &'static str {
171 match self {
172 RejectionReason::DataTooLarge { .. } => "data_too_large",
173 RejectionReason::ChannelPriorityTooLow { .. } => "channel_priority_too_low",
174 RejectionReason::AccountFull { .. } => "account_full",
175 RejectionReason::StoreFull => "store_full",
176 RejectionReason::TrackFull => "track_full",
177 RejectionReason::NoAllowance => "no_allowance",
178 }
179 }
180}
181
182/// Reason why a statement failed validation.
183#[derive(Debug, Clone, Eq, PartialEq)]
184#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
185#[cfg_attr(feature = "serde", serde(tag = "reason", rename_all = "camelCase"))]
186pub enum InvalidReason {
187 /// Statement has no proof.
188 NoProof,
189 /// Proof validation failed.
190 BadProof,
191 /// Statement exceeds max allowed statement size.
192 EncodingTooLarge {
193 /// The size of the submitted statement encoding.
194 submitted_size: usize,
195 /// The maximum allowed size.
196 max_size: usize,
197 },
198 /// Statement has already expired. The expiry field is in the past.
199 AlreadyExpired,
200 /// Statement has no topics, so topic-based routing cannot deliver it.
201 NoTopics,
202}
203
204impl InvalidReason {
205 /// Returns a short string label suitable for use in metrics.
206 pub fn label(&self) -> &'static str {
207 match self {
208 InvalidReason::NoProof => "no_proof",
209 InvalidReason::BadProof => "bad_proof",
210 InvalidReason::EncodingTooLarge { .. } => "encoding_too_large",
211 InvalidReason::AlreadyExpired => "already_expired",
212 InvalidReason::NoTopics => "no_topics",
213 }
214 }
215}
216
217/// Statement submission outcome
218#[derive(Debug, Clone, Eq, PartialEq)]
219#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
220#[cfg_attr(feature = "serde", serde(tag = "status", rename_all = "camelCase"))]
221pub enum SubmitResult {
222 /// Statement was accepted as new.
223 New,
224 /// Statement was already known.
225 Known,
226 /// Statement was already known but has expired.
227 KnownExpired,
228 /// Statement was rejected because the store is full or priority is too low.
229 Rejected(RejectionReason),
230 /// Statement failed validation.
231 Invalid(InvalidReason),
232 /// Internal store error.
233 InternalError(Error),
234}
235
236/// Rejection reason as exposed by the spec-v2 `statement_unstable_submit` RPC.
237#[derive(Debug, Clone, Eq, PartialEq)]
238#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
239#[cfg_attr(
240 feature = "serde",
241 serde(tag = "reason", rename_all = "camelCase", rename_all_fields = "camelCase")
242)]
243pub enum SubmitRejectionReason {
244 /// Statement data exceeds the maximum allowed size for the account.
245 DataTooLarge {
246 /// The size of the submitted statement data.
247 submitted_size: usize,
248 /// Still available data size for the account.
249 available_size: usize,
250 },
251 /// Attempting to replace a channel message with lower or equal expiry.
252 ChannelPriorityTooLow {
253 /// The expiry of the submitted statement.
254 submitted_expiry: u64,
255 /// The minimum expiry of the existing channel message.
256 min_expiry: u64,
257 },
258 /// Account reached its statement limit and submitted expiry is too low to evict existing.
259 AccountFull {
260 /// The expiry of the submitted statement.
261 submitted_expiry: u64,
262 /// The minimum expiry of the existing statement.
263 min_expiry: u64,
264 },
265 /// The global statement store is full and cannot accept new statements.
266 StoreFull,
267 /// Account has no allowance set.
268 NoAllowance,
269}
270
271impl From<RejectionReason> for SubmitRejectionReason {
272 fn from(reason: RejectionReason) -> Self {
273 match reason {
274 RejectionReason::DataTooLarge { submitted_size, available_size } => {
275 SubmitRejectionReason::DataTooLarge { submitted_size, available_size }
276 },
277 RejectionReason::ChannelPriorityTooLow { submitted_expiry, min_expiry } => {
278 SubmitRejectionReason::ChannelPriorityTooLow { submitted_expiry, min_expiry }
279 },
280 RejectionReason::AccountFull { submitted_expiry, min_expiry } => {
281 SubmitRejectionReason::AccountFull { submitted_expiry, min_expiry }
282 },
283 // The RPC spec knows no tracks: a full track is a full store to the submitter.
284 RejectionReason::StoreFull | RejectionReason::TrackFull => {
285 SubmitRejectionReason::StoreFull
286 },
287 RejectionReason::NoAllowance => SubmitRejectionReason::NoAllowance,
288 }
289 }
290}
291
292/// Invalid reason as exposed by the spec-v2 `statement_unstable_submit` RPC.
293#[derive(Debug, Clone, Eq, PartialEq)]
294#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
295#[cfg_attr(
296 feature = "serde",
297 serde(tag = "reason", rename_all = "camelCase", rename_all_fields = "camelCase")
298)]
299pub enum SubmitInvalidReason {
300 /// Statement has no proof.
301 NoProof,
302 /// Proof validation failed.
303 BadProof,
304 /// Statement exceeds max allowed statement size.
305 EncodingTooLarge {
306 /// The size of the submitted statement encoding.
307 submitted_size: usize,
308 /// The maximum allowed size.
309 max_size: usize,
310 },
311 /// Statement has already expired. The expiry field is in the past.
312 AlreadyExpired,
313 /// Statement has no topics, so topic-based routing cannot deliver it.
314 NoTopics,
315}
316
317impl From<InvalidReason> for SubmitInvalidReason {
318 fn from(reason: InvalidReason) -> Self {
319 match reason {
320 InvalidReason::NoProof => SubmitInvalidReason::NoProof,
321 InvalidReason::BadProof => SubmitInvalidReason::BadProof,
322 InvalidReason::EncodingTooLarge { submitted_size, max_size } => {
323 SubmitInvalidReason::EncodingTooLarge { submitted_size, max_size }
324 },
325 InvalidReason::AlreadyExpired => SubmitInvalidReason::AlreadyExpired,
326 InvalidReason::NoTopics => SubmitInvalidReason::NoTopics,
327 }
328 }
329}
330
331/// Statement submission outcome exposed by the spec-v2 `statement_unstable_submit` RPC.
332#[derive(Debug, Clone, Eq, PartialEq)]
333#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
334#[cfg_attr(feature = "serde", serde(tag = "status", rename_all = "camelCase"))]
335pub enum SubmitOutcome {
336 /// Statement was accepted as new
337 New,
338 /// Statement was already known
339 Known,
340 /// Statement was rejected because the store is full or priority is too low
341 Rejected(SubmitRejectionReason),
342 /// Statement failed validation
343 Invalid(SubmitInvalidReason),
344}
345
346impl SubmitOutcome {
347 /// Converts a store submission result into the RPC-visible outcome
348 pub fn from_submit_result(result: SubmitResult) -> std::result::Result<Self, Error> {
349 match result {
350 SubmitResult::New => Ok(SubmitOutcome::New),
351 SubmitResult::Known => Ok(SubmitOutcome::Known),
352 // The store only returns `KnownExpired` for `Network` sources; the RPC path is `Local`.
353 SubmitResult::KnownExpired => {
354 Err(Error::Storage("unexpected KnownExpired on local submission".into()))
355 },
356 SubmitResult::Rejected(reason) => Ok(SubmitOutcome::Rejected(reason.into())),
357 SubmitResult::Invalid(reason) => Ok(SubmitOutcome::Invalid(reason.into())),
358 SubmitResult::InternalError(error) => Err(error),
359 }
360 }
361}
362
363/// An item returned by the statement subscription stream.
364#[derive(Debug, Clone, Eq, PartialEq)]
365#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
366#[cfg_attr(feature = "serde", serde(tag = "event", content = "data", rename_all = "camelCase"))]
367pub enum StatementEvent {
368 /// A batch of statements matching the subscription filter.
369 NewStatements {
370 /// A batch of statements matching the subscription filter, each entry is a SCALE-encoded
371 /// statement.
372 statements: Vec<Bytes>,
373 /// An optional count of how many more matching statements are in the store after this
374 /// batch. This guarantees to the client that it will receive at least this many more
375 /// statements in the subscription stream, but it may receive more if new statements are
376 /// added to the store that match the filter.
377 #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
378 remaining: Option<u32>,
379 },
380}
381
382/// Result type for `Error`
383pub type Result<T> = std::result::Result<T, Error>;
384
385/// Decision returned by the filter used in [`StatementStore::statements_by_hashes`].
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub enum FilterDecision {
388 /// Skip this statement, continue to next.
389 Skip,
390 /// Take this statement, continue to next.
391 Take,
392 /// Stop iteration, return collected statements.
393 Abort,
394}
395
396/// A batch of statements read from the admission journal by
397/// [`StatementStore::admitted_statements`].
398#[derive(Debug)]
399pub struct AdmittedBatch {
400 /// The taken statements, oldest admission first.
401 pub statements: Vec<(Hash, Statement)>,
402 /// Admission sequence number to resume the walk from.
403 pub cursor: u64,
404 /// Whether the walk reached the watermark; always equals `cursor >= watermark`.
405 pub done: bool,
406}
407
408/// Statement store API.
409pub trait StatementStore: Send + Sync {
410 /// Return all statements.
411 fn statements(&self) -> Result<Vec<(Hash, Statement)>>;
412
413 /// Return recent statements with their admission sequence numbers, oldest admission
414 /// first, and clear the internal index.
415 ///
416 /// This consumes and clears the recently received statements,
417 /// allowing new statements to be collected from this point forward. Every returned
418 /// statement comes with one hold, see [`Self::hold_statements`], for the caller to release.
419 fn take_recent_statements(&self) -> Result<Vec<(u64, Hash, Statement)>>;
420
421 /// Keep the statements from removal as propagated, one hold per occurrence of a hash. A
422 /// statement may leave the store once its last hold is released, so only a caller still
423 /// holding a hash can extend its holds.
424 ///
425 /// Does nothing by default, for stores that never remove propagated statements.
426 fn hold_statements(&self, _hashes: &[Hash]) {}
427
428 /// Release one hold per occurrence of a hash, ignoring hashes without holds.
429 fn release_statements(&self, _hashes: &[Hash]) {}
430
431 /// Get statement by hash.
432 fn statement(&self, hash: &Hash) -> Result<Option<Statement>>;
433
434 /// Check if statement exists in the store
435 ///
436 /// Fast index check without accessing the DB.
437 fn has_statement(&self, hash: &Hash) -> bool;
438
439 /// Fetch statements by their hashes with a filter callback.
440 ///
441 /// The callback receives (hash, encoded_bytes, decoded_statement) and returns:
442 /// - `Skip`: ignore this statement, continue to next
443 /// - `Take`: include this statement in the result, continue to next
444 /// - `Abort`: stop iteration, return collected statements so far
445 ///
446 /// Returns (statements, number_of_hashes_processed). A hash absent from the store or whose
447 /// statement fails to decode counts as processed without reaching the callback, the hash an
448 /// `Abort` stopped on does not.
449 fn statements_by_hashes(
450 &self,
451 hashes: &[Hash],
452 filter: &mut dyn FnMut(&Hash, &[u8], &Statement) -> FilterDecision,
453 ) -> Result<(Vec<(Hash, Statement)>, usize)>;
454
455 /// One past the newest assigned admission sequence number.
456 ///
457 /// Every statement currently in the store was admitted below this boundary, so it
458 /// serves as the watermark for a subsequent [`Self::admitted_statements`] walk.
459 fn admission_watermark(&self) -> Result<u64>;
460
461 /// Walk the admission journal from `cursor` (inclusive) towards `watermark`
462 /// (exclusive), collecting statements through a filter callback.
463 ///
464 /// The callback receives (hash, encoded_bytes, decoded_statement) and returns:
465 /// - `Skip`: leave this statement out of the batch, continue to next
466 /// - `Take`: include this statement in the batch, continue to next
467 /// - `Abort`: stop the walk before this statement
468 ///
469 /// Sequence numbers whose statement has left the store are passed over. The returned
470 /// cursor sits after every visited statement except an `Abort`ed one, which the next
471 /// walk revisits first.
472 ///
473 /// A call visits at most `scan_limit` journal entries, passed-over ones included, so
474 /// its cost stays bounded even when the filter takes nothing. `scan_limit` must be
475 /// positive: a walk that visits no entries cannot advance the cursor. A walk stopped
476 /// by the limit returns a partial cursor to resume from, exactly like an `Abort`.
477 fn admitted_statements(
478 &self,
479 cursor: u64,
480 watermark: u64,
481 scan_limit: usize,
482 filter: &mut dyn FnMut(&Hash, &[u8], &Statement) -> FilterDecision,
483 ) -> Result<AdmittedBatch>;
484
485 /// Return the data of all known statements which include all topics and have no `DecryptionKey`
486 /// field.
487 fn broadcasts(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>>;
488
489 /// Return the data of all known statements whose decryption key is identified as `dest` (this
490 /// will generally be the public key or a hash thereof for symmetric ciphers, or a hash of the
491 /// private key for symmetric ciphers).
492 fn posted(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>>;
493
494 /// Return the decrypted data of all known statements whose decryption key is identified as
495 /// `dest`. The key must be available to the client.
496 fn posted_clear(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>>;
497
498 /// Return all known statements which include all topics and have no `DecryptionKey`
499 /// field.
500 fn broadcasts_stmt(&self, match_all_topics: &[Topic]) -> Result<Vec<Vec<u8>>>;
501
502 /// Return all known statements whose decryption key is identified as `dest` (this
503 /// will generally be the public key or a hash thereof for symmetric ciphers, or a hash of the
504 /// private key for symmetric ciphers).
505 fn posted_stmt(&self, match_all_topics: &[Topic], dest: [u8; 32]) -> Result<Vec<Vec<u8>>>;
506
507 /// Return the statement and the decrypted data of all known statements whose decryption key is
508 /// identified as `dest`. The key must be available to the client.
509 ///
510 /// The result is for each statement: the SCALE-encoded statement concatenated to the
511 /// decrypted data.
512 fn posted_clear_stmt(&self, match_all_topics: &[Topic], dest: [u8; 32])
513 -> Result<Vec<Vec<u8>>>;
514
515 /// Submit a statement.
516 fn submit(&self, statement: Statement, source: StatementSource) -> SubmitResult;
517
518 /// Remove a statement from the store.
519 fn remove(&self, hash: &Hash) -> Result<()>;
520
521 /// Remove all statements authored by `who`.
522 fn remove_by(&self, who: [u8; 32]) -> Result<()>;
523
524 /// Topics across all live statement subscriptions, for advertising topic affinity.
525 ///
526 /// Defaults to empty for stores without a subscription manager.
527 fn subscription_topics(&self) -> HashSet<Topic> {
528 HashSet::new()
529 }
530}