Skip to main content

sp_statement_store/
lib.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
18#![cfg_attr(not(feature = "std"), no_std)]
19#![warn(missing_docs)]
20
21//! A crate which contains statement-store primitives.
22
23extern crate alloc;
24
25use alloc::vec::Vec;
26use codec::{Compact, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
27use core::ops::Deref;
28use scale_info::{build::Fields, Path, Type, TypeInfo};
29use sp_application_crypto::RuntimeAppPublic;
30#[cfg(feature = "std")]
31use sp_core::Pair;
32
33/// Statement topic.
34///
35/// A 32-byte topic identifier that serializes as a hex string (like `sp_core::Bytes`).
36#[derive(
37	Clone,
38	Copy,
39	Debug,
40	Default,
41	PartialEq,
42	Eq,
43	PartialOrd,
44	Ord,
45	Hash,
46	Encode,
47	Decode,
48	DecodeWithMemTracking,
49	MaxEncodedLen,
50	TypeInfo,
51)]
52pub struct Topic(pub [u8; 32]);
53
54#[cfg(feature = "serde")]
55impl serde::Serialize for Topic {
56	fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
57	where
58		S: serde::Serializer,
59	{
60		sp_core::bytes::serialize(&self.0, serializer)
61	}
62}
63
64#[cfg(feature = "serde")]
65impl<'de> serde::Deserialize<'de> for Topic {
66	fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
67	where
68		D: serde::Deserializer<'de>,
69	{
70		let mut arr = [0u8; 32];
71		sp_core::bytes::deserialize_check_len(
72			deserializer,
73			sp_core::bytes::ExpectedLen::Exact(&mut arr[..]),
74		)?;
75		Ok(Topic(arr))
76	}
77}
78
79impl From<[u8; 32]> for Topic {
80	fn from(inner: [u8; 32]) -> Self {
81		Topic(inner)
82	}
83}
84
85impl From<Topic> for [u8; 32] {
86	fn from(topic: Topic) -> Self {
87		topic.0
88	}
89}
90
91impl AsRef<[u8; 32]> for Topic {
92	fn as_ref(&self) -> &[u8; 32] {
93		&self.0
94	}
95}
96
97impl AsRef<[u8]> for Topic {
98	fn as_ref(&self) -> &[u8] {
99		&self.0
100	}
101}
102
103impl Deref for Topic {
104	type Target = [u8; 32];
105
106	fn deref(&self) -> &Self::Target {
107		&self.0
108	}
109}
110
111/// Decryption key identifier.
112pub type DecryptionKey = [u8; 32];
113/// Statement hash.
114pub type Hash = [u8; 32];
115/// Block hash.
116pub type BlockHash = [u8; 32];
117/// Account id
118pub type AccountId = [u8; 32];
119/// Statement channel.
120pub type Channel = [u8; 32];
121
122/// Total number of topic fields allowed in a statement and in `MatchAll` filters.
123pub const MAX_TOPICS: usize = 4;
124/// `MatchAny` allows to provide a list of topics match against. This is the maximum number of
125/// topics allowed.
126pub const MAX_ANY_TOPICS: usize = 128;
127
128/// Statement allowance limits for an account.
129#[derive(Clone, Default, PartialEq, Eq, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo)]
130pub struct StatementAllowance {
131	/// Maximum number of statements allowed
132	pub max_count: u32,
133	/// Maximum total size of statements in bytes
134	pub max_size: u32,
135}
136
137impl StatementAllowance {
138	/// Create a new statement allowance.
139	pub fn new(max_count: u32, max_size: u32) -> Self {
140		Self { max_count, max_size }
141	}
142
143	/// Saturating addition of statement allowances.
144	pub const fn saturating_add(self, rhs: StatementAllowance) -> StatementAllowance {
145		StatementAllowance {
146			max_count: self.max_count.saturating_add(rhs.max_count),
147			max_size: self.max_size.saturating_add(rhs.max_size),
148		}
149	}
150
151	/// Saturating subtraction of statement allowances.
152	pub const fn saturating_sub(self, rhs: StatementAllowance) -> StatementAllowance {
153		StatementAllowance {
154			max_count: self.max_count.saturating_sub(rhs.max_count),
155			max_size: self.max_size.saturating_sub(rhs.max_size),
156		}
157	}
158
159	/// Check if the statement allowance is depleted.
160	pub fn is_depleted(&self) -> bool {
161		self.max_count == 0 || self.max_size == 0
162	}
163}
164
165/// Storage key prefix for per-account statement allowances.
166pub const STATEMENT_ALLOWANCE_PREFIX: &[u8] = b":statement_allowance:";
167
168/// Constructs a per-account statement allowance storage key.
169///
170/// # Arguments
171/// * `account_id` - Account identifier as byte slice
172///
173/// # Returns
174/// Storage key: `":statement_allowance:" ++ account_id`
175pub fn statement_allowance_key(account_id: impl AsRef<[u8]>) -> Vec<u8> {
176	let mut key = STATEMENT_ALLOWANCE_PREFIX.to_vec();
177	key.extend_from_slice(account_id.as_ref());
178	key
179}
180
181/// Increase the statement allowance by the given amount.
182pub fn increase_allowance_by(account_id: impl AsRef<[u8]>, by: StatementAllowance) {
183	let key = statement_allowance_key(account_id);
184	let mut allowance: StatementAllowance = frame_support::storage::unhashed::get_or_default(&key);
185	allowance = allowance.saturating_add(by);
186	frame_support::storage::unhashed::put(&key, &allowance);
187}
188
189/// Decrease the statement allowance by the given amount.
190pub fn decrease_allowance_by(account_id: impl AsRef<[u8]>, by: StatementAllowance) {
191	let key = statement_allowance_key(account_id);
192	let mut allowance: StatementAllowance = frame_support::storage::unhashed::get_or_default(&key);
193	allowance = allowance.saturating_sub(by);
194	if allowance.is_depleted() {
195		frame_support::storage::unhashed::kill(&key);
196	} else {
197		frame_support::storage::unhashed::put(&key, &allowance);
198	}
199}
200
201/// Get the statement allowance for the given account.
202pub fn get_allowance(account_id: impl AsRef<[u8]>) -> StatementAllowance {
203	let key = statement_allowance_key(account_id);
204	frame_support::storage::unhashed::get_or_default(&key)
205}
206
207#[cfg(feature = "std")]
208pub use store_api::{
209	Error, FilterDecision, InvalidReason, OptimizedTopicFilter, RejectionReason, Result,
210	StatementEvent, StatementSource, StatementStore, SubmitResult, TopicFilter,
211};
212
213#[cfg(feature = "std")]
214mod ecies;
215pub mod runtime_api;
216#[cfg(feature = "std")]
217mod store_api;
218
219mod sr25519 {
220	mod app_sr25519 {
221		use sp_application_crypto::{app_crypto, key_types::STATEMENT, sr25519};
222		app_crypto!(sr25519, STATEMENT);
223	}
224	pub type Public = app_sr25519::Public;
225}
226
227/// Statement-store specific ed25519 crypto primitives.
228pub mod ed25519 {
229	mod app_ed25519 {
230		use sp_application_crypto::{app_crypto, ed25519, key_types::STATEMENT};
231		app_crypto!(ed25519, STATEMENT);
232	}
233	/// Statement-store specific ed25519 public key.
234	pub type Public = app_ed25519::Public;
235	/// Statement-store specific ed25519 key pair.
236	#[cfg(feature = "std")]
237	pub type Pair = app_ed25519::Pair;
238}
239
240mod ecdsa {
241	mod app_ecdsa {
242		use sp_application_crypto::{app_crypto, ecdsa, key_types::STATEMENT};
243		app_crypto!(ecdsa, STATEMENT);
244	}
245	pub type Public = app_ecdsa::Public;
246}
247
248/// Returns blake2-256 hash for the encoded statement.
249#[cfg(feature = "std")]
250pub fn hash_encoded(data: &[u8]) -> [u8; 32] {
251	sp_crypto_hashing::blake2_256(data)
252}
253
254/// Statement proof.
255#[derive(
256	Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo, Debug, Clone, PartialEq, Eq,
257)]
258pub enum Proof {
259	/// Sr25519 Signature.
260	Sr25519 {
261		/// Signature.
262		signature: [u8; 64],
263		/// Public key.
264		signer: [u8; 32],
265	},
266	/// Ed25519 Signature.
267	Ed25519 {
268		/// Signature.
269		signature: [u8; 64],
270		/// Public key.
271		signer: [u8; 32],
272	},
273	/// Secp256k1 Signature.
274	Secp256k1Ecdsa {
275		/// Signature.
276		signature: [u8; 65],
277		/// Public key.
278		signer: [u8; 33],
279	},
280	/// On-chain event proof.
281	OnChain {
282		/// Account identifier associated with the event.
283		who: AccountId,
284		/// Hash of block that contains the event.
285		block_hash: BlockHash,
286		/// Index of the event in the event list.
287		event_index: u64,
288	},
289}
290
291impl Proof {
292	/// Return account id for the proof creator.
293	pub fn account_id(&self) -> AccountId {
294		match self {
295			Proof::Sr25519 { signer, .. } => *signer,
296			Proof::Ed25519 { signer, .. } => *signer,
297			Proof::Secp256k1Ecdsa { signer, .. } => {
298				<sp_runtime::traits::BlakeTwo256 as sp_core::Hasher>::hash(signer).into()
299			},
300			Proof::OnChain { who, .. } => *who,
301		}
302	}
303}
304
305/// Statement attributes. Each statement is a list of 0 or more fields. Fields may only appear once
306/// and in the order declared here.
307#[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)]
308#[repr(u8)]
309pub enum Field {
310	/// Statement proof.
311	AuthenticityProof(Proof) = 0,
312	/// An identifier for the key that `Data` field may be decrypted with.
313	DecryptionKey(DecryptionKey) = 1,
314	/// Expiry of the statement. See [`Statement::expiry`] for details on the format.
315	Expiry(u64) = 2,
316	/// Account channel to use. Only one message per `(account, channel)` pair is allowed.
317	Channel(Channel) = 3,
318	/// First statement topic.
319	Topic1(Topic) = 4,
320	/// Second statement topic.
321	Topic2(Topic) = 5,
322	/// Third statement topic.
323	Topic3(Topic) = 6,
324	/// Fourth statement topic.
325	Topic4(Topic) = 7,
326	/// Additional data.
327	Data(Vec<u8>) = 8,
328}
329
330impl Field {
331	fn discriminant(&self) -> u8 {
332		// This is safe for repr(u8)
333		// see https://doc.rust-lang.org/reference/items/enumerations.html#pointer-casting
334		unsafe { *(self as *const Self as *const u8) }
335	}
336}
337
338/// Statement structure.
339#[derive(DecodeWithMemTracking, Debug, Clone, PartialEq, Eq, Default)]
340pub struct Statement {
341	/// Proof used for authorizing the statement.
342	proof: Option<Proof>,
343	/// An identifier for the key that `Data` field may be decrypted with.
344	#[deprecated(note = "Experimental feature, may be removed/changed in future releases")]
345	decryption_key: Option<DecryptionKey>,
346	/// Used for identifying a distinct communication channel, only a message per channel is
347	/// stored.
348	///
349	/// This can be used to implement message replacement, submitting a new message with a
350	/// different topic/data on the same channel and a greater expiry replaces the previous one.
351	///
352	/// If the new statement data is bigger than the old one, submitting a statement with the same
353	/// channel does not guarantee that **ONLY** the old one will be replaced, as it might not fit
354	/// in the account quota. In that case, other statements from the same account with the lowest
355	/// expiry will be removed.
356	channel: Option<Channel>,
357	/// Message expiry, used for determining which statements to keep.
358	///
359	/// The most significant 32 bits represents the expiration timestamp (in seconds since
360	/// UNIX epoch) after which the statement gets removed. These ensure that statements with a
361	/// higher expiration time have a higher priority.
362	/// The lower 32 bits represents an arbitrary sequence number used to order statements with the
363	/// same expiration time.
364	///
365	/// Higher values indicate a higher priority.
366	/// This is used in two cases:
367	/// 1) When an account exceeds its quota and some statements need to be removed. Statements
368	///    with the lowest `expiry` are removed first.
369	/// 2) When multiple statements are submitted on the same channel, the one with the highest
370	///    expiry replaces the one with the same channel.
371	expiry: u64,
372	/// Number of topics present.
373	num_topics: u8,
374	/// Topics, used for querying and filtering statements.
375	topics: [Topic; MAX_TOPICS],
376	/// Statement data.
377	data: Option<Vec<u8>>,
378}
379
380/// Note: The `TypeInfo` implementation reflects the actual encoding format (`Vec<Field>`)
381/// rather than the struct fields, since `Statement` has custom `Encode`/`Decode` implementations.
382impl TypeInfo for Statement {
383	type Identity = Self;
384
385	fn type_info() -> Type {
386		// Statement encodes as Vec<Field>, so we report the same type info
387		Type::builder()
388			.path(Path::new("Statement", module_path!()))
389			.docs(&["Statement structure"])
390			.composite(Fields::unnamed().field(|f| f.ty::<Vec<Field>>()))
391	}
392}
393
394impl Decode for Statement {
395	fn decode<I: codec::Input>(input: &mut I) -> core::result::Result<Self, codec::Error> {
396		// Encoding matches that of Vec<Field>. Basically this just means accepting that there
397		// will be a prefix of vector length.
398		let num_fields: codec::Compact<u32> = Decode::decode(input)?;
399		let mut tag = 0;
400		let mut statement = Statement::new();
401		for i in 0..num_fields.into() {
402			let field: Field = Decode::decode(input)?;
403			if i > 0 && field.discriminant() <= tag {
404				return Err("Invalid field order or duplicate fields".into());
405			}
406			tag = field.discriminant();
407			match field {
408				Field::AuthenticityProof(p) => statement.set_proof(p),
409				Field::DecryptionKey(key) => statement.set_decryption_key(key),
410				Field::Expiry(p) => statement.set_expiry(p),
411				Field::Channel(c) => statement.set_channel(c),
412				Field::Topic1(t) => statement.set_topic(0, t),
413				Field::Topic2(t) => statement.set_topic(1, t),
414				Field::Topic3(t) => statement.set_topic(2, t),
415				Field::Topic4(t) => statement.set_topic(3, t),
416				Field::Data(data) => statement.set_plain_data(data),
417			}
418		}
419		Ok(statement)
420	}
421}
422
423impl Encode for Statement {
424	fn encode(&self) -> Vec<u8> {
425		self.encoded(false)
426	}
427}
428
429#[derive(Clone, Copy, PartialEq, Eq, Debug)]
430/// Result returned by `Statement::verify_signature`
431pub enum SignatureVerificationResult {
432	/// Signature is valid and matches this account id.
433	Valid(AccountId),
434	/// Signature has failed verification.
435	Invalid,
436	/// No signature in the proof or no proof.
437	NoSignature,
438}
439
440impl Statement {
441	/// Create a new empty statement with no proof.
442	pub fn new() -> Statement {
443		Default::default()
444	}
445
446	/// Create a new statement with a proof.
447	pub fn new_with_proof(proof: Proof) -> Statement {
448		let mut statement = Self::new();
449		statement.set_proof(proof);
450		statement
451	}
452
453	/// Sign with a key that matches given public key in the keystore.
454	///
455	/// Returns `true` if signing worked (private key present etc).
456	///
457	/// NOTE: This can only be called from the runtime.
458	pub fn sign_sr25519_public(&mut self, key: &sr25519::Public) -> bool {
459		let to_sign = self.signature_material();
460		if let Some(signature) = key.sign(&to_sign) {
461			let proof = Proof::Sr25519 {
462				signature: signature.into_inner().into(),
463				signer: key.clone().into_inner().into(),
464			};
465			self.set_proof(proof);
466			true
467		} else {
468			false
469		}
470	}
471
472	/// Returns slice of all topics set in the statement.
473	pub fn topics(&self) -> &[Topic] {
474		&self.topics[..self.num_topics as usize]
475	}
476
477	/// Sign with a given private key and add the signature proof field.
478	#[cfg(feature = "std")]
479	pub fn sign_sr25519_private(&mut self, key: &sp_core::sr25519::Pair) {
480		let to_sign = self.signature_material();
481		let proof =
482			Proof::Sr25519 { signature: key.sign(&to_sign).into(), signer: key.public().into() };
483		self.set_proof(proof);
484	}
485
486	/// Sign with a key that matches given public key in the keystore.
487	///
488	/// Returns `true` if signing worked (private key present etc).
489	///
490	/// NOTE: This can only be called from the runtime.
491	pub fn sign_ed25519_public(&mut self, key: &ed25519::Public) -> bool {
492		let to_sign = self.signature_material();
493		if let Some(signature) = key.sign(&to_sign) {
494			let proof = Proof::Ed25519 {
495				signature: signature.into_inner().into(),
496				signer: key.clone().into_inner().into(),
497			};
498			self.set_proof(proof);
499			true
500		} else {
501			false
502		}
503	}
504
505	/// Sign with a given private key and add the signature proof field.
506	#[cfg(feature = "std")]
507	pub fn sign_ed25519_private(&mut self, key: &sp_core::ed25519::Pair) {
508		let to_sign = self.signature_material();
509		let proof =
510			Proof::Ed25519 { signature: key.sign(&to_sign).into(), signer: key.public().into() };
511		self.set_proof(proof);
512	}
513
514	/// Sign with a key that matches given public key in the keystore.
515	///
516	/// Returns `true` if signing worked (private key present etc).
517	///
518	/// NOTE: This can only be called from the runtime.
519	///
520	/// Returns `true` if signing worked (private key present etc).
521	///
522	/// NOTE: This can only be called from the runtime.
523	pub fn sign_ecdsa_public(&mut self, key: &ecdsa::Public) -> bool {
524		let to_sign = self.signature_material();
525		if let Some(signature) = key.sign(&to_sign) {
526			let proof = Proof::Secp256k1Ecdsa {
527				signature: signature.into_inner().into(),
528				signer: key.clone().into_inner().0,
529			};
530			self.set_proof(proof);
531			true
532		} else {
533			false
534		}
535	}
536
537	/// Sign with a given private key and add the signature proof field.
538	#[cfg(feature = "std")]
539	pub fn sign_ecdsa_private(&mut self, key: &sp_core::ecdsa::Pair) {
540		let to_sign = self.signature_material();
541		let proof =
542			Proof::Secp256k1Ecdsa { signature: key.sign(&to_sign).into(), signer: key.public().0 };
543		self.set_proof(proof);
544	}
545
546	/// Check proof signature, if any.
547	pub fn verify_signature(&self) -> SignatureVerificationResult {
548		use sp_runtime::traits::Verify;
549
550		match self.proof() {
551			Some(Proof::OnChain { .. }) | None => SignatureVerificationResult::NoSignature,
552			Some(Proof::Sr25519 { signature, signer }) => {
553				let to_sign = self.signature_material();
554				let signature = sp_core::sr25519::Signature::from(*signature);
555				let public = sp_core::sr25519::Public::from(*signer);
556				if signature.verify(to_sign.as_slice(), &public) {
557					SignatureVerificationResult::Valid(*signer)
558				} else {
559					SignatureVerificationResult::Invalid
560				}
561			},
562			Some(Proof::Ed25519 { signature, signer }) => {
563				let to_sign = self.signature_material();
564				let signature = sp_core::ed25519::Signature::from(*signature);
565				let public = sp_core::ed25519::Public::from(*signer);
566				if signature.verify(to_sign.as_slice(), &public) {
567					SignatureVerificationResult::Valid(*signer)
568				} else {
569					SignatureVerificationResult::Invalid
570				}
571			},
572			Some(Proof::Secp256k1Ecdsa { signature, signer }) => {
573				let to_sign = self.signature_material();
574				let signature = sp_core::ecdsa::Signature::from(*signature);
575				let public = sp_core::ecdsa::Public::from(*signer);
576				if signature.verify(to_sign.as_slice(), &public) {
577					let sender_hash =
578						<sp_runtime::traits::BlakeTwo256 as sp_core::Hasher>::hash(signer);
579					SignatureVerificationResult::Valid(sender_hash.into())
580				} else {
581					SignatureVerificationResult::Invalid
582				}
583			},
584		}
585	}
586
587	/// Calculate statement hash.
588	#[cfg(feature = "std")]
589	pub fn hash(&self) -> [u8; 32] {
590		self.using_encoded(hash_encoded)
591	}
592
593	/// Returns a topic by topic index.
594	pub fn topic(&self, index: usize) -> Option<Topic> {
595		if index < self.num_topics as usize {
596			Some(self.topics[index])
597		} else {
598			None
599		}
600	}
601
602	/// Returns decryption key if any.
603	#[allow(deprecated)]
604	pub fn decryption_key(&self) -> Option<DecryptionKey> {
605		self.decryption_key
606	}
607
608	/// Convert to internal data.
609	pub fn into_data(self) -> Option<Vec<u8>> {
610		self.data
611	}
612
613	/// Get a reference to the statement proof, if any.
614	pub fn proof(&self) -> Option<&Proof> {
615		self.proof.as_ref()
616	}
617
618	/// Get proof account id, if any
619	pub fn account_id(&self) -> Option<AccountId> {
620		self.proof.as_ref().map(Proof::account_id)
621	}
622
623	/// Get plain data.
624	pub fn data(&self) -> Option<&Vec<u8>> {
625		self.data.as_ref()
626	}
627
628	/// Get plain data len.
629	pub fn data_len(&self) -> usize {
630		self.data().map_or(0, Vec::len)
631	}
632
633	/// Get channel, if any.
634	pub fn channel(&self) -> Option<Channel> {
635		self.channel
636	}
637
638	/// Get expiry.
639	pub fn expiry(&self) -> u64 {
640		self.expiry
641	}
642
643	/// Get expiration timestamp in seconds.
644	///
645	/// The expiration timestamp in seconds is stored in the most significant 32 bits of the expiry
646	/// field.
647	pub fn get_expiration_timestamp_secs(&self) -> u32 {
648		(self.expiry >> 32) as u32
649	}
650
651	/// Return encoded fields that can be signed to construct or verify a proof
652	fn signature_material(&self) -> Vec<u8> {
653		self.encoded(true)
654	}
655
656	/// Remove the proof of this statement.
657	pub fn remove_proof(&mut self) {
658		self.proof = None;
659	}
660
661	/// Set statement proof. Any existing proof is overwritten.
662	pub fn set_proof(&mut self, proof: Proof) {
663		self.proof = Some(proof)
664	}
665
666	/// Set statement expiry.
667	pub fn set_expiry(&mut self, expiry: u64) {
668		self.expiry = expiry;
669	}
670
671	/// Set statement expiry from its parts. See [`Statement::expiry`] for details on the format.
672	pub fn set_expiry_from_parts(&mut self, expiration_timestamp_secs: u32, sequence_number: u32) {
673		self.expiry = (expiration_timestamp_secs as u64) << 32 | sequence_number as u64;
674	}
675
676	/// Set statement channel.
677	pub fn set_channel(&mut self, channel: Channel) {
678		self.channel = Some(channel)
679	}
680
681	/// Set topic by index. Does noting if index is over `MAX_TOPICS`.
682	pub fn set_topic(&mut self, index: usize, topic: Topic) {
683		if index < MAX_TOPICS {
684			self.topics[index] = topic;
685			self.num_topics = self.num_topics.max(index as u8 + 1);
686		}
687	}
688
689	/// Set decryption key.
690	#[allow(deprecated)]
691	pub fn set_decryption_key(&mut self, key: DecryptionKey) {
692		self.decryption_key = Some(key);
693	}
694
695	/// Set unencrypted statement data.
696	pub fn set_plain_data(&mut self, data: Vec<u8>) {
697		self.data = Some(data)
698	}
699
700	/// Estimate the encoded size for preallocation.
701	///
702	/// Returns a close approximation of the SCALE-encoded size without actually performing the
703	/// encoding. Uses max_encoded_len() for type sizes:
704	/// - Compact length prefix: max_encoded_len() bytes
705	/// - Proof field: 1 (tag) + max_encoded_len()
706	/// - DecryptionKey: 1 (tag) + max_encoded_len()
707	/// - Expiry: 1 (tag) + max_encoded_len()
708	/// - Channel: 1 (tag) + max_encoded_len()
709	/// - Each topic: 1 (tag) + max_encoded_len()
710	/// - Data: 1 (tag) + max_encoded_len() (compact len) + data.len()
711	#[allow(deprecated)]
712	fn estimated_encoded_size(&self, for_signing: bool) -> usize {
713		let proof_size =
714			if !for_signing && self.proof.is_some() { 1 + Proof::max_encoded_len() } else { 0 };
715		let decryption_key_size =
716			if self.decryption_key.is_some() { 1 + DecryptionKey::max_encoded_len() } else { 0 };
717		let expiry_size = 1 + u64::max_encoded_len();
718		let channel_size = if self.channel.is_some() { 1 + Channel::max_encoded_len() } else { 0 };
719		let topics_size = self.num_topics as usize * (1 + Topic::max_encoded_len());
720		let data_size = self
721			.data
722			.as_ref()
723			.map_or(0, |d| 1 + Compact::<u32>::max_encoded_len() + d.len());
724		let compact_prefix_size = if !for_signing { Compact::<u32>::max_encoded_len() } else { 0 };
725
726		compact_prefix_size +
727			proof_size +
728			decryption_key_size +
729			expiry_size +
730			channel_size +
731			topics_size +
732			data_size
733	}
734
735	#[allow(deprecated)]
736	fn encoded(&self, for_signing: bool) -> Vec<u8> {
737		// Encoding matches that of Vec<Field>. Basically this just means accepting that there
738		// will be a prefix of vector length.
739		// Expiry field is always present.
740		let num_fields = if !for_signing && self.proof.is_some() { 2 } else { 1 } +
741			if self.decryption_key.is_some() { 1 } else { 0 } +
742			if self.channel.is_some() { 1 } else { 0 } +
743			if self.data.is_some() { 1 } else { 0 } +
744			self.num_topics as u32;
745
746		let mut output = Vec::with_capacity(self.estimated_encoded_size(for_signing));
747		// When encoding signature payload, the length prefix is omitted.
748		// This is so that the signature for encoded statement can potentially be derived without
749		// needing to re-encode the statement.
750		if !for_signing {
751			let compact_len = codec::Compact::<u32>(num_fields);
752			compact_len.encode_to(&mut output);
753
754			if let Some(proof) = &self.proof {
755				0u8.encode_to(&mut output);
756				proof.encode_to(&mut output);
757			}
758		}
759		if let Some(decryption_key) = &self.decryption_key {
760			1u8.encode_to(&mut output);
761			decryption_key.encode_to(&mut output);
762		}
763
764		2u8.encode_to(&mut output);
765		self.expiry().encode_to(&mut output);
766
767		if let Some(channel) = &self.channel {
768			3u8.encode_to(&mut output);
769			channel.encode_to(&mut output);
770		}
771		for t in 0..self.num_topics {
772			(4u8 + t).encode_to(&mut output);
773			self.topics[t as usize].encode_to(&mut output);
774		}
775		if let Some(data) = &self.data {
776			8u8.encode_to(&mut output);
777			data.encode_to(&mut output);
778		}
779		output
780	}
781
782	/// Encrypt give data with given key and store both in the statements.
783	#[allow(deprecated)]
784	#[cfg(feature = "std")]
785	pub fn encrypt(
786		&mut self,
787		data: &[u8],
788		key: &sp_core::ed25519::Public,
789	) -> core::result::Result<(), ecies::Error> {
790		let encrypted = ecies::encrypt_ed25519(key, data)?;
791		self.data = Some(encrypted);
792		self.decryption_key = Some((*key).into());
793		Ok(())
794	}
795
796	/// Decrypt data (if any) with the given private key.
797	#[cfg(feature = "std")]
798	pub fn decrypt_private(
799		&self,
800		key: &sp_core::ed25519::Pair,
801	) -> core::result::Result<Option<Vec<u8>>, ecies::Error> {
802		self.data.as_ref().map(|d| ecies::decrypt_ed25519(key, d)).transpose()
803	}
804}
805
806#[cfg(test)]
807mod test {
808	use crate::{
809		hash_encoded, Field, Proof, SignatureVerificationResult, Statement, Topic, MAX_TOPICS,
810	};
811	use codec::{Decode, Encode};
812	use scale_info::{MetaType, TypeInfo};
813	use sp_application_crypto::Pair;
814	use sp_core::sr25519;
815
816	#[test]
817	fn statement_encoding_matches_vec() {
818		let mut statement = Statement::new();
819		assert!(statement.proof().is_none());
820		let proof = Proof::OnChain { who: [42u8; 32], block_hash: [24u8; 32], event_index: 66 };
821
822		let decryption_key = [0xde; 32];
823		let topic1: Topic = [0x01; 32].into();
824		let topic2: Topic = [0x02; 32].into();
825		let data = vec![55, 99];
826		let expiry = 999;
827		let channel = [0xcc; 32];
828
829		statement.set_proof(proof.clone());
830		statement.set_decryption_key(decryption_key);
831		statement.set_expiry(expiry);
832		statement.set_channel(channel);
833		statement.set_topic(0, topic1);
834		statement.set_topic(1, topic2);
835		statement.set_plain_data(data.clone());
836
837		statement.set_topic(5, [0x55; 32].into());
838		assert_eq!(statement.topic(5), None);
839
840		let fields = vec![
841			Field::AuthenticityProof(proof.clone()),
842			Field::DecryptionKey(decryption_key),
843			Field::Expiry(expiry),
844			Field::Channel(channel),
845			Field::Topic1(topic1),
846			Field::Topic2(topic2),
847			Field::Data(data.clone()),
848		];
849
850		let encoded = statement.encode();
851		assert_eq!(statement.hash(), hash_encoded(&encoded));
852		assert_eq!(encoded, fields.encode());
853
854		let decoded = Statement::decode(&mut encoded.as_slice()).unwrap();
855		assert_eq!(decoded, statement);
856	}
857
858	#[test]
859	fn decode_checks_fields() {
860		let topic1: Topic = [0x01; 32].into();
861		let topic2: Topic = [0x02; 32].into();
862		let priority = 999;
863
864		let dup_topic1 = vec![
865			Field::Expiry(priority),
866			Field::Topic1(topic1),
867			Field::Topic1(topic1),
868			Field::Topic2(topic2),
869		]
870		.encode();
871		assert!(Statement::decode(&mut dup_topic1.as_slice()).is_err());
872
873		let topic1_before_expiry =
874			vec![Field::Topic1(topic1), Field::Expiry(priority), Field::Topic2(topic2)].encode();
875		assert!(Statement::decode(&mut topic1_before_expiry.as_slice()).is_err());
876
877		let dup_expiry = vec![Field::Expiry(1), Field::Expiry(2)].encode();
878		assert!(Statement::decode(&mut dup_expiry.as_slice()).is_err());
879
880		let dup_data = vec![Field::Data(vec![1]), Field::Data(vec![2])].encode();
881		assert!(Statement::decode(&mut dup_data.as_slice()).is_err());
882
883		let data_before_expiry = vec![Field::Data(vec![1]), Field::Expiry(42)].encode();
884		assert!(Statement::decode(&mut data_before_expiry.as_slice()).is_err());
885
886		let channel_before_expiry = vec![Field::Channel([0; 32]), Field::Expiry(1)].encode();
887		assert!(Statement::decode(&mut channel_before_expiry.as_slice()).is_err());
888
889		let topic2_before_topic1 =
890			vec![Field::Expiry(1), Field::Topic2(topic1), Field::Topic1(topic2)].encode();
891		assert!(Statement::decode(&mut topic2_before_topic1.as_slice()).is_err());
892	}
893
894	#[test]
895	fn decode_rejects_malformed_bytes() {
896		assert!(Statement::decode(&mut &[][..]).is_err());
897
898		// Take a valid encoded statement and corrupt it in different ways
899		let valid = vec![Field::Expiry(42)].encode();
900		let decoded = Statement::decode(&mut valid.as_slice()).unwrap();
901		assert_eq!(decoded.expiry(), 42);
902
903		// Truncate to just the length prefix
904		assert!(Statement::decode(&mut &valid[..1][..]).is_err());
905
906		// Replace field discriminant with invalid value (Field only has 0..=8)
907		let mut invalid_discriminant = valid.clone();
908		invalid_discriminant[1] = 9;
909		assert!(Statement::decode(&mut invalid_discriminant.as_slice()).is_err());
910
911		invalid_discriminant[1] = 255;
912		assert!(Statement::decode(&mut invalid_discriminant.as_slice()).is_err());
913
914		// Truncate the Expiry payload (need 8 bytes for u64, provide fewer)
915		assert!(Statement::decode(&mut &valid[..5][..]).is_err());
916
917		// Encode a statement with Proof, then corrupt the Proof variant
918		let with_proof = vec![
919			Field::AuthenticityProof(Proof::OnChain {
920				who: [0u8; 32],
921				block_hash: [0u8; 32],
922				event_index: 0,
923			}),
924			Field::Expiry(42),
925		]
926		.encode();
927		assert!(Statement::decode(&mut with_proof.as_slice()).is_ok());
928
929		let mut invalid_proof_variant = with_proof.clone();
930		invalid_proof_variant[2] = 99;
931		assert!(Statement::decode(&mut invalid_proof_variant.as_slice()).is_err());
932
933		// Truncate the Proof payload
934		assert!(Statement::decode(&mut &with_proof[..6][..]).is_err());
935
936		// Claim more fields than actually present
937		let mut inflated_count = valid.clone();
938		inflated_count[0] = 5 << 2; // change field count from 1 to 5
939		assert!(Statement::decode(&mut inflated_count.as_slice()).is_err());
940	}
941
942	#[test]
943	fn sign_and_verify() {
944		let mut statement = Statement::new();
945		statement.set_plain_data(vec![42]);
946
947		let sr25519_kp = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap();
948		let ed25519_kp = sp_core::ed25519::Pair::from_string("//Alice", None).unwrap();
949		let secp256k1_kp = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap();
950
951		statement.sign_sr25519_private(&sr25519_kp);
952		assert_eq!(
953			statement.verify_signature(),
954			SignatureVerificationResult::Valid(sr25519_kp.public().0)
955		);
956
957		statement.sign_ed25519_private(&ed25519_kp);
958		assert_eq!(
959			statement.verify_signature(),
960			SignatureVerificationResult::Valid(ed25519_kp.public().0)
961		);
962
963		statement.sign_ecdsa_private(&secp256k1_kp);
964		assert_eq!(
965			statement.verify_signature(),
966			SignatureVerificationResult::Valid(sp_crypto_hashing::blake2_256(
967				&secp256k1_kp.public().0
968			))
969		);
970
971		// set an invalid Sr25519 signature
972		statement.set_proof(Proof::Sr25519 { signature: [0u8; 64], signer: [0u8; 32] });
973		assert_eq!(statement.verify_signature(), SignatureVerificationResult::Invalid);
974
975		// set an invalid Ed25519 signature
976		statement.set_proof(Proof::Ed25519 { signature: [0xAB; 64], signer: [0xCD; 32] });
977		assert_eq!(statement.verify_signature(), SignatureVerificationResult::Invalid);
978
979		// set an invalid Secp256k1Ecdsa signature
980		statement.set_proof(Proof::Secp256k1Ecdsa { signature: [0u8; 65], signer: [0u8; 33] });
981		assert_eq!(statement.verify_signature(), SignatureVerificationResult::Invalid);
982
983		statement.remove_proof();
984		assert_eq!(statement.verify_signature(), SignatureVerificationResult::NoSignature);
985	}
986
987	#[test]
988	fn encrypt_decrypt() {
989		let mut statement = Statement::new();
990		let (pair, _) = sp_core::ed25519::Pair::generate();
991		let plain = b"test data".to_vec();
992
993		// let sr25519_kp = sp_core::sr25519::Pair::from_string("//Alice", None).unwrap();
994		statement.encrypt(&plain, &pair.public()).unwrap();
995		assert_ne!(plain.as_slice(), statement.data().unwrap().as_slice());
996
997		let decrypted = statement.decrypt_private(&pair).unwrap();
998		assert_eq!(decrypted, Some(plain));
999	}
1000
1001	#[test]
1002	fn check_matches() {
1003		let mut statement = Statement::new();
1004		let topic1: Topic = [0x01; 32].into();
1005		let topic2: Topic = [0x02; 32].into();
1006		let topic3: Topic = [0x03; 32].into();
1007
1008		statement.set_topic(0, topic1);
1009		statement.set_topic(1, topic2);
1010
1011		let filter_any = crate::OptimizedTopicFilter::Any;
1012		assert!(filter_any.matches(&statement));
1013
1014		let filter_all =
1015			crate::OptimizedTopicFilter::MatchAll([topic1, topic2].iter().cloned().collect());
1016		assert!(filter_all.matches(&statement));
1017
1018		let filter_all_fail =
1019			crate::OptimizedTopicFilter::MatchAll([topic1, topic3].iter().cloned().collect());
1020		assert!(!filter_all_fail.matches(&statement));
1021
1022		let filter_any_match =
1023			crate::OptimizedTopicFilter::MatchAny([topic2, topic3].iter().cloned().collect());
1024		assert!(filter_any_match.matches(&statement));
1025
1026		let filter_any_fail =
1027			crate::OptimizedTopicFilter::MatchAny([topic3].iter().cloned().collect());
1028		assert!(!filter_any_fail.matches(&statement));
1029	}
1030
1031	#[test]
1032	fn statement_type_info_matches_encoding() {
1033		// Statement has custom Encode/Decode that encodes as Vec<Field>.
1034		// Verify that TypeInfo reflects this by containing a reference to Vec<Field>.
1035		let statement_type = Statement::type_info();
1036		let vec_field_meta = MetaType::new::<Vec<Field>>();
1037
1038		// The Statement type should be a composite with one unnamed field of type Vec<Field>
1039		match statement_type.type_def {
1040			scale_info::TypeDef::Composite(composite) => {
1041				assert_eq!(composite.fields.len(), 1, "Statement should have exactly one field");
1042				let field = &composite.fields[0];
1043				assert!(field.name.is_none(), "Field should be unnamed (newtype pattern)");
1044				assert_eq!(field.ty, vec_field_meta, "Statement's inner type should be Vec<Field>");
1045			},
1046			_ => panic!("Statement TypeInfo should be a Composite"),
1047		}
1048	}
1049
1050	#[test]
1051	fn measure_hash_30_000_statements() {
1052		use std::time::Instant;
1053		const NUM_STATEMENTS: usize = 30_000;
1054		let (keyring, _) = sr25519::Pair::generate();
1055
1056		// Create 2000 statements with varying data
1057		let statements: Vec<Statement> = (0..NUM_STATEMENTS)
1058			.map(|i| {
1059				let mut statement = Statement::new();
1060
1061				statement.set_expiry(i as u64);
1062				statement.set_topic(0, [(i % 256) as u8; 32].into());
1063				statement.set_plain_data(vec![i as u8; 512]);
1064				statement.sign_sr25519_private(&keyring);
1065
1066				statement.sign_sr25519_private(&keyring);
1067				statement
1068			})
1069			.collect();
1070		// Measure time to hash all statements
1071		let start = Instant::now();
1072		let hashes: Vec<[u8; 32]> = statements.iter().map(|s| s.hash()).collect();
1073		let elapsed = start.elapsed();
1074		println!("Time to hash {} statements: {:?}", NUM_STATEMENTS, elapsed);
1075		println!("Average time per statement: {:?}", elapsed / NUM_STATEMENTS as u32);
1076		// Verify hashes are unique
1077		let unique_hashes: std::collections::HashSet<_> = hashes.iter().collect();
1078		assert_eq!(unique_hashes.len(), NUM_STATEMENTS);
1079	}
1080
1081	#[test]
1082	fn estimated_encoded_size_is_sufficient() {
1083		// Allow some overhead due to using max_encoded_len() approximations.
1084		const MAX_ACCEPTED_OVERHEAD: usize = 33;
1085
1086		let proof = Proof::OnChain { who: [42u8; 32], block_hash: [24u8; 32], event_index: 66 };
1087		let decryption_key = [0xde; 32];
1088		let data = vec![55; 1000];
1089		let expiry = 999;
1090		let channel = [0xcc; 32];
1091
1092		// Test with all fields populated
1093		let mut statement = Statement::new();
1094		statement.set_proof(proof);
1095		statement.set_decryption_key(decryption_key);
1096		statement.set_expiry(expiry);
1097		statement.set_channel(channel);
1098		for i in 0..MAX_TOPICS {
1099			statement.set_topic(i, [i as u8; 32].into());
1100		}
1101		statement.set_plain_data(data);
1102
1103		let encoded = statement.encode();
1104		let estimated = statement.estimated_encoded_size(false);
1105		assert!(
1106			estimated >= encoded.len(),
1107			"estimated_encoded_size ({}) should be >= actual encoded length ({})",
1108			estimated,
1109			encoded.len()
1110		);
1111		let overhead = estimated - encoded.len();
1112		assert!(
1113			overhead <= MAX_ACCEPTED_OVERHEAD,
1114			"estimated overhead ({}) should be small, estimated: {}, actual: {}",
1115			overhead,
1116			estimated,
1117			encoded.len()
1118		);
1119
1120		// Test for_signing = true (no proof, no compact prefix)
1121		let signing_payload = statement.encoded(true);
1122		let signing_estimated = statement.estimated_encoded_size(true);
1123		assert!(
1124			signing_estimated >= signing_payload.len(),
1125			"estimated_encoded_size for signing ({}) should be >= actual signing payload length ({})",
1126			signing_estimated,
1127			signing_payload.len()
1128		);
1129		let signing_overhead = signing_estimated - signing_payload.len();
1130		assert!(
1131			signing_overhead <= MAX_ACCEPTED_OVERHEAD,
1132			"signing overhead ({}) should be small, estimated: {}, actual: {}",
1133			signing_overhead,
1134			signing_estimated,
1135			signing_payload.len()
1136		);
1137
1138		// Test with minimal statement (empty)
1139		let empty_statement = Statement::new();
1140		let empty_encoded = empty_statement.encode();
1141		let empty_estimated = empty_statement.estimated_encoded_size(false);
1142		assert!(
1143			empty_estimated >= empty_encoded.len(),
1144			"estimated_encoded_size for empty ({}) should be >= actual encoded length ({})",
1145			empty_estimated,
1146			empty_encoded.len()
1147		);
1148		let empty_overhead = empty_estimated - empty_encoded.len();
1149		assert!(
1150			empty_overhead <= MAX_ACCEPTED_OVERHEAD,
1151			"empty overhead ({}) should be minimal, estimated: {}, actual: {}",
1152			empty_overhead,
1153			empty_estimated,
1154			empty_encoded.len()
1155		);
1156	}
1157}