runtime_api.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. system::CheckSpecVersion<Runtime>,
  24. system::CheckTxVersion<Runtime>,
  25. system::CheckGenesis<Runtime>,
  26. system::CheckEra<Runtime>,
  27. system::CheckNonce<Runtime>,
  28. system::CheckWeight<Runtime>,
  29. pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
  30. pallet_grandpa::ValidateEquivocationReport<Runtime>,
  31. );
  32. /// Digest item type.
  33. pub type DigestItem = generic::DigestItem<Hash>;
  34. /// Block header type as expected by this runtime.
  35. pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
  36. /// Block type as expected by this runtime.
  37. pub type Block = generic::Block<Header, UncheckedExtrinsic>;
  38. /// A Block signed with a Justification
  39. pub type SignedBlock = generic::SignedBlock<Block>;
  40. /// BlockId type as expected by this runtime.
  41. pub type BlockId = generic::BlockId<Block>;
  42. /// Unchecked extrinsic type as expected by this runtime.
  43. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<AccountId, Call, Signature, SignedExtra>;
  44. /// Executive: handles dispatch to the various modules.
  45. pub type Executive =
  46. frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;
  47. /// Export of the private const generated within the macro.
  48. pub const EXPORTED_RUNTIME_API_VERSIONS: sp_version::ApisVec = RUNTIME_API_VERSIONS;
  49. impl_runtime_apis! {
  50. impl sp_api::Core<Block> for Runtime {
  51. fn version() -> RuntimeVersion {
  52. VERSION
  53. }
  54. fn execute_block(block: Block) {
  55. Executive::execute_block(block)
  56. }
  57. fn initialize_block(header: &<Block as BlockT>::Header) {
  58. Executive::initialize_block(header)
  59. }
  60. }
  61. impl sp_api::Metadata<Block> for Runtime {
  62. fn metadata() -> OpaqueMetadata {
  63. Runtime::metadata().into()
  64. }
  65. }
  66. impl sp_block_builder::BlockBuilder<Block> for Runtime {
  67. fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
  68. Executive::apply_extrinsic(extrinsic)
  69. }
  70. fn finalize_block() -> <Block as BlockT>::Header {
  71. Executive::finalize_block()
  72. }
  73. fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
  74. data.create_extrinsics()
  75. }
  76. fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
  77. data.check_extrinsics(&block)
  78. }
  79. fn random_seed() -> <Block as BlockT>::Hash {
  80. RandomnessCollectiveFlip::random_seed()
  81. }
  82. }
  83. impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
  84. fn validate_transaction(
  85. source: TransactionSource,
  86. tx: <Block as BlockT>::Extrinsic,
  87. ) -> TransactionValidity {
  88. Executive::validate_transaction(source, tx)
  89. }
  90. }
  91. impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
  92. fn offchain_worker(header: &<Block as BlockT>::Header) {
  93. Executive::offchain_worker(header)
  94. }
  95. }
  96. impl fg_primitives::GrandpaApi<Block> for Runtime {
  97. fn grandpa_authorities() -> GrandpaAuthorityList {
  98. Grandpa::grandpa_authorities()
  99. }
  100. fn submit_report_equivocation_extrinsic(
  101. equivocation_proof: fg_primitives::EquivocationProof<
  102. <Block as BlockT>::Hash,
  103. NumberFor<Block>,
  104. >,
  105. key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
  106. ) -> Option<()> {
  107. let key_owner_proof = key_owner_proof.decode()?;
  108. Grandpa::submit_report_equivocation_extrinsic(
  109. equivocation_proof,
  110. key_owner_proof,
  111. )
  112. }
  113. fn generate_key_ownership_proof(
  114. _set_id: fg_primitives::SetId,
  115. authority_id: GrandpaId,
  116. ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
  117. use codec::Encode;
  118. Historical::prove((fg_primitives::KEY_TYPE, authority_id))
  119. .map(|p| p.encode())
  120. .map(fg_primitives::OpaqueKeyOwnershipProof::new)
  121. }
  122. }
  123. impl sp_consensus_babe::BabeApi<Block> for Runtime {
  124. fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
  125. // The choice of `c` parameter (where `1 - c` represents the
  126. // probability of a slot being empty), is done in accordance to the
  127. // slot duration and expected target block time, for safely
  128. // resisting network delays of maximum two seconds.
  129. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
  130. sp_consensus_babe::BabeGenesisConfiguration {
  131. slot_duration: Babe::slot_duration(),
  132. epoch_length: EpochDuration::get(),
  133. c: PRIMARY_PROBABILITY,
  134. genesis_authorities: Babe::authorities(),
  135. randomness: Babe::randomness(),
  136. allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
  137. }
  138. }
  139. fn current_epoch_start() -> sp_consensus_babe::SlotNumber {
  140. Babe::current_epoch_start()
  141. }
  142. }
  143. impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
  144. fn authorities() -> Vec<AuthorityDiscoveryId> {
  145. AuthorityDiscovery::authorities()
  146. }
  147. }
  148. impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
  149. fn account_nonce(account: AccountId) -> Index {
  150. System::account_nonce(account)
  151. }
  152. }
  153. impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
  154. Block,
  155. Balance,
  156. UncheckedExtrinsic,
  157. > for Runtime {
  158. fn query_info(uxt: UncheckedExtrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
  159. TransactionPayment::query_info(uxt, len)
  160. }
  161. }
  162. impl sp_session::SessionKeys<Block> for Runtime {
  163. fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
  164. SessionKeys::generate(seed)
  165. }
  166. fn decode_session_keys(
  167. encoded: Vec<u8>,
  168. ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
  169. SessionKeys::decode_into_raw_public_keys(&encoded)
  170. }
  171. }
  172. #[cfg(feature = "runtime-benchmarks")]
  173. impl frame_benchmarking::Benchmark<Block> for Runtime {
  174. fn dispatch_benchmark(
  175. pallet: Vec<u8>,
  176. benchmark: Vec<u8>,
  177. lowest_range_values: Vec<u32>,
  178. highest_range_values: Vec<u32>,
  179. steps: Vec<u32>,
  180. repeat: u32,
  181. ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
  182. use sp_std::vec;
  183. use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark};
  184. use frame_system_benchmarking::Module as SystemBench;
  185. impl frame_system_benchmarking::Trait for Runtime {}
  186. let whitelist: Vec<Vec<u8>> = vec![
  187. // Block Number
  188. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec(),
  189. // Total Issuance
  190. hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec(),
  191. // Execution Phase
  192. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec(),
  193. // Event Count
  194. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec(),
  195. // System Events
  196. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec(),
  197. // Caller 0 Account
  198. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da946c154ffd9992e395af90b5b13cc6f295c77033fce8a9045824a6690bbf99c6db269502f0a8d1d2a008542d5690a0749").to_vec(),
  199. // Treasury Account
  200. hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec(),
  201. ];
  202. let mut batches = Vec::<BenchmarkBatch>::new();
  203. let params = (&pallet, &benchmark, &lowest_range_values, &highest_range_values, &steps, repeat, &whitelist);
  204. add_benchmark!(params, batches, b"system", SystemBench::<Runtime>);
  205. if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
  206. Ok(batches)
  207. }
  208. }
  209. }