griffin_solochain_runtime/
lib.rs

1//! The runtime contains the core logic of the ledger run by the Griffin node.
2
3#![cfg_attr(not(feature = "std"), no_std)]
4
5#[cfg(feature = "std")]
6include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
7
8extern crate alloc;
9
10pub mod genesis;
11
12use alloc::{string::ToString, vec, vec::Vec};
13use codec::{Decode, Encode};
14use griffin_core::genesis::config_builder::GenesisConfig;
15use griffin_core::MILLI_SECS_PER_SLOT;
16use scale_info::TypeInfo;
17use sp_api::impl_runtime_apis;
18use sp_consensus_aura::sr25519::AuthorityId as AuraId;
19use sp_consensus_grandpa::AuthorityId as GrandpaId;
20use sp_core::OpaqueMetadata;
21use sp_inherents::InherentData;
22use sp_runtime::{
23    create_runtime_str, impl_opaque_keys,
24    traits::Block as BlockT,
25    transaction_validity::{TransactionSource, TransactionValidity},
26    ApplyExtrinsicResult, BoundToRuntimeAppPublic,
27};
28
29#[cfg(feature = "std")]
30use sp_version::NativeVersion;
31use sp_version::RuntimeVersion;
32
33/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
34/// the specifics of the runtime. They can then be made to be agnostic over specific formats
35/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
36/// to even the core data structures.
37pub mod opaque {
38    use super::*;
39
40    // This part is necessary for generating session keys in the runtime
41    impl_opaque_keys! {
42        pub struct SessionKeys {
43            pub aura: AuraAppPublic,
44            pub grandpa: GrandpaAppPublic,
45        }
46    }
47
48    // Typically these are not implemented manually, but rather for the pallet associated with the
49    // keys. Here we are not using the pallets, and these implementations are trivial, so we just
50    // re-write them.
51    pub struct AuraAppPublic;
52    impl BoundToRuntimeAppPublic for AuraAppPublic {
53        type Public = AuraId;
54    }
55
56    pub struct GrandpaAppPublic;
57    impl BoundToRuntimeAppPublic for GrandpaAppPublic {
58        type Public = sp_consensus_grandpa::AuthorityId;
59    }
60}
61
62/// This runtime version.
63#[sp_version::runtime_version]
64pub const VERSION: RuntimeVersion = RuntimeVersion {
65    spec_name: create_runtime_str!("griffin-solochain-runtime"),
66    impl_name: create_runtime_str!("griffin-solochain-runtime"),
67    authoring_version: 1,
68    spec_version: 100,
69    impl_version: 1,
70    apis: RUNTIME_API_VERSIONS,
71    transaction_version: 1,
72    state_version: 1,
73};
74
75/// The version information used to identify this runtime when compiled natively.
76#[cfg(feature = "std")]
77pub fn native_version() -> NativeVersion {
78    NativeVersion {
79        runtime_version: VERSION,
80        can_author_with: Default::default(),
81    }
82}
83
84pub type Transaction = griffin_core::types::Transaction;
85pub type Block = griffin_core::types::Block;
86pub type Executive = griffin_core::Executive;
87pub type Output = griffin_core::types::Output;
88
89/// The main struct in this module.
90#[derive(Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
91pub struct Runtime;
92
93// Here we hard-code consensus authority IDs for the well-known identities that work with the CLI flags
94// Such as `--alice`, `--bob`, etc. Only Alice is enabled by default which makes things work nicely
95// in a `--dev` node. You may enable more authorities to test more interesting networks, or replace
96// these IDs entirely.
97impl Runtime {
98    /// Aura authority IDs
99    fn aura_authorities() -> Vec<AuraId> {
100        use hex_literal::hex;
101        use sp_application_crypto::ByteArray;
102
103        [
104            // Alice
105            hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"),
106            // Bob
107            // hex!("8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"),
108            // Charlie
109            // hex!("90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"),
110            // Dave
111            // hex!("306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"),
112            // Eve
113            // hex!("e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"),
114            // Ferdie
115            // hex!("1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"),
116        ]
117        .iter()
118        .map(|hex| AuraId::from_slice(hex.as_ref()).expect("Valid Aura authority hex was provided"))
119        .collect()
120    }
121
122    ///Grandpa Authority IDs - All equally weighted
123    fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
124        use hex_literal::hex;
125        use sp_application_crypto::ByteArray;
126
127        [
128            // Alice
129            hex!("88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"),
130            // Bob
131            // hex!("d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"),
132            // Charlie
133            // hex!("439660b36c6c03afafca027b910b4fecf99801834c62a5e6006f27d978de234f"),
134            // Dave
135            // hex!("5e639b43e0052c47447dac87d6fd2b6ec50bdd4d0f614e4299c665249bbd09d9"),
136            // Eve
137            // hex!("1dfe3e22cc0d45c70779c1095f7489a8ef3cf52d62fbd8c2fa38c9f1723502b5"),
138            // Ferdie
139            // hex!("568cb4a574c6d178feb39c27dfc8b3f789e5f5423e19c71633c748b9acf086b5"),
140        ]
141        .iter()
142        .map(|hex| {
143            (
144                GrandpaId::from_slice(hex.as_ref())
145                    .expect("Valid Grandpa authority hex was provided"),
146                1,
147            )
148        })
149        .collect()
150    }
151}
152
153impl_runtime_apis! {
154    // https://substrate.dev/rustdocs/master/sp_api/trait.Core.html
155    impl sp_api::Core<Block> for Runtime {
156        fn version() -> RuntimeVersion {
157            VERSION
158        }
159
160        fn execute_block(block: Block) {
161            Executive::execute_block(block)
162        }
163
164        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
165            Executive::open_block(header)
166        }
167    }
168
169    // https://substrate.dev/rustdocs/master/sc_block_builder/trait.BlockBuilderApi.html
170    impl sp_block_builder::BlockBuilder<Block> for Runtime {
171        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
172            Executive::apply_extrinsic(extrinsic)
173        }
174
175        fn finalize_block() -> <Block as BlockT>::Header {
176            Executive::close_block()
177        }
178
179        fn inherent_extrinsics(_data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
180            Vec::new()
181        }
182
183        fn check_inherents(
184            _block: Block,
185            _data: InherentData
186        ) -> sp_inherents::CheckInherentsResult {
187            sp_inherents::CheckInherentsResult::new()
188        }
189    }
190
191    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
192        fn validate_transaction(
193            source: TransactionSource,
194            tx: <Block as BlockT>::Extrinsic,
195            block_hash: <Block as BlockT>::Hash,
196        ) -> TransactionValidity {
197            Executive::validate_transaction(source, tx, block_hash)
198        }
199    }
200
201    impl sp_api::Metadata<Block> for Runtime {
202        fn metadata() -> OpaqueMetadata {
203            OpaqueMetadata::new(Vec::new())
204        }
205
206        fn metadata_at_version(_version: u32) -> Option<OpaqueMetadata> {
207            None
208        }
209
210        fn metadata_versions() -> alloc::vec::Vec<u32> {
211            Default::default()
212        }
213    }
214
215    impl sp_session::SessionKeys<Block> for Runtime {
216        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
217            opaque::SessionKeys::generate(seed)
218        }
219
220        fn decode_session_keys(
221            encoded: Vec<u8>,
222        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
223            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
224        }
225    }
226
227    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
228        fn slot_duration() -> sp_consensus_aura::SlotDuration {
229            sp_consensus_aura::SlotDuration::from_millis(MILLI_SECS_PER_SLOT.into())
230        }
231
232        fn authorities() -> Vec<AuraId> {
233            Self::aura_authorities()
234        }
235    }
236
237    impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
238        fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
239            Self::grandpa_authorities()
240        }
241
242        fn current_set_id() -> sp_consensus_grandpa::SetId {
243            0u64
244        }
245
246        fn submit_report_equivocation_unsigned_extrinsic(
247            _equivocation_proof: sp_consensus_grandpa::EquivocationProof<
248                <Block as BlockT>::Hash,
249                sp_runtime::traits::NumberFor<Block>,
250            >,
251            _key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
252        ) -> Option<()> {
253            None
254        }
255
256        fn generate_key_ownership_proof(
257            _set_id: sp_consensus_grandpa::SetId,
258            _authority_id: sp_consensus_grandpa::AuthorityId,
259        ) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
260            None
261        }
262    }
263
264    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
265        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
266            let genesis_config = serde_json::from_slice::<GenesisConfig>(config.as_slice())
267                .map_err(|_| "The input JSON is not a valid genesis configuration.")?;
268
269            griffin_core::genesis::GriffinGenesisConfigBuilder::build(genesis_config)
270        }
271
272        fn get_preset(_id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
273            let genesis_config : &GenesisConfig = &genesis::get_genesis_config("".to_string());
274            Some(serde_json::to_vec(genesis_config)
275                 .expect("Genesis configuration is valid."))
276        }
277
278        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
279            vec![]
280        }
281    }
282}