bp_idn/types.rs
1/*
2 * Copyright 2025 by Ideal Labs, LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Types of IDN runtime
18use ark_serialize::CanonicalSerialize;
19use codec::{Decode, DecodeWithMemTracking, Encode};
20use frame_support::parameter_types;
21use pallet_idn_manager::{
22 primitives::{
23 CreateSubParams as MngCreateSubParams, Quote as MngQuote, QuoteRequest as MngQuoteRequest,
24 QuoteSubParams as MngQuoteSubParams, SubInfoRequest as MngSubInfoRequest,
25 SubInfoResponse as MngSubInfoResponse, SubscriptionMetadata,
26 },
27 Subscription as MngSubscription, SubscriptionDetails as MngSubscriptionDetails,
28 UpdateSubParams as MngUpdateSubParams,
29};
30use scale_info::TypeInfo;
31use sha2::{Digest, Sha256};
32use sp_core::crypto::Ss58Codec;
33use sp_idn_crypto::prelude::*;
34use sp_idn_traits::pulse::Pulse as TPulse;
35use sp_runtime::{
36 traits::{IdentifyAccount, Verify},
37 MultiSignature, Vec,
38};
39
40pub use pallet_idn_manager::{
41 primitives::{OriginKind, RequestReference, SubscriptionCallData},
42 SubscriptionState,
43};
44pub use sp_consensus_randomness_beacon::types::*;
45
46pub mod xcm {
47 pub use pallet_idn_manager::primitives::{Junction, Junctions, Location};
48}
49
50/// The runtime pulse represents a verifiable pulse constructed from the aggregation
51/// of one or more valid drand pulses. That is, this struct represents the format
52/// in which subscribers recieve, consume, and verify on-chain randomness
53/// More specifically, it represents an aggregation of pulses and associated messages
54/// output from Drand's Quicknet
55///
56/// The aggregated signature is the sum of the aggregated signatures output from
57/// a randomness beacon for monotonically increasing rounds `[start, ..., end]`.
58/// Explicitly, for valid runtime pulses:
59/// ```latex
60/// $sig = \sum_{i \in [n]} \sum_{j \in [m]} sk_i * H(r_j)$
61/// ```
62/// where `$sk_i$` is the secret key of the `$i^ th$` worker and `$r_j$` is the `$j^{th}$`
63#[derive(Encode, Decode, Debug, Clone, TypeInfo, PartialEq, DecodeWithMemTracking)]
64pub struct RuntimePulse {
65 /// The aggregated signature
66 signature: OpaqueSignature,
67 /// The first round from which round numbers begin
68 start: RoundNumber,
69 /// The round when round numbers cease
70 end: RoundNumber,
71}
72
73impl Default for RuntimePulse {
74 fn default() -> Self {
75 Self { signature: [0; 48], start: 0, end: 0 }
76 }
77}
78
79impl RuntimePulse {
80 /// Construct a new RuntimePulse
81 pub fn new(signature: OpaqueSignature, start: RoundNumber, end: RoundNumber) -> Self {
82 Self { signature, start, end }
83 }
84}
85
86impl TPulse for RuntimePulse {
87 type Rand = Randomness;
88 type RoundNumber = RoundNumber;
89 type Sig = OpaqueSignature;
90 type Pubkey = OpaquePublicKey;
91
92 fn rand(&self) -> Self::Rand {
93 let mut hasher = Sha256::default();
94 hasher.update(self.signature);
95 hasher.finalize().into()
96 }
97
98 fn message(&self) -> Self::Sig {
99 let msg = (self.start..self.end + 1)
100 .map(|r| compute_round_on_g1(r).unwrap_or(zero_on_g1()))
101 .fold(zero_on_g1(), |amsg, val| (amsg + val).into());
102
103 let mut bytes = Vec::new();
104 msg.serialize_compressed(&mut bytes)
105 .expect("The message should be well formed.");
106
107 bytes.try_into().unwrap_or([0u8; 48])
108 }
109
110 fn start(&self) -> Self::RoundNumber {
111 self.start
112 }
113
114 fn end(&self) -> Self::RoundNumber {
115 self.end
116 }
117
118 fn sig(&self) -> Self::Sig {
119 self.signature
120 }
121
122 fn authenticate(&self, pubkey: Self::Pubkey) -> bool {
123 QuicknetVerifier::verify(
124 pubkey.as_ref().to_vec(),
125 self.sig().as_ref().to_vec(),
126 self.message().as_ref().to_vec(),
127 )
128 .is_ok()
129 }
130}
131
132// TODO: unhardcode these values https://github.com/ideal-lab5/idn-sdk/issues/379
133// Primitive types
134parameter_types! {
135 /// The IDN Treasury Account for fee collection. Fees collected for subscriptions, transaction fees and dusted balances are sent to this account.
136 /// This account should be funded with at least the existential deposit of the native currency, to be able to collect fees lower than the existential deposit.
137 pub TreasuryAccount: AccountId =
138 AccountId::from_ss58check("1LX9m9Ee8u653hU1sxvvRNpV1ZjYExa7K8r9zjDws9GDLvp")
139 .expect("Invalid Treasury Account");
140 /// The Subscription Deposit Multiplier, used for calculating the subscription fee
141 pub const SDMultiplier: u64 = 100;
142 /// Maximum number of subscriptions allowed
143 ///
144 /// This and [`MaxTerminatableSubs`] should be set to a number that keeps the estimated
145 /// `dispatch_pulse` Proof size in combinations with the `on_finalize` Proof size under
146 /// the relay chain's [`MAX_POV_SIZE`](https://github.com/paritytech/polkadot-sdk/blob/da8c374871cc97807935230e7c398876d5adce62/polkadot/primitives/src/v8/mod.rs#L441)
147 // Given:
148 // - `MAX_POV_SIZE` = 10,485,760
149 // - `on_finalize`'s POV = 689,013 (for `MaxTerminatableSubs` = 200)
150 // - Estimated `dispatch_pulse`'s POV: `4413 + s * (3423 ±0)` (where 's' is `MaxSubscriptions`)
151 // Then:
152 // s = (10,485,760 - 689,013 - 4,413) / 3,423 = 2,860
153 // Thus, we set `MaxSubscriptions` to 2,000 to leave some margin to other transactions
154 pub const MaxSubscriptions: u32 = 2_000;
155 /// Maximum number of subscriptions that can be terminated in a `on_finalize` execution
156 ///
157 /// This and [`MaxSubscriptions`] should be set to a number that keeps the estimated Proof
158 /// Size in the weights under the relay chain's [`MAX_POV_SIZE`](https://github.com/paritytech/polkadot-sdk/blob/da8c374871cc97807935230e7c398876d5adce62/polkadot/primitives/src/v8/mod.rs#L441)
159 // We leave it to a 10% of `MaxSubscriptions`, which is more than reasonable
160 pub const MaxTerminatableSubs: u32 = 200;
161 /// The maximum length of the metadata vector
162 pub const MaxMetadataLen: u32 = 8;
163 /// The maximum length of the call data vector
164 // The current maximum size for the given data types is under 190 bytes, so we set a higher limit
165 // to leave some margin for future changes, until this issue is ready https://github.com/ideal-lab5/idn-sdk/issues/379
166 pub const MaxCallDataLen: u32 = 256;
167}
168
169/// A type that defines the amount of credits in a subscription
170pub type Credits = u64;
171/// The subscription ID
172pub type SubscriptionId = [u8; 32];
173/// An index to a block.
174pub type BlockNumber = u32;
175/// Balance of an account.
176pub type Balance = u128;
177/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
178pub type Signature = MultiSignature;
179/// Some way of identifying an account on the chain. We intentionally make it equivalent
180/// to the public key of our transaction signing scheme.
181pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
182
183// Derived types
184
185/// The metadata type used in the pallet, represented as a bounded vector of bytes.
186///
187/// See [`pallet_idn_manager::primitives::SubscriptionMetadata`] for more details.
188pub type Metadata = SubscriptionMetadata<MaxMetadataLen>;
189/// The call data type used in the pallet, represented as a bounded vector of bytes.
190///
191/// See [`pallet_idn_manager::primitives::SubscriptionCallData`] for more details.
192pub type CallData = SubscriptionCallData<MaxCallDataLen>;
193/// The parameters for creating a new subscription, containing various details about the
194/// subscription.
195///
196/// See [`pallet_idn_manager::primitives::CreateSubParams`] for more details.
197pub type CreateSubParams =
198 MngCreateSubParams<Credits, BlockNumber, Metadata, SubscriptionId, CallData>;
199/// The parameters for updating an existing subscription, containing various details about the
200/// subscription.
201///
202/// See [`pallet_idn_manager::UpdateSubParams`] for more details.
203pub type UpdateSubParams = MngUpdateSubParams<SubscriptionId, Credits, BlockNumber, Metadata>;
204/// The parameters for quoting a subscription.
205///
206/// See [`pallet_idn_manager::primitives::QuoteSubParams`] for more details.
207pub type QuoteSubParams = MngQuoteSubParams<CreateSubParams, BlockNumber, CallData>;
208/// The request for a quote, containing the parameters for the describing the subscription.
209///
210/// See [`pallet_idn_manager::primitives::QuoteRequest`] for more details.
211pub type QuoteRequest = MngQuoteRequest<CreateSubParams, BlockNumber>;
212/// The quote for a subscription, containing the deposit and fees.
213///
214/// See [`pallet_idn_manager::primitives::Quote`] for more details.
215pub type Quote = MngQuote<Balance>;
216/// Represents a subscription in the system.
217///
218/// See [`pallet_idn_manager::Subscription`] for more details.
219pub type Subscription =
220 MngSubscription<AccountId, BlockNumber, Credits, Metadata, SubscriptionId, CallData>;
221/// The subscription info returned by the IDN Manager to the target parachain.
222///
223/// See [`pallet_idn_manager::primitives::SubInfoResponse`] for more details.
224pub type SubInfoResponse = MngSubInfoResponse<Subscription>;
225/// Contains the parameters for requesting a subscription info by its Id.
226///
227/// See [`pallet_idn_manager::primitives::SubInfoRequest`] for more details.
228pub type SubInfoRequest = MngSubInfoRequest<SubscriptionId, CallData>;
229/// Details specific to a subscription for pulse delivery.
230///
231/// See [`pallet_idn_manager::SubscriptionDetails`] for more details.
232pub type SubscriptionDetails = MngSubscriptionDetails<AccountId, CallData>;
233
234#[cfg(test)]
235mod test {
236 use super::*;
237 use sp_idn_crypto::test_utils::*;
238
239 #[test]
240 fn test_runtime_pulse_can_authenticate_valid_pulse() {
241 let beacon_pk_bytes = get_beacon_pk();
242 let (asig, _amsg, _pulses) = get(vec![PULSE1000, PULSE1001]);
243 let valid_pulse = RuntimePulse::new(asig.try_into().unwrap(), 1000, 1001);
244 let validity = valid_pulse.authenticate(beacon_pk_bytes.try_into().unwrap());
245 assert!(validity);
246 }
247
248 #[test]
249 fn test_runtime_pulse_can_handle_invalid_pulse() {
250 let beacon_pk_bytes = get_beacon_pk();
251 let (asig, _amsg, _pulses) = get(vec![PULSE1000, PULSE1001]);
252 // the pulse expects sigs for rounds 1000-1004, but only has 1000-1002
253 let valid_pulse = RuntimePulse::new(asig.try_into().unwrap(), 1000, 1004);
254 let validity = valid_pulse.authenticate(beacon_pk_bytes.try_into().unwrap());
255 assert!(!validity);
256 }
257}