runtime_api.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. use frame_support::inherent::{CheckInherentsResult, InherentData};
  2. use frame_support::traits::{KeyOwnerProofSystem, Randomness};
  3. use frame_support::unsigned::{TransactionSource, TransactionValidity};
  4. use pallet_grandpa::fg_primitives;
  5. use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
  6. use sp_api::impl_runtime_apis;
  7. use sp_core::crypto::KeyTypeId;
  8. use sp_core::OpaqueMetadata;
  9. use sp_runtime::traits::{BlakeTwo256, Block as BlockT, NumberFor};
  10. use sp_runtime::{generic, ApplyExtrinsicResult};
  11. use sp_std::vec::Vec;
  12. use crate::constants::PRIMARY_PROBABILITY;
  13. use crate::{
  14. AccountId, AuthorityDiscoveryId, Balance, BlockNumber, EpochDuration, GrandpaAuthorityList,
  15. GrandpaId, Hash, Index, RuntimeVersion, Signature, VERSION,
  16. };
  17. use crate::{
  18. AllModules, AuthorityDiscovery, Babe, Call, Grandpa, Historical, InherentDataExt,
  19. RandomnessCollectiveFlip, Runtime, SessionKeys, System, TransactionPayment,
  20. };
  21. /// The SignedExtension to the basic transaction logic.
  22. pub type SignedExtra = (
  23. frame_system::CheckSpecVersion<Runtime>,
  24. frame_system::CheckTxVersion<Runtime>,
  25. frame_system::CheckGenesis<Runtime>,
  26. frame_system::CheckEra<Runtime>,
  27. frame_system::CheckNonce<Runtime>,
  28. frame_system::CheckWeight<Runtime>,
  29. pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
  30. );
  31. /// We don't use specific Address types (like Indices).
  32. pub type Address = AccountId;
  33. /// Digest item type.
  34. pub type DigestItem = generic::DigestItem<Hash>;
  35. /// Block header type as expected by this runtime.
  36. pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
  37. /// Block type as expected by this runtime.
  38. pub type Block = generic::Block<Header, UncheckedExtrinsic>;
  39. /// A Block signed with a Justification
  40. pub type SignedBlock = generic::SignedBlock<Block>;
  41. /// BlockId type as expected by this runtime.
  42. pub type BlockId = generic::BlockId<Block>;
  43. /// Unchecked extrinsic type as expected by this runtime.
  44. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<AccountId, Call, Signature, SignedExtra>;
  45. // Default Executive type without the RuntimeUpgrade
  46. pub type Executive = frame_executive::Executive<
  47. Runtime,
  48. Block,
  49. frame_system::ChainContext<Runtime>,
  50. Runtime,
  51. AllModules,
  52. >;
  53. // /// Custom runtime upgrade handler.
  54. // pub struct CustomOnRuntimeUpgrade;
  55. // impl OnRuntimeUpgrade for CustomOnRuntimeUpgrade {
  56. // fn on_runtime_upgrade() -> Weight {
  57. //
  58. // 10_000_000 // TODO: adjust weight
  59. // }
  60. // }
  61. //
  62. // /// Executive: handles dispatch to the various modules with CustomOnRuntimeUpgrade.
  63. // pub type Executive = frame_executive::Executive<
  64. // Runtime,
  65. // Block,
  66. // frame_system::ChainContext<Runtime>,
  67. // Runtime,
  68. // AllModules,
  69. // CustomOnRuntimeUpgrade,
  70. // >;
  71. /// Export of the private const generated within the macro.
  72. pub const EXPORTED_RUNTIME_API_VERSIONS: sp_version::ApisVec = RUNTIME_API_VERSIONS;
  73. impl_runtime_apis! {
  74. impl sp_api::Core<Block> for Runtime {
  75. fn version() -> RuntimeVersion {
  76. VERSION
  77. }
  78. fn execute_block(block: Block) {
  79. Executive::execute_block(block)
  80. }
  81. fn initialize_block(header: &<Block as BlockT>::Header) {
  82. Executive::initialize_block(header)
  83. }
  84. }
  85. impl sp_api::Metadata<Block> for Runtime {
  86. fn metadata() -> OpaqueMetadata {
  87. Runtime::metadata().into()
  88. }
  89. }
  90. impl sp_block_builder::BlockBuilder<Block> for Runtime {
  91. fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
  92. Executive::apply_extrinsic(extrinsic)
  93. }
  94. fn finalize_block() -> <Block as BlockT>::Header {
  95. Executive::finalize_block()
  96. }
  97. fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
  98. data.create_extrinsics()
  99. }
  100. fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
  101. data.check_extrinsics(&block)
  102. }
  103. fn random_seed() -> <Block as BlockT>::Hash {
  104. RandomnessCollectiveFlip::random_seed()
  105. }
  106. }
  107. impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
  108. fn validate_transaction(
  109. source: TransactionSource,
  110. tx: <Block as BlockT>::Extrinsic,
  111. ) -> TransactionValidity {
  112. Executive::validate_transaction(source, tx)
  113. }
  114. }
  115. impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
  116. fn offchain_worker(header: &<Block as BlockT>::Header) {
  117. Executive::offchain_worker(header)
  118. }
  119. }
  120. impl fg_primitives::GrandpaApi<Block> for Runtime {
  121. fn grandpa_authorities() -> GrandpaAuthorityList {
  122. Grandpa::grandpa_authorities()
  123. }
  124. fn submit_report_equivocation_unsigned_extrinsic(
  125. equivocation_proof: fg_primitives::EquivocationProof<
  126. <Block as BlockT>::Hash,
  127. NumberFor<Block>,
  128. >,
  129. key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
  130. ) -> Option<()> {
  131. let key_owner_proof = key_owner_proof.decode()?;
  132. Grandpa::submit_unsigned_equivocation_report(
  133. equivocation_proof,
  134. key_owner_proof,
  135. )
  136. }
  137. fn generate_key_ownership_proof(
  138. _set_id: fg_primitives::SetId,
  139. authority_id: GrandpaId,
  140. ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
  141. use codec::Encode;
  142. Historical::prove((fg_primitives::KEY_TYPE, authority_id))
  143. .map(|p| p.encode())
  144. .map(fg_primitives::OpaqueKeyOwnershipProof::new)
  145. }
  146. }
  147. impl sp_consensus_babe::BabeApi<Block> for Runtime {
  148. fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
  149. // The choice of `c` parameter (where `1 - c` represents the
  150. // probability of a slot being empty), is done in accordance to the
  151. // slot duration and expected target block time, for safely
  152. // resisting network delays of maximum two seconds.
  153. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
  154. sp_consensus_babe::BabeGenesisConfiguration {
  155. slot_duration: Babe::slot_duration(),
  156. epoch_length: EpochDuration::get(),
  157. c: PRIMARY_PROBABILITY,
  158. genesis_authorities: Babe::authorities(),
  159. randomness: Babe::randomness(),
  160. allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
  161. }
  162. }
  163. fn generate_key_ownership_proof(
  164. _slot_number: sp_consensus_babe::SlotNumber,
  165. authority_id: sp_consensus_babe::AuthorityId,
  166. ) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
  167. use codec::Encode;
  168. Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
  169. .map(|p| p.encode())
  170. .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
  171. }
  172. fn submit_report_equivocation_unsigned_extrinsic(
  173. equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
  174. key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
  175. ) -> Option<()> {
  176. let key_owner_proof = key_owner_proof.decode()?;
  177. Babe::submit_unsigned_equivocation_report(
  178. equivocation_proof,
  179. key_owner_proof,
  180. )
  181. }
  182. fn current_epoch_start() -> sp_consensus_babe::SlotNumber {
  183. Babe::current_epoch_start()
  184. }
  185. }
  186. impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
  187. fn authorities() -> Vec<AuthorityDiscoveryId> {
  188. AuthorityDiscovery::authorities()
  189. }
  190. }
  191. impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
  192. fn account_nonce(account: AccountId) -> Index {
  193. System::account_nonce(account)
  194. }
  195. }
  196. impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
  197. Block,
  198. Balance,
  199. > for Runtime {
  200. fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
  201. TransactionPayment::query_info(uxt, len)
  202. }
  203. }
  204. impl sp_session::SessionKeys<Block> for Runtime {
  205. fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
  206. SessionKeys::generate(seed)
  207. }
  208. fn decode_session_keys(
  209. encoded: Vec<u8>,
  210. ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
  211. SessionKeys::decode_into_raw_public_keys(&encoded)
  212. }
  213. }
  214. #[cfg(feature = "runtime-benchmarks")]
  215. impl frame_benchmarking::Benchmark<Block> for Runtime {
  216. fn dispatch_benchmark(
  217. config: frame_benchmarking::BenchmarkConfig
  218. ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
  219. use sp_std::vec;
  220. use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};
  221. use frame_system_benchmarking::Module as SystemBench;
  222. impl frame_system_benchmarking::Trait for Runtime {}
  223. use crate::ProposalsDiscussion;
  224. use crate::ProposalsEngine;
  225. use crate::Constitution;
  226. let whitelist: Vec<TrackedStorageKey> = vec![
  227. // Block Number
  228. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
  229. // Total Issuance
  230. hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
  231. // Execution Phase
  232. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
  233. // Event Count
  234. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
  235. // System Events
  236. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
  237. // Caller 0 Account
  238. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da946c154ffd9992e395af90b5b13cc6f295c77033fce8a9045824a6690bbf99c6db269502f0a8d1d2a008542d5690a0749").to_vec().into(),
  239. // Treasury Account
  240. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(),
  241. ];
  242. let mut batches = Vec::<BenchmarkBatch>::new();
  243. let params = (&config, &whitelist);
  244. add_benchmark!(params, batches, system, SystemBench::<Runtime>);
  245. add_benchmark!(params, batches, proposals_discussion, ProposalsDiscussion);
  246. add_benchmark!(params, batches, proposals_engine, ProposalsEngine);
  247. add_benchmark!(params, batches, pallet_constitution, Constitution);
  248. if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
  249. Ok(batches)
  250. }
  251. }
  252. }