lib.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. // This is required only by the node build.
  7. // A dummy wasm_binary.rs will be built for the IDE.
  8. #[cfg(feature = "std")]
  9. include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
  10. use authority_discovery_primitives::{
  11. AuthorityId as EncodedAuthorityId, Signature as EncodedSignature,
  12. };
  13. use babe_primitives::{AuthorityId as BabeId, AuthoritySignature as BabeSignature};
  14. use codec::{Decode, Encode};
  15. use grandpa::fg_primitives;
  16. use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight};
  17. use im_online::sr25519::AuthorityId as ImOnlineId;
  18. use primitives::OpaqueMetadata;
  19. use rstd::prelude::*;
  20. use sr_primitives::curve::PiecewiseLinear;
  21. use sr_primitives::traits::{
  22. BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, StaticLookup, Verify,
  23. };
  24. use sr_primitives::weights::Weight;
  25. use sr_primitives::{
  26. create_runtime_str, generic, impl_opaque_keys, transaction_validity::TransactionValidity,
  27. ApplyResult, MultiSignature,
  28. };
  29. use substrate_client::{
  30. block_builder::api::{self as block_builder_api, CheckInherentsResult, InherentData},
  31. impl_runtime_apis, runtime_api as client_api,
  32. };
  33. use system::offchain::TransactionSubmitter;
  34. #[cfg(feature = "std")]
  35. use version::NativeVersion;
  36. use version::RuntimeVersion;
  37. // A few exports that help ease life for downstream crates.
  38. pub use balances::Call as BalancesCall;
  39. #[cfg(any(feature = "std", test))]
  40. pub use sr_primitives::BuildStorage;
  41. pub use sr_primitives::{Perbill, Permill};
  42. pub use srml_support::{
  43. construct_runtime, parameter_types, traits::Currency, traits::Imbalance, traits::Randomness,
  44. StorageLinkedMap, StorageMap, StorageValue,
  45. };
  46. pub use staking::StakerStatus;
  47. pub use timestamp::Call as TimestampCall;
  48. /// An index to a block.
  49. pub type BlockNumber = u32;
  50. /// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
  51. pub type Signature = MultiSignature;
  52. /// Some way of identifying an account on the chain. We intentionally make it equivalent
  53. /// to the public key of our transaction signing scheme.
  54. pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
  55. /// The type for looking up accounts. We don't expect more than 4 billion of them, but you
  56. /// never know...
  57. pub type AccountIndex = u32;
  58. /// Balance of an account.
  59. pub type Balance = u128;
  60. /// Index of a transaction in the chain.
  61. pub type Index = u32;
  62. /// A hash of some data used by the chain.
  63. pub type Hash = primitives::H256;
  64. /// Digest item type.
  65. pub type DigestItem = generic::DigestItem<Hash>;
  66. /// Moment type
  67. pub type Moment = u64;
  68. /// Credential type
  69. pub type Credential = u64;
  70. /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
  71. /// the specifics of the runtime. They can then be made to be agnostic over specific formats
  72. /// of data like extrinsics, allowing for them to continue syncing the network through upgrades
  73. /// to even the core datastructures.
  74. pub mod opaque {
  75. use super::*;
  76. pub use sr_primitives::OpaqueExtrinsic as UncheckedExtrinsic;
  77. /// Opaque block header type.
  78. pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
  79. /// Opaque block type.
  80. pub type Block = generic::Block<Header, UncheckedExtrinsic>;
  81. /// Opaque block identifier type.
  82. pub type BlockId = generic::BlockId<Block>;
  83. pub type SessionHandlers = (Grandpa, Babe, ImOnline);
  84. impl_opaque_keys! {
  85. pub struct SessionKeys {
  86. pub grandpa: Grandpa,
  87. pub babe: Babe,
  88. pub im_online: ImOnline,
  89. }
  90. }
  91. }
  92. /// This runtime version.
  93. pub const VERSION: RuntimeVersion = RuntimeVersion {
  94. spec_name: create_runtime_str!("joystream-node"),
  95. impl_name: create_runtime_str!("joystream-node"),
  96. authoring_version: 6,
  97. spec_version: 9,
  98. impl_version: 0,
  99. apis: RUNTIME_API_VERSIONS,
  100. };
  101. /// Constants for Babe.
  102. /// Since BABE is probabilistic this is the average expected block time that
  103. /// we are targetting. Blocks will be produced at a minimum duration defined
  104. /// by `SLOT_DURATION`, but some slots will not be allocated to any
  105. /// authority and hence no block will be produced. We expect to have this
  106. /// block time on average following the defined slot duration and the value
  107. /// of `c` configured for BABE (where `1 - c` represents the probability of
  108. /// a slot being empty).
  109. /// This value is only used indirectly to define the unit constants below
  110. /// that are expressed in blocks. The rest of the code should use
  111. /// `SLOT_DURATION` instead (like the timestamp module for calculating the
  112. /// minimum period).
  113. /// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
  114. pub const MILLISECS_PER_BLOCK: Moment = 6000;
  115. pub const SECS_PER_BLOCK: Moment = MILLISECS_PER_BLOCK / 1000;
  116. pub const SLOT_DURATION: Moment = 6000;
  117. pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 10 * MINUTES;
  118. pub const EPOCH_DURATION_IN_SLOTS: u64 = {
  119. const SLOT_FILL_RATE: f64 = MILLISECS_PER_BLOCK as f64 / SLOT_DURATION as f64;
  120. (EPOCH_DURATION_IN_BLOCKS as f64 * SLOT_FILL_RATE) as u64
  121. };
  122. // These time units are defined in number of blocks.
  123. pub const MINUTES: BlockNumber = 60 / (SECS_PER_BLOCK as BlockNumber);
  124. pub const HOURS: BlockNumber = MINUTES * 60;
  125. pub const DAYS: BlockNumber = HOURS * 24;
  126. // 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
  127. pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
  128. /// The version infromation used to identify this runtime when compiled natively.
  129. #[cfg(feature = "std")]
  130. pub fn native_version() -> NativeVersion {
  131. NativeVersion {
  132. runtime_version: VERSION,
  133. can_author_with: Default::default(),
  134. }
  135. }
  136. parameter_types! {
  137. pub const BlockHashCount: BlockNumber = 250;
  138. pub const MaximumBlockWeight: Weight = 1_000_000;
  139. pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
  140. pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;
  141. pub const Version: RuntimeVersion = VERSION;
  142. }
  143. impl system::Trait for Runtime {
  144. /// The identifier used to distinguish between accounts.
  145. type AccountId = AccountId;
  146. /// The aggregated dispatch type that is available for extrinsics.
  147. type Call = Call;
  148. /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
  149. type Lookup = Indices;
  150. /// The index type for storing how many extrinsics an account has signed.
  151. type Index = Index;
  152. /// The index type for blocks.
  153. type BlockNumber = BlockNumber;
  154. /// The type for hashing blocks and tries.
  155. type Hash = Hash;
  156. /// The hashing algorithm used.
  157. type Hashing = BlakeTwo256;
  158. /// The header type.
  159. type Header = generic::Header<BlockNumber, BlakeTwo256>;
  160. /// The ubiquitous event type.
  161. type Event = Event;
  162. /// The ubiquitous origin type.
  163. type Origin = Origin;
  164. /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
  165. type BlockHashCount = BlockHashCount;
  166. /// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok.
  167. type MaximumBlockWeight = MaximumBlockWeight;
  168. /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.
  169. type MaximumBlockLength = MaximumBlockLength;
  170. /// Portion of the block weight that is available to all normal transactions.
  171. type AvailableBlockRatio = AvailableBlockRatio;
  172. type Version = Version;
  173. }
  174. parameter_types! {
  175. pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
  176. pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
  177. }
  178. impl babe::Trait for Runtime {
  179. type EpochDuration = EpochDuration;
  180. type ExpectedBlockTime = ExpectedBlockTime;
  181. type EpochChangeTrigger = babe::ExternalTrigger;
  182. }
  183. impl grandpa::Trait for Runtime {
  184. type Event = Event;
  185. }
  186. impl indices::Trait for Runtime {
  187. /// The type for recording indexing into the account enumeration. If this ever overflows, there
  188. /// will be problems!
  189. type AccountIndex = u32;
  190. /// Use the standard means of resolving an index hint from an id.
  191. type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
  192. /// Determine whether an account is dead.
  193. type IsDeadAccount = Balances;
  194. /// The ubiquitous event type.
  195. type Event = Event;
  196. }
  197. parameter_types! {
  198. pub const MinimumPeriod: Moment = SLOT_DURATION / 2;
  199. }
  200. impl timestamp::Trait for Runtime {
  201. /// A timestamp: milliseconds since the unix epoch.
  202. type Moment = Moment;
  203. type OnTimestampSet = Babe;
  204. type MinimumPeriod = MinimumPeriod;
  205. }
  206. parameter_types! {
  207. pub const ExistentialDeposit: u128 = 0;
  208. pub const TransferFee: u128 = 0;
  209. pub const CreationFee: u128 = 0;
  210. pub const TransactionBaseFee: u128 = 1;
  211. pub const TransactionByteFee: u128 = 0;
  212. pub const InitialMembersBalance: u32 = 2000;
  213. }
  214. impl balances::Trait for Runtime {
  215. /// The type for recording an account's balance.
  216. type Balance = Balance;
  217. /// What to do if an account's free balance gets zeroed.
  218. type OnFreeBalanceZero = (Staking, Session);
  219. /// What to do if a new account is created.
  220. type OnNewAccount = (); // Indices; // disable use of Indices feature
  221. /// The ubiquitous event type.
  222. type Event = Event;
  223. type DustRemoval = ();
  224. type TransferPayment = ();
  225. type ExistentialDeposit = ExistentialDeposit;
  226. type TransferFee = TransferFee;
  227. type CreationFee = CreationFee;
  228. }
  229. impl transaction_payment::Trait for Runtime {
  230. type Currency = Balances;
  231. type OnTransactionPayment = ();
  232. type TransactionBaseFee = TransactionBaseFee;
  233. type TransactionByteFee = TransactionByteFee;
  234. type WeightToFee = ();
  235. type FeeMultiplierUpdate = (); // FeeMultiplierUpdateHandler;
  236. }
  237. impl sudo::Trait for Runtime {
  238. type Event = Event;
  239. type Proposal = Call;
  240. }
  241. parameter_types! {
  242. pub const UncleGenerations: BlockNumber = 5;
  243. }
  244. impl authorship::Trait for Runtime {
  245. type FindAuthor = session::FindAccountFromAuthorIndex<Self, Babe>;
  246. type UncleGenerations = UncleGenerations;
  247. type FilterUncle = ();
  248. type EventHandler = Staking;
  249. }
  250. type SessionHandlers = (Grandpa, Babe, ImOnline);
  251. impl_opaque_keys! {
  252. pub struct SessionKeys {
  253. pub grandpa: Grandpa,
  254. pub babe: Babe,
  255. pub im_online: ImOnline,
  256. }
  257. }
  258. // NOTE: `SessionHandler` and `SessionKeys` are co-dependent: One key will be used for each handler.
  259. // The number and order of items in `SessionHandler` *MUST* be the same number and order of keys in
  260. // `SessionKeys`.
  261. // TODO: Introduce some structure to tie these together to make it a bit less of a footgun. This
  262. // should be easy, since OneSessionHandler trait provides the `Key` as an associated type. #2858
  263. parameter_types! {
  264. pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
  265. }
  266. impl session::Trait for Runtime {
  267. type OnSessionEnding = Staking;
  268. type SessionHandler = SessionHandlers;
  269. type ShouldEndSession = Babe;
  270. type Event = Event;
  271. type Keys = SessionKeys;
  272. type ValidatorId = AccountId;
  273. type ValidatorIdOf = staking::StashOf<Self>;
  274. type SelectInitialValidators = Staking;
  275. type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
  276. }
  277. impl session::historical::Trait for Runtime {
  278. type FullIdentification = staking::Exposure<AccountId, Balance>;
  279. type FullIdentificationOf = staking::ExposureOf<Runtime>;
  280. }
  281. srml_staking_reward_curve::build! {
  282. const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
  283. min_inflation: 0_025_000,
  284. max_inflation: 0_100_000,
  285. ideal_stake: 0_500_000,
  286. falloff: 0_050_000,
  287. max_piece_count: 40,
  288. test_precision: 0_005_000,
  289. );
  290. }
  291. parameter_types! {
  292. pub const SessionsPerEra: sr_staking_primitives::SessionIndex = 6;
  293. pub const BondingDuration: staking::EraIndex = 24 * 28;
  294. pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
  295. }
  296. impl staking::Trait for Runtime {
  297. type Currency = Balances;
  298. type Time = Timestamp;
  299. type CurrencyToVote = common::currency::CurrencyToVoteHandler;
  300. type RewardRemainder = ();
  301. type Event = Event;
  302. type Slash = (); // where to send the slashed funds.
  303. type Reward = (); // rewards are minted from the void
  304. type SessionsPerEra = SessionsPerEra;
  305. type BondingDuration = BondingDuration;
  306. type SessionInterface = Self;
  307. type RewardCurve = RewardCurve;
  308. }
  309. type SubmitTransaction = TransactionSubmitter<ImOnlineId, Runtime, UncheckedExtrinsic>;
  310. parameter_types! {
  311. pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_SLOTS as _;
  312. }
  313. impl im_online::Trait for Runtime {
  314. type AuthorityId = ImOnlineId;
  315. type Call = Call;
  316. type Event = Event;
  317. type SubmitTransaction = SubmitTransaction;
  318. type ReportUnresponsiveness = Offences;
  319. type SessionDuration = SessionDuration;
  320. }
  321. impl offences::Trait for Runtime {
  322. type Event = Event;
  323. type IdentificationTuple = session::historical::IdentificationTuple<Self>;
  324. type OnOffenceHandler = Staking;
  325. }
  326. impl authority_discovery::Trait for Runtime {
  327. type AuthorityId = BabeId;
  328. }
  329. parameter_types! {
  330. pub const WindowSize: BlockNumber = 101;
  331. pub const ReportLatency: BlockNumber = 1000;
  332. }
  333. impl finality_tracker::Trait for Runtime {
  334. type OnFinalizationStalled = Grandpa;
  335. type WindowSize = WindowSize;
  336. type ReportLatency = ReportLatency;
  337. }
  338. pub use forum;
  339. use governance::{council, election, proposals};
  340. use membership::members;
  341. use storage::{data_directory, data_object_storage_registry, data_object_type_registry};
  342. pub use versioned_store;
  343. use versioned_store_permissions;
  344. pub use content_working_group as content_wg;
  345. mod migration;
  346. use hiring;
  347. use minting;
  348. use recurringrewards;
  349. use roles::actors;
  350. use service_discovery::discovery;
  351. use stake;
  352. /// Alias for ContentId, used in various places.
  353. pub type ContentId = primitives::H256;
  354. impl versioned_store::Trait for Runtime {
  355. type Event = Event;
  356. }
  357. impl versioned_store_permissions::Trait for Runtime {
  358. type Credential = Credential;
  359. type CredentialChecker = (ContentWorkingGroupCredentials, SudoKeyHasAllCredentials);
  360. type CreateClassPermissionsChecker = ContentLeadOrSudoKeyCanCreateClasses;
  361. }
  362. // Credential Checker that gives the sudo key holder all credentials
  363. pub struct SudoKeyHasAllCredentials {}
  364. impl versioned_store_permissions::CredentialChecker<Runtime> for SudoKeyHasAllCredentials {
  365. fn account_has_credential(
  366. account: &AccountId,
  367. _credential: <Runtime as versioned_store_permissions::Trait>::Credential,
  368. ) -> bool {
  369. <sudo::Module<Runtime>>::key() == *account
  370. }
  371. }
  372. parameter_types! {
  373. pub const CurrentLeadCredential: Credential = 0;
  374. pub const AnyActiveCuratorCredential: Credential = 1;
  375. pub const AnyActiveChannelOwnerCredential: Credential = 2;
  376. pub const PrincipalIdMappingStartsAtCredential: Credential = 1000;
  377. }
  378. pub struct ContentWorkingGroupCredentials {}
  379. impl versioned_store_permissions::CredentialChecker<Runtime> for ContentWorkingGroupCredentials {
  380. fn account_has_credential(
  381. account: &AccountId,
  382. credential: <Runtime as versioned_store_permissions::Trait>::Credential,
  383. ) -> bool {
  384. match credential {
  385. // Credentials from 0..999 represents groups or more complex requirements
  386. // Current Lead if set
  387. credential if credential == CurrentLeadCredential::get() => {
  388. match <content_wg::Module<Runtime>>::ensure_lead_is_set() {
  389. Ok((_, lead)) => lead.role_account == *account,
  390. _ => false,
  391. }
  392. }
  393. // Any Active Curator
  394. credential if credential == AnyActiveCuratorCredential::get() => {
  395. // Look for a Curator with a matching role account
  396. for (_principal_id, principal) in <content_wg::PrincipalById<Runtime>>::enumerate()
  397. {
  398. if let content_wg::Principal::Curator(curator_id) = principal {
  399. let curator = <content_wg::CuratorById<Runtime>>::get(curator_id);
  400. if curator.role_account == *account
  401. && curator.stage == content_wg::CuratorRoleStage::Active
  402. {
  403. return true;
  404. }
  405. }
  406. }
  407. return false;
  408. }
  409. // Any Active Channel Owner
  410. credential if credential == AnyActiveChannelOwnerCredential::get() => {
  411. // Look for a ChannelOwner with a matching role account
  412. for (_principal_id, principal) in <content_wg::PrincipalById<Runtime>>::enumerate()
  413. {
  414. if let content_wg::Principal::ChannelOwner(channel_id) = principal {
  415. let channel = <content_wg::ChannelById<Runtime>>::get(channel_id);
  416. if channel.role_account == *account {
  417. return true; // should we also take publishing_status/curation_status into account ?
  418. }
  419. }
  420. }
  421. return false;
  422. }
  423. // mapping to workging group principal id
  424. n if n >= PrincipalIdMappingStartsAtCredential::get() => {
  425. <content_wg::Module<Runtime>>::account_has_credential(
  426. account,
  427. n - PrincipalIdMappingStartsAtCredential::get(),
  428. )
  429. }
  430. _ => false,
  431. }
  432. }
  433. }
  434. // Allow sudo key holder permission to create classes
  435. pub struct SudoKeyCanCreateClasses {}
  436. impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
  437. for SudoKeyCanCreateClasses
  438. {
  439. fn account_can_create_class_permissions(account: &AccountId) -> bool {
  440. <sudo::Module<Runtime>>::key() == *account
  441. }
  442. }
  443. // Impl this in the permissions module - can't be done here because
  444. // neither CreateClassPermissionsChecker or (X, Y) are local types?
  445. // impl<
  446. // T: versioned_store_permissions::Trait,
  447. // X: versioned_store_permissions::CreateClassPermissionsChecker<T>,
  448. // Y: versioned_store_permissions::CreateClassPermissionsChecker<T>,
  449. // > versioned_store_permissions::CreateClassPermissionsChecker<T> for (X, Y)
  450. // {
  451. // fn account_can_create_class_permissions(account: &T::AccountId) -> bool {
  452. // X::account_can_create_class_permissions(account)
  453. // || Y::account_can_create_class_permissions(account)
  454. // }
  455. // }
  456. pub struct ContentLeadOrSudoKeyCanCreateClasses {}
  457. impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
  458. for ContentLeadOrSudoKeyCanCreateClasses
  459. {
  460. fn account_can_create_class_permissions(account: &AccountId) -> bool {
  461. ContentLeadCanCreateClasses::account_can_create_class_permissions(account)
  462. || SudoKeyCanCreateClasses::account_can_create_class_permissions(account)
  463. }
  464. }
  465. // Allow content working group lead to create classes in content directory
  466. pub struct ContentLeadCanCreateClasses {}
  467. impl versioned_store_permissions::CreateClassPermissionsChecker<Runtime>
  468. for ContentLeadCanCreateClasses
  469. {
  470. fn account_can_create_class_permissions(account: &AccountId) -> bool {
  471. // get current lead id
  472. let maybe_current_lead_id = content_wg::CurrentLeadId::<Runtime>::get();
  473. if let Some(lead_id) = maybe_current_lead_id {
  474. let lead = content_wg::LeadById::<Runtime>::get(lead_id);
  475. lead.role_account == *account
  476. } else {
  477. false
  478. }
  479. }
  480. }
  481. impl hiring::Trait for Runtime {
  482. type OpeningId = u64;
  483. type ApplicationId = u64;
  484. type ApplicationDeactivatedHandler = (); // TODO - what needs to happen?
  485. type StakeHandlerProvider = hiring::Module<Self>;
  486. }
  487. impl minting::Trait for Runtime {
  488. type Currency = <Self as common::currency::GovernanceCurrency>::Currency;
  489. type MintId = u64;
  490. }
  491. impl recurringrewards::Trait for Runtime {
  492. type PayoutStatusHandler = (); // TODO - deal with successful and failed payouts
  493. type RecipientId = u64;
  494. type RewardRelationshipId = u64;
  495. }
  496. parameter_types! {
  497. pub const StakePoolId: [u8; 8] = *b"joystake";
  498. }
  499. impl stake::Trait for Runtime {
  500. type Currency = <Self as common::currency::GovernanceCurrency>::Currency;
  501. type StakePoolId = StakePoolId;
  502. type StakingEventsHandler = ContentWorkingGroupStakingEventHandler;
  503. type StakeId = u64;
  504. type SlashId = u64;
  505. }
  506. pub struct ContentWorkingGroupStakingEventHandler {}
  507. impl stake::StakingEventsHandler<Runtime> for ContentWorkingGroupStakingEventHandler {
  508. fn unstaked(
  509. stake_id: &<Runtime as stake::Trait>::StakeId,
  510. _unstaked_amount: stake::BalanceOf<Runtime>,
  511. remaining_imbalance: stake::NegativeImbalance<Runtime>,
  512. ) -> stake::NegativeImbalance<Runtime> {
  513. if !hiring::ApplicationIdByStakingId::<Runtime>::exists(stake_id) {
  514. // Stake not related to a staked role managed by the hiring module
  515. return remaining_imbalance;
  516. }
  517. let application_id = hiring::ApplicationIdByStakingId::<Runtime>::get(stake_id);
  518. if !content_wg::CuratorApplicationById::<Runtime>::exists(application_id) {
  519. // Stake not for a Curator
  520. return remaining_imbalance;
  521. }
  522. // Notify the Hiring module - is there a potential re-entrancy bug if
  523. // instant unstaking is occuring?
  524. hiring::Module::<Runtime>::unstaked(*stake_id);
  525. // Only notify working group module if non instantaneous unstaking occured
  526. if content_wg::UnstakerByStakeId::<Runtime>::exists(stake_id) {
  527. content_wg::Module::<Runtime>::unstaked(*stake_id);
  528. }
  529. // Determine member id of the curator
  530. let curator_application =
  531. content_wg::CuratorApplicationById::<Runtime>::get(application_id);
  532. let member_id = curator_application.member_id;
  533. // get member's profile
  534. let member_profile = membership::members::MemberProfile::<Runtime>::get(member_id).unwrap();
  535. // deposit funds to member's root_account
  536. // The application doesn't recorded the original source_account from which staked funds were
  537. // provided, so we don't really have another option at the moment.
  538. <Runtime as stake::Trait>::Currency::resolve_creating(
  539. &member_profile.root_account,
  540. remaining_imbalance,
  541. );
  542. stake::NegativeImbalance::<Runtime>::zero()
  543. }
  544. // Handler for slashing event
  545. fn slashed(
  546. _id: &<Runtime as stake::Trait>::StakeId,
  547. _slash_id: Option<<Runtime as stake::Trait>::SlashId>,
  548. _slashed_amount: stake::BalanceOf<Runtime>,
  549. _remaining_stake: stake::BalanceOf<Runtime>,
  550. remaining_imbalance: stake::NegativeImbalance<Runtime>,
  551. ) -> stake::NegativeImbalance<Runtime> {
  552. // Check if the stake is associated with a hired curator or applicant
  553. // if their stake goes below minimum required for the role,
  554. // they should get deactivated.
  555. // Since we don't currently implement any slash initiation in working group,
  556. // there is nothing to do for now.
  557. // Not interested in transfering the slashed amount anywhere for now,
  558. // so return it to next handler.
  559. remaining_imbalance
  560. }
  561. }
  562. impl content_wg::Trait for Runtime {
  563. type Event = Event;
  564. }
  565. impl common::currency::GovernanceCurrency for Runtime {
  566. type Currency = balances::Module<Self>;
  567. }
  568. impl governance::proposals::Trait for Runtime {
  569. type Event = Event;
  570. }
  571. impl governance::election::Trait for Runtime {
  572. type Event = Event;
  573. type CouncilElected = (Council,);
  574. }
  575. impl governance::council::Trait for Runtime {
  576. type Event = Event;
  577. type CouncilTermEnded = (CouncilElection,);
  578. }
  579. impl memo::Trait for Runtime {
  580. type Event = Event;
  581. }
  582. impl storage::data_object_type_registry::Trait for Runtime {
  583. type Event = Event;
  584. type DataObjectTypeId = u64;
  585. }
  586. impl storage::data_directory::Trait for Runtime {
  587. type Event = Event;
  588. type ContentId = ContentId;
  589. type SchemaId = u64;
  590. type Roles = LookupRoles;
  591. type IsActiveDataObjectType = DataObjectTypeRegistry;
  592. }
  593. impl storage::data_object_storage_registry::Trait for Runtime {
  594. type Event = Event;
  595. type DataObjectStorageRelationshipId = u64;
  596. type Roles = LookupRoles;
  597. type ContentIdExists = DataDirectory;
  598. }
  599. fn random_index(upper_bound: usize) -> usize {
  600. let seed = RandomnessCollectiveFlip::random_seed();
  601. let mut rand: u64 = 0;
  602. for offset in 0..8 {
  603. rand += (seed.as_ref()[offset] as u64) << offset;
  604. }
  605. (rand as usize) % upper_bound
  606. }
  607. pub struct LookupRoles {}
  608. impl roles::traits::Roles<Runtime> for LookupRoles {
  609. fn is_role_account(account_id: &<Runtime as system::Trait>::AccountId) -> bool {
  610. <actors::Module<Runtime>>::is_role_account(account_id)
  611. }
  612. fn account_has_role(
  613. account_id: &<Runtime as system::Trait>::AccountId,
  614. role: actors::Role,
  615. ) -> bool {
  616. <actors::Module<Runtime>>::account_has_role(account_id, role)
  617. }
  618. fn random_account_for_role(
  619. role: actors::Role,
  620. ) -> Result<<Runtime as system::Trait>::AccountId, &'static str> {
  621. let ids = <actors::AccountIdsByRole<Runtime>>::get(role);
  622. let live_ids: Vec<<Runtime as system::Trait>::AccountId> = ids
  623. .into_iter()
  624. .filter(|id| !<discovery::Module<Runtime>>::is_account_info_expired(id))
  625. .collect();
  626. if live_ids.len() == 0 {
  627. Err("no staked account found")
  628. } else {
  629. let index = random_index(live_ids.len());
  630. Ok(live_ids[index].clone())
  631. }
  632. }
  633. }
  634. impl members::Trait for Runtime {
  635. type Event = Event;
  636. type MemberId = u64;
  637. type PaidTermId = u64;
  638. type SubscriptionId = u64;
  639. type ActorId = u64;
  640. type InitialMembersBalance = InitialMembersBalance;
  641. }
  642. /*
  643. * Forum module integration
  644. *
  645. * ForumUserRegistry could have been implemented directly on
  646. * the membership module, and likewise ForumUser on Profile,
  647. * however this approach is more loosley coupled.
  648. *
  649. * Further exploration required to decide what the long
  650. * run convention should be.
  651. */
  652. /// Shim registry which will proxy ForumUserRegistry behaviour to the members module
  653. pub struct ShimMembershipRegistry {}
  654. impl forum::ForumUserRegistry<AccountId> for ShimMembershipRegistry {
  655. fn get_forum_user(id: &AccountId) -> Option<forum::ForumUser<AccountId>> {
  656. if members::Module::<Runtime>::is_member_account(id) {
  657. // For now we don't retreive the members profile since it is not used for anything,
  658. // but in the future we may need it to read out more
  659. // information possibly required to construct a
  660. // ForumUser.
  661. // Now convert member profile to a forum user
  662. Some(forum::ForumUser { id: id.clone() })
  663. } else {
  664. None
  665. }
  666. }
  667. }
  668. impl forum::Trait for Runtime {
  669. type Event = Event;
  670. type MembershipRegistry = ShimMembershipRegistry;
  671. }
  672. impl migration::Trait for Runtime {
  673. type Event = Event;
  674. }
  675. impl actors::Trait for Runtime {
  676. type Event = Event;
  677. type OnActorRemoved = HandleActorRemoved;
  678. }
  679. pub struct HandleActorRemoved {}
  680. impl actors::ActorRemoved<Runtime> for HandleActorRemoved {
  681. fn actor_removed(actor: &<Runtime as system::Trait>::AccountId) {
  682. Discovery::remove_account_info(actor);
  683. }
  684. }
  685. impl discovery::Trait for Runtime {
  686. type Event = Event;
  687. type Roles = LookupRoles;
  688. }
  689. construct_runtime!(
  690. pub enum Runtime where
  691. Block = Block,
  692. NodeBlock = opaque::Block,
  693. UncheckedExtrinsic = UncheckedExtrinsic
  694. {
  695. // Substrate
  696. System: system::{Module, Call, Storage, Config, Event},
  697. Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)},
  698. Timestamp: timestamp::{Module, Call, Storage, Inherent},
  699. Authorship: authorship::{Module, Call, Storage, Inherent},
  700. Indices: indices,
  701. Balances: balances,
  702. TransactionPayment: transaction_payment::{Module, Storage},
  703. Staking: staking::{default, OfflineWorker},
  704. Session: session::{Module, Call, Storage, Event, Config<T>},
  705. FinalityTracker: finality_tracker::{Module, Call, Inherent},
  706. Grandpa: grandpa::{Module, Call, Storage, Config, Event},
  707. ImOnline: im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
  708. AuthorityDiscovery: authority_discovery::{Module, Call, Config<T>},
  709. Offences: offences::{Module, Call, Storage, Event},
  710. RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},
  711. Sudo: sudo,
  712. // Joystream
  713. Proposals: proposals::{Module, Call, Storage, Event<T>, Config<T>},
  714. CouncilElection: election::{Module, Call, Storage, Event<T>, Config<T>},
  715. Council: council::{Module, Call, Storage, Event<T>, Config<T>},
  716. Memo: memo::{Module, Call, Storage, Event<T>},
  717. Members: members::{Module, Call, Storage, Event<T>, Config<T>},
  718. Forum: forum::{Module, Call, Storage, Event<T>, Config<T>},
  719. Migration: migration::{Module, Call, Storage, Event<T>},
  720. Actors: actors::{Module, Call, Storage, Event<T>, Config},
  721. DataObjectTypeRegistry: data_object_type_registry::{Module, Call, Storage, Event<T>, Config<T>},
  722. DataDirectory: data_directory::{Module, Call, Storage, Event<T>},
  723. DataObjectStorageRegistry: data_object_storage_registry::{Module, Call, Storage, Event<T>, Config<T>},
  724. Discovery: discovery::{Module, Call, Storage, Event<T>},
  725. VersionedStore: versioned_store::{Module, Call, Storage, Event<T>, Config},
  726. VersionedStorePermissions: versioned_store_permissions::{Module, Call, Storage},
  727. Stake: stake::{Module, Call, Storage},
  728. Minting: minting::{Module, Call, Storage},
  729. RecurringRewards: recurringrewards::{Module, Call, Storage},
  730. Hiring: hiring::{Module, Call, Storage},
  731. ContentWorkingGroup: content_wg::{Module, Call, Storage, Event<T>, Config<T>},
  732. }
  733. );
  734. /// The address format for describing accounts.
  735. pub type Address = <Indices as StaticLookup>::Source;
  736. /// Block header type as expected by this runtime.
  737. pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
  738. /// Block type as expected by this runtime.
  739. pub type Block = generic::Block<Header, UncheckedExtrinsic>;
  740. /// A Block signed with a Justification
  741. pub type SignedBlock = generic::SignedBlock<Block>;
  742. /// BlockId type as expected by this runtime.
  743. pub type BlockId = generic::BlockId<Block>;
  744. /// The SignedExtension to the basic transaction logic.
  745. pub type SignedExtra = (
  746. system::CheckVersion<Runtime>,
  747. system::CheckGenesis<Runtime>,
  748. system::CheckEra<Runtime>,
  749. system::CheckNonce<Runtime>,
  750. system::CheckWeight<Runtime>,
  751. transaction_payment::ChargeTransactionPayment<Runtime>,
  752. );
  753. /// Unchecked extrinsic type as expected by this runtime.
  754. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
  755. /// Extrinsic type that has already been checked.
  756. pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;
  757. /// Executive: handles dispatch to the various modules.
  758. pub type Executive =
  759. executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;
  760. impl_runtime_apis! {
  761. impl client_api::Core<Block> for Runtime {
  762. fn version() -> RuntimeVersion {
  763. VERSION
  764. }
  765. fn execute_block(block: Block) {
  766. Executive::execute_block(block)
  767. }
  768. fn initialize_block(header: &<Block as BlockT>::Header) {
  769. Executive::initialize_block(header)
  770. }
  771. }
  772. impl client_api::Metadata<Block> for Runtime {
  773. fn metadata() -> OpaqueMetadata {
  774. Runtime::metadata().into()
  775. }
  776. }
  777. impl block_builder_api::BlockBuilder<Block> for Runtime {
  778. fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
  779. Executive::apply_extrinsic(extrinsic)
  780. }
  781. fn finalize_block() -> <Block as BlockT>::Header {
  782. Executive::finalize_block()
  783. }
  784. fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
  785. data.create_extrinsics()
  786. }
  787. fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
  788. data.check_extrinsics(&block)
  789. }
  790. fn random_seed() -> <Block as BlockT>::Hash {
  791. RandomnessCollectiveFlip::random_seed()
  792. }
  793. }
  794. impl client_api::TaggedTransactionQueue<Block> for Runtime {
  795. fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {
  796. Executive::validate_transaction(tx)
  797. }
  798. }
  799. impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
  800. fn offchain_worker(number: NumberFor<Block>) {
  801. Executive::offchain_worker(number)
  802. }
  803. }
  804. impl fg_primitives::GrandpaApi<Block> for Runtime {
  805. fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> {
  806. Grandpa::grandpa_authorities()
  807. }
  808. }
  809. impl babe_primitives::BabeApi<Block> for Runtime {
  810. fn configuration() -> babe_primitives::BabeConfiguration {
  811. // The choice of `c` parameter (where `1 - c` represents the
  812. // probability of a slot being empty), is done in accordance to the
  813. // slot duration and expected target block time, for safely
  814. // resisting network delays of maximum two seconds.
  815. // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
  816. babe_primitives::BabeConfiguration {
  817. slot_duration: Babe::slot_duration(),
  818. epoch_length: EpochDuration::get(),
  819. c: PRIMARY_PROBABILITY,
  820. genesis_authorities: Babe::authorities(),
  821. randomness: Babe::randomness(),
  822. secondary_slots: true,
  823. }
  824. }
  825. }
  826. impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
  827. fn authorities() -> Vec<EncodedAuthorityId> {
  828. AuthorityDiscovery::authorities().into_iter()
  829. .map(|id| id.encode())
  830. .map(EncodedAuthorityId)
  831. .collect()
  832. }
  833. fn sign(payload: &Vec<u8>) -> Option<(EncodedSignature, EncodedAuthorityId)> {
  834. AuthorityDiscovery::sign(payload).map(|(sig, id)| {
  835. (EncodedSignature(sig.encode()), EncodedAuthorityId(id.encode()))
  836. })
  837. }
  838. fn verify(payload: &Vec<u8>, signature: &EncodedSignature, authority_id: &EncodedAuthorityId) -> bool {
  839. let signature = match BabeSignature::decode(&mut &signature.0[..]) {
  840. Ok(s) => s,
  841. _ => return false,
  842. };
  843. let authority_id = match BabeId::decode(&mut &authority_id.0[..]) {
  844. Ok(id) => id,
  845. _ => return false,
  846. };
  847. AuthorityDiscovery::verify(payload, signature, authority_id)
  848. }
  849. }
  850. impl system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
  851. fn account_nonce(account: AccountId) -> Index {
  852. System::account_nonce(account)
  853. }
  854. }
  855. impl substrate_session::SessionKeys<Block> for Runtime {
  856. fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
  857. let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string"));
  858. opaque::SessionKeys::generate(seed)
  859. }
  860. }
  861. }