lib.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. //! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.
  2. #![cfg_attr(not(feature = "std"), no_std)]
  3. // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
  4. #![recursion_limit = "256"]
  5. // Make the WASM binary available.
  6. #[cfg(feature = "std")]
  7. include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
  8. use babe::AuthorityId as BabeId;
  9. use grandpa::fg_primitives::{self, ScheduledChange};
  10. use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight};
  11. use im_online::sr25519::AuthorityId as ImOnlineId;
  12. use primitives::{crypto::key_types, OpaqueMetadata};
  13. use rstd::prelude::*;
  14. use runtime_primitives::traits::{
  15. BlakeTwo256, Block as BlockT, DigestFor, NumberFor, StaticLookup, Verify,
  16. };
  17. use runtime_primitives::weights::Weight;
  18. use runtime_primitives::{
  19. create_runtime_str, generic, impl_opaque_keys, transaction_validity::TransactionValidity,
  20. AnySignature, ApplyResult,
  21. };
  22. use substrate_client::{
  23. block_builder::api::{self as block_builder_api, CheckInherentsResult, InherentData},
  24. impl_runtime_apis, runtime_api as client_api,
  25. };
  26. #[cfg(feature = "std")]
  27. use version::NativeVersion;
  28. use version::RuntimeVersion;
  29. // A few exports that help ease life for downstream crates.
  30. pub use balances::Call as BalancesCall;
  31. #[cfg(any(feature = "std", test))]
  32. pub use runtime_primitives::BuildStorage;
  33. pub use runtime_primitives::{Perbill, Permill};
  34. pub use srml_support::{construct_runtime, parameter_types, StorageMap, StorageValue};
  35. pub use staking::StakerStatus;
  36. pub use timestamp::Call as TimestampCall;
  37. /// An index to a block.
  38. pub type BlockNumber = u32;
  39. /// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
  40. pub type Signature = AnySignature;
  41. /// Some way of identifying an account on the chain. We intentionally make it equivalent
  42. /// to the public key of our transaction signing scheme.
  43. pub type AccountId = <Signature as Verify>::Signer;
  44. /// The type for looking up accounts. We don't expect more than 4 billion of them, but you
  45. /// never know...
  46. pub type AccountIndex = u32;
  47. /// Balance of an account.
  48. pub type Balance = u128;
  49. /// Index of a transaction in the chain.
  50. pub type Index = u32;
  51. /// A hash of some data used by the chain.
  52. pub type Hash = primitives::H256;
  53. /// Digest item type.
  54. pub type DigestItem = generic::DigestItem<Hash>;
  55. /// Moment type
  56. pub type Moment = u64;
  57. /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
  58. /// the specifics of the runtime. They can then be made to be agnostic over specific formats
  59. /// of data like extrinsics, allowing for them to continue syncing the network through upgrades
  60. /// to even the core datastructures.
  61. pub mod opaque {
  62. use super::*;
  63. pub use runtime_primitives::OpaqueExtrinsic as UncheckedExtrinsic;
  64. /// Opaque block header type.
  65. pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
  66. /// Opaque block type.
  67. pub type Block = generic::Block<Header, UncheckedExtrinsic>;
  68. /// Opaque block identifier type.
  69. pub type BlockId = generic::BlockId<Block>;
  70. pub type SessionHandlers = (Grandpa, Babe, ImOnline);
  71. impl_opaque_keys! {
  72. pub struct SessionKeys {
  73. #[id(key_types::GRANDPA)]
  74. pub grandpa: GrandpaId,
  75. #[id(key_types::BABE)]
  76. pub babe: BabeId,
  77. #[id(key_types::IM_ONLINE)]
  78. pub im_online: ImOnlineId,
  79. }
  80. }
  81. }
  82. /// This runtime version.
  83. pub const VERSION: RuntimeVersion = RuntimeVersion {
  84. spec_name: create_runtime_str!("joystream-node"),
  85. impl_name: create_runtime_str!("joystream-node"),
  86. authoring_version: 0,
  87. spec_version: 6,
  88. impl_version: 0,
  89. apis: RUNTIME_API_VERSIONS,
  90. };
  91. /// Constants for Babe.
  92. /// Since BABE is probabilistic this is the average expected block time that
  93. /// we are targetting. Blocks will be produced at a minimum duration defined
  94. /// by `SLOT_DURATION`, but some slots will not be allocated to any
  95. /// authority and hence no block will be produced. We expect to have this
  96. /// block time on average following the defined slot duration and the value
  97. /// of `c` configured for BABE (where `1 - c` represents the probability of
  98. /// a slot being empty).
  99. /// This value is only used indirectly to define the unit constants below
  100. /// that are expressed in blocks. The rest of the code should use
  101. /// `SLOT_DURATION` instead (like the timestamp module for calculating the
  102. /// minimum period).
  103. /// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
  104. pub const MILLISECS_PER_BLOCK: Moment = 6000;
  105. pub const SECS_PER_BLOCK: Moment = MILLISECS_PER_BLOCK / 1000;
  106. pub const SLOT_DURATION: Moment = 6000;
  107. pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 10 * MINUTES;
  108. pub const EPOCH_DURATION_IN_SLOTS: u64 = {
  109. const SLOT_FILL_RATE: f64 = MILLISECS_PER_BLOCK as f64 / SLOT_DURATION as f64;
  110. (EPOCH_DURATION_IN_BLOCKS as f64 * SLOT_FILL_RATE) as u64
  111. };
  112. // These time units are defined in number of blocks.
  113. pub const MINUTES: BlockNumber = 60 / (SECS_PER_BLOCK as BlockNumber);
  114. pub const HOURS: BlockNumber = MINUTES * 60;
  115. pub const DAYS: BlockNumber = HOURS * 24;
  116. // 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
  117. pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
  118. /// The version infromation used to identify this runtime when compiled natively.
  119. #[cfg(feature = "std")]
  120. pub fn native_version() -> NativeVersion {
  121. NativeVersion {
  122. runtime_version: VERSION,
  123. can_author_with: Default::default(),
  124. }
  125. }
  126. parameter_types! {
  127. pub const BlockHashCount: BlockNumber = 250;
  128. pub const MaximumBlockWeight: Weight = 1_000_000;
  129. pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
  130. pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;
  131. pub const Version: RuntimeVersion = VERSION;
  132. }
  133. impl system::Trait for Runtime {
  134. /// The identifier used to distinguish between accounts.
  135. type AccountId = AccountId;
  136. /// The aggregated dispatch type that is available for extrinsics.
  137. type Call = Call;
  138. /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
  139. type Lookup = Indices;
  140. /// The index type for storing how many extrinsics an account has signed.
  141. type Index = Index;
  142. /// The index type for blocks.
  143. type BlockNumber = BlockNumber;
  144. /// The type for hashing blocks and tries.
  145. type Hash = Hash;
  146. /// The hashing algorithm used.
  147. type Hashing = BlakeTwo256;
  148. /// The header type.
  149. type Header = generic::Header<BlockNumber, BlakeTwo256>;
  150. /// The ubiquitous event type.
  151. type Event = Event;
  152. /// Update weight (to fee) multiplier per-block.
  153. type WeightMultiplierUpdate = ();
  154. /// The ubiquitous origin type.
  155. type Origin = Origin;
  156. /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
  157. type BlockHashCount = BlockHashCount;
  158. /// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok.
  159. type MaximumBlockWeight = MaximumBlockWeight;
  160. /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.
  161. type MaximumBlockLength = MaximumBlockLength;
  162. /// Portion of the block weight that is available to all normal transactions.
  163. type AvailableBlockRatio = AvailableBlockRatio;
  164. type Version = Version;
  165. }
  166. parameter_types! {
  167. pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
  168. pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
  169. }
  170. impl babe::Trait for Runtime {
  171. type EpochDuration = EpochDuration;
  172. type ExpectedBlockTime = ExpectedBlockTime;
  173. }
  174. impl grandpa::Trait for Runtime {
  175. type Event = Event;
  176. }
  177. impl indices::Trait for Runtime {
  178. /// The type for recording indexing into the account enumeration. If this ever overflows, there
  179. /// will be problems!
  180. type AccountIndex = u32;
  181. /// Use the standard means of resolving an index hint from an id.
  182. type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
  183. /// Determine whether an account is dead.
  184. type IsDeadAccount = Balances;
  185. /// The ubiquitous event type.
  186. type Event = Event;
  187. }
  188. parameter_types! {
  189. pub const MinimumPeriod: Moment = SLOT_DURATION / 2;
  190. }
  191. impl timestamp::Trait for Runtime {
  192. /// A timestamp: milliseconds since the unix epoch.
  193. type Moment = Moment;
  194. type OnTimestampSet = Babe;
  195. type MinimumPeriod = MinimumPeriod;
  196. }
  197. parameter_types! {
  198. pub const ExistentialDeposit: u128 = 0;
  199. pub const TransferFee: u128 = 0;
  200. pub const CreationFee: u128 = 0;
  201. pub const TransactionBaseFee: u128 = 1;
  202. pub const TransactionByteFee: u128 = 0;
  203. pub const InitialMembersBalance: u32 = 2000;
  204. }
  205. impl balances::Trait for Runtime {
  206. /// The type for recording an account's balance.
  207. type Balance = Balance;
  208. /// What to do if an account's free balance gets zeroed.
  209. type OnFreeBalanceZero = (Staking, Session);
  210. /// What to do if a new account is created.
  211. type OnNewAccount = Indices;
  212. /// The ubiquitous event type.
  213. type Event = Event;
  214. type TransactionPayment = ();
  215. type DustRemoval = ();
  216. type TransferPayment = ();
  217. type ExistentialDeposit = ExistentialDeposit;
  218. type TransferFee = TransferFee;
  219. type CreationFee = CreationFee;
  220. type TransactionBaseFee = TransactionBaseFee;
  221. type TransactionByteFee = TransactionByteFee;
  222. type WeightToFee = (); // computes fee to be default value of Balance/u128 = 0
  223. }
  224. impl sudo::Trait for Runtime {
  225. type Event = Event;
  226. type Proposal = Call;
  227. }
  228. parameter_types! {
  229. pub const UncleGenerations: BlockNumber = 5;
  230. }
  231. impl authorship::Trait for Runtime {
  232. type FindAuthor = session::FindAccountFromAuthorIndex<Self, Babe>;
  233. type UncleGenerations = UncleGenerations;
  234. type FilterUncle = ();
  235. type EventHandler = Staking;
  236. }
  237. type SessionHandlers = (Grandpa, Babe, ImOnline);
  238. impl_opaque_keys! {
  239. pub struct SessionKeys {
  240. #[id(key_types::GRANDPA)]
  241. pub grandpa: GrandpaId,
  242. #[id(key_types::BABE)]
  243. pub babe: BabeId,
  244. #[id(key_types::IM_ONLINE)]
  245. pub im_online: ImOnlineId,
  246. }
  247. }
  248. // NOTE: `SessionHandler` and `SessionKeys` are co-dependent: One key will be used for each handler.
  249. // The number and order of items in `SessionHandler` *MUST* be the same number and order of keys in
  250. // `SessionKeys`.
  251. // TODO: Introduce some structure to tie these together to make it a bit less of a footgun. This
  252. // should be easy, since OneSessionHandler trait provides the `Key` as an associated type. #2858
  253. impl session::Trait for Runtime {
  254. type OnSessionEnding = Staking;
  255. type SessionHandler = SessionHandlers;
  256. type ShouldEndSession = Babe;
  257. type Event = Event;
  258. type Keys = SessionKeys;
  259. type ValidatorId = AccountId;
  260. type ValidatorIdOf = staking::StashOf<Self>;
  261. type SelectInitialValidators = Staking;
  262. }
  263. impl session::historical::Trait for Runtime {
  264. type FullIdentification = staking::Exposure<AccountId, Balance>;
  265. type FullIdentificationOf = staking::ExposureOf<Runtime>;
  266. }
  267. parameter_types! {
  268. pub const SessionsPerEra: sr_staking_primitives::SessionIndex = 6;
  269. pub const BondingDuration: staking::EraIndex = 24 * 28;
  270. }
  271. impl staking::Trait for Runtime {
  272. type Currency = Balances;
  273. type Time = Timestamp;
  274. type CurrencyToVote = currency::CurrencyToVoteHandler;
  275. type OnRewardMinted = ();
  276. type Event = Event;
  277. type Slash = (); // where to send the slashed funds.
  278. type Reward = (); // rewards are minted from the void
  279. type SessionsPerEra = SessionsPerEra;
  280. type BondingDuration = BondingDuration;
  281. type SessionInterface = Self;
  282. }
  283. impl im_online::Trait for Runtime {
  284. type AuthorityId = ImOnlineId;
  285. type Call = Call;
  286. type Event = Event;
  287. type UncheckedExtrinsic = UncheckedExtrinsic;
  288. type ReportUnresponsiveness = Offences;
  289. type CurrentElectedSet = staking::CurrentElectedStashAccounts<Runtime>;
  290. }
  291. impl offences::Trait for Runtime {
  292. type Event = Event;
  293. type IdentificationTuple = session::historical::IdentificationTuple<Self>;
  294. type OnOffenceHandler = Staking;
  295. }
  296. impl authority_discovery::Trait for Runtime {}
  297. parameter_types! {
  298. pub const WindowSize: BlockNumber = 101;
  299. pub const ReportLatency: BlockNumber = 1000;
  300. }
  301. impl finality_tracker::Trait for Runtime {
  302. type OnFinalizationStalled = Grandpa;
  303. type WindowSize = WindowSize;
  304. type ReportLatency = ReportLatency;
  305. }
  306. pub mod currency;
  307. pub mod governance;
  308. use governance::{council, election, proposals};
  309. pub mod storage;
  310. use storage::{data_directory, data_object_storage_registry, data_object_type_registry, downloads};
  311. mod membership;
  312. mod memo;
  313. mod traits;
  314. pub use forum;
  315. use membership::members;
  316. mod migration;
  317. mod roles;
  318. mod service_discovery;
  319. use roles::actors;
  320. use service_discovery::discovery;
  321. /// Alias for ContentId, used in various places.
  322. pub type ContentId = primitives::H256;
  323. impl currency::GovernanceCurrency for Runtime {
  324. type Currency = balances::Module<Self>;
  325. }
  326. impl governance::proposals::Trait for Runtime {
  327. type Event = Event;
  328. }
  329. impl governance::election::Trait for Runtime {
  330. type Event = Event;
  331. type CouncilElected = (Council,);
  332. }
  333. impl governance::council::Trait for Runtime {
  334. type Event = Event;
  335. type CouncilTermEnded = (CouncilElection,);
  336. }
  337. impl memo::Trait for Runtime {
  338. type Event = Event;
  339. }
  340. impl storage::data_object_type_registry::Trait for Runtime {
  341. type Event = Event;
  342. type DataObjectTypeId = u64;
  343. }
  344. impl storage::data_directory::Trait for Runtime {
  345. type Event = Event;
  346. type ContentId = ContentId;
  347. type SchemaId = u64;
  348. type Roles = LookupRoles;
  349. type IsActiveDataObjectType = DataObjectTypeRegistry;
  350. }
  351. impl storage::downloads::Trait for Runtime {
  352. type Event = Event;
  353. type DownloadSessionId = u64;
  354. type ContentHasStorage = DataObjectStorageRegistry;
  355. }
  356. impl storage::data_object_storage_registry::Trait for Runtime {
  357. type Event = Event;
  358. type DataObjectStorageRelationshipId = u64;
  359. type Roles = LookupRoles;
  360. type ContentIdExists = DataDirectory;
  361. }
  362. fn random_index(upper_bound: usize) -> usize {
  363. let seed = <system::Module<Runtime>>::random_seed();
  364. let mut rand: u64 = 0;
  365. for offset in 0..8 {
  366. rand += (seed.as_ref()[offset] as u64) << offset;
  367. }
  368. (rand as usize) % upper_bound
  369. }
  370. pub struct LookupRoles {}
  371. impl traits::Roles<Runtime> for LookupRoles {
  372. fn is_role_account(account_id: &<Runtime as system::Trait>::AccountId) -> bool {
  373. <actors::Module<Runtime>>::is_role_account(account_id)
  374. }
  375. fn account_has_role(
  376. account_id: &<Runtime as system::Trait>::AccountId,
  377. role: actors::Role,
  378. ) -> bool {
  379. <actors::Module<Runtime>>::account_has_role(account_id, role)
  380. }
  381. fn random_account_for_role(
  382. role: actors::Role,
  383. ) -> Result<<Runtime as system::Trait>::AccountId, &'static str> {
  384. let ids = <actors::AccountIdsByRole<Runtime>>::get(role);
  385. let live_ids: Vec<<Runtime as system::Trait>::AccountId> = ids
  386. .into_iter()
  387. .filter(|id| !<discovery::Module<Runtime>>::is_account_info_expired(id))
  388. .collect();
  389. if live_ids.len() == 0 {
  390. Err("no staked account found")
  391. } else {
  392. let index = random_index(live_ids.len());
  393. Ok(live_ids[index].clone())
  394. }
  395. }
  396. }
  397. impl members::Trait for Runtime {
  398. type Event = Event;
  399. type MemberId = u64;
  400. type PaidTermId = u64;
  401. type SubscriptionId = u64;
  402. type InitialMembersBalance = InitialMembersBalance;
  403. }
  404. /*
  405. * Forum module integration
  406. *
  407. * ForumUserRegistry could have been implemented directly on
  408. * the membership module, and likewise ForumUser on Profile,
  409. * however this approach is more loosley coupled.
  410. *
  411. * Further exploration required to decide what the long
  412. * run convention should be.
  413. */
  414. /// Shim registry which will proxy ForumUserRegistry behaviour to the members module
  415. pub struct ShimMembershipRegistry {}
  416. impl forum::ForumUserRegistry<AccountId> for ShimMembershipRegistry {
  417. fn get_forum_user(id: &AccountId) -> Option<forum::ForumUser<AccountId>> {
  418. if let Some(_profile) = members::Module::<Runtime>::get_profile_by_primary_account(id) {
  419. // For now the profile is not used for anything,
  420. // but in the future we may need it to read out more
  421. // information possibly required to construct a
  422. // ForumUser.
  423. // Now convert member profile to a forum user
  424. Some(forum::ForumUser { id: id.clone() })
  425. } else {
  426. None
  427. }
  428. }
  429. }
  430. impl forum::Trait for Runtime {
  431. type Event = Event;
  432. type MembershipRegistry = ShimMembershipRegistry;
  433. }
  434. impl migration::Trait for Runtime {
  435. type Event = Event;
  436. }
  437. impl actors::Trait for Runtime {
  438. type Event = Event;
  439. type OnActorRemoved = HandleActorRemoved;
  440. }
  441. pub struct HandleActorRemoved {}
  442. impl actors::ActorRemoved<Runtime> for HandleActorRemoved {
  443. fn actor_removed(actor: &<Runtime as system::Trait>::AccountId) {
  444. Discovery::remove_account_info(actor);
  445. }
  446. }
  447. impl discovery::Trait for Runtime {
  448. type Event = Event;
  449. type Roles = LookupRoles;
  450. }
  451. construct_runtime!(
  452. pub enum Runtime where
  453. Block = Block,
  454. NodeBlock = opaque::Block,
  455. UncheckedExtrinsic = UncheckedExtrinsic
  456. {
  457. // Substrate
  458. System: system::{Module, Call, Storage, Config, Event},
  459. Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)},
  460. Timestamp: timestamp::{Module, Call, Storage, Inherent},
  461. Authorship: authorship::{Module, Call, Storage, Inherent},
  462. Indices: indices,
  463. Balances: balances,
  464. Staking: staking::{default, OfflineWorker},
  465. Session: session::{Module, Call, Storage, Event, Config<T>},
  466. FinalityTracker: finality_tracker::{Module, Call, Inherent},
  467. Grandpa: grandpa::{Module, Call, Storage, Config, Event},
  468. ImOnline: im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
  469. AuthorityDiscovery: authority_discovery::{Module, Call, Config<T>},
  470. Offences: offences::{Module, Call, Storage, Event},
  471. Sudo: sudo,
  472. // Joystream
  473. Proposals: proposals::{Module, Call, Storage, Event<T>, Config<T>},
  474. CouncilElection: election::{Module, Call, Storage, Event<T>, Config<T>},
  475. Council: council::{Module, Call, Storage, Event<T>, Config<T>},
  476. Memo: memo::{Module, Call, Storage, Event<T>},
  477. Members: members::{Module, Call, Storage, Event<T>, Config<T>},
  478. Forum: forum::{Module, Call, Storage, Event<T>, Config<T>},
  479. Migration: migration::{Module, Call, Storage, Event<T>},
  480. Actors: actors::{Module, Call, Storage, Event<T>, Config},
  481. DataObjectTypeRegistry: data_object_type_registry::{Module, Call, Storage, Event<T>, Config<T>},
  482. DataDirectory: data_directory::{Module, Call, Storage, Event<T>},
  483. DataObjectStorageRegistry: data_object_storage_registry::{Module, Call, Storage, Event<T>, Config<T>},
  484. DownloadSessions: downloads::{Module, Call, Storage, Event<T>, Config<T>},
  485. Discovery: discovery::{Module, Call, Storage, Event<T>},
  486. }
  487. );
  488. /// The address format for describing accounts.
  489. pub type Address = <Indices as StaticLookup>::Source;
  490. /// Block header type as expected by this runtime.
  491. pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
  492. /// Block type as expected by this runtime.
  493. pub type Block = generic::Block<Header, UncheckedExtrinsic>;
  494. /// A Block signed with a Justification
  495. pub type SignedBlock = generic::SignedBlock<Block>;
  496. /// BlockId type as expected by this runtime.
  497. pub type BlockId = generic::BlockId<Block>;
  498. /// The SignedExtension to the basic transaction logic.
  499. pub type SignedExtra = (
  500. system::CheckVersion<Runtime>,
  501. system::CheckGenesis<Runtime>,
  502. system::CheckEra<Runtime>,
  503. system::CheckNonce<Runtime>,
  504. system::CheckWeight<Runtime>,
  505. balances::TakeFees<Runtime>,
  506. );
  507. /// Unchecked extrinsic type as expected by this runtime.
  508. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
  509. /// Extrinsic type that has already been checked.
  510. pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;
  511. /// Executive: handles dispatch to the various modules.
  512. pub type Executive =
  513. executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;
  514. impl_runtime_apis! {
  515. impl client_api::Core<Block> for Runtime {
  516. fn version() -> RuntimeVersion {
  517. VERSION
  518. }
  519. fn execute_block(block: Block) {
  520. Executive::execute_block(block)
  521. }
  522. fn initialize_block(header: &<Block as BlockT>::Header) {
  523. Executive::initialize_block(header)
  524. }
  525. }
  526. impl client_api::Metadata<Block> for Runtime {
  527. fn metadata() -> OpaqueMetadata {
  528. Runtime::metadata().into()
  529. }
  530. }
  531. impl block_builder_api::BlockBuilder<Block> for Runtime {
  532. fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
  533. Executive::apply_extrinsic(extrinsic)
  534. }
  535. fn finalize_block() -> <Block as BlockT>::Header {
  536. Executive::finalize_block()
  537. }
  538. fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
  539. data.create_extrinsics()
  540. }
  541. fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
  542. data.check_extrinsics(&block)
  543. }
  544. fn random_seed() -> <Block as BlockT>::Hash {
  545. System::random_seed()
  546. }
  547. }
  548. impl client_api::TaggedTransactionQueue<Block> for Runtime {
  549. fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {
  550. Executive::validate_transaction(tx)
  551. }
  552. }
  553. impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
  554. fn offchain_worker(number: NumberFor<Block>) {
  555. Executive::offchain_worker(number)
  556. }
  557. }
  558. impl fg_primitives::GrandpaApi<Block> for Runtime {
  559. fn grandpa_pending_change(digest: &DigestFor<Block>)
  560. -> Option<ScheduledChange<NumberFor<Block>>>
  561. {
  562. Grandpa::pending_change(digest)
  563. }
  564. fn grandpa_forced_change(digest: &DigestFor<Block>)
  565. -> Option<(NumberFor<Block>, ScheduledChange<NumberFor<Block>>)>
  566. {
  567. Grandpa::forced_change(digest)
  568. }
  569. fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> {
  570. Grandpa::grandpa_authorities()
  571. }
  572. }
  573. impl babe_primitives::BabeApi<Block> for Runtime {
  574. fn startup_data() -> babe_primitives::BabeConfiguration {
  575. // The choice of `c` parameter (where `1 - c` represents the
  576. // probability of a slot being empty), is done in accordance to the
  577. // slot duration and expected target block time, for safely
  578. // resisting network delays of maximum two seconds.
  579. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
  580. babe_primitives::BabeConfiguration {
  581. median_required_blocks: 1000,
  582. slot_duration: Babe::slot_duration(),
  583. c: PRIMARY_PROBABILITY,
  584. }
  585. }
  586. fn epoch() -> babe_primitives::Epoch {
  587. babe_primitives::Epoch {
  588. start_slot: Babe::epoch_start_slot(),
  589. authorities: Babe::authorities(),
  590. epoch_index: Babe::epoch_index(),
  591. randomness: Babe::randomness(),
  592. duration: EpochDuration::get(),
  593. secondary_slots: Babe::secondary_slots().0,
  594. }
  595. }
  596. }
  597. impl authority_discovery_primitives::AuthorityDiscoveryApi<Block, ImOnlineId> for Runtime {
  598. fn authority_id() -> Option<ImOnlineId> {
  599. AuthorityDiscovery::authority_id()
  600. }
  601. fn authorities() -> Vec<ImOnlineId> {
  602. AuthorityDiscovery::authorities()
  603. }
  604. fn sign(payload: Vec<u8>, authority_id: ImOnlineId) -> Option<Vec<u8>> {
  605. AuthorityDiscovery::sign(payload, authority_id)
  606. }
  607. fn verify(payload: Vec<u8>, signature: Vec<u8>, public_key: ImOnlineId) -> bool {
  608. AuthorityDiscovery::verify(payload, signature, public_key)
  609. }
  610. }
  611. impl node_primitives::AccountNonceApi<Block> for Runtime {
  612. fn account_nonce(account: AccountId) -> Index {
  613. System::account_nonce(account)
  614. }
  615. }
  616. impl substrate_session::SessionKeys<Block> for Runtime {
  617. fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
  618. let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string"));
  619. opaque::SessionKeys::generate(seed)
  620. }
  621. }
  622. }