workers.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict'
  19. const debug = require('debug')('joystream:runtime:roles')
  20. const BN = require('bn.js')
  21. const { Worker } = require('@joystream/types/working-group')
  22. /*
  23. * Finds assigned worker id corresponding to the application id from the resulting
  24. * ApplicationIdToWorkerIdMap map in the OpeningFilled event. Expects map to
  25. * contain at least one entry.
  26. */
  27. function getWorkerIdFromApplicationIdToWorkerIdMap(filledMap, applicationId) {
  28. if (filledMap.size === 0) {
  29. throw new Error('Expected opening to be filled!')
  30. }
  31. let ourApplicationIdKey
  32. for (const key of filledMap.keys()) {
  33. if (key.eq(applicationId)) {
  34. ourApplicationIdKey = key
  35. break
  36. }
  37. }
  38. if (!ourApplicationIdKey) {
  39. throw new Error('Expected application id to have been filled!')
  40. }
  41. const workerId = filledMap.get(ourApplicationIdKey)
  42. return workerId
  43. }
  44. /*
  45. * Add worker related functionality to the substrate API.
  46. */
  47. class WorkersApi {
  48. static async create(base) {
  49. const ret = new WorkersApi()
  50. ret.base = base
  51. await ret.init()
  52. return ret
  53. }
  54. // eslint-disable-next-line class-methods-use-this, require-await
  55. async init() {
  56. debug('Init')
  57. }
  58. /*
  59. * Check whether the given account and id represent an enrolled storage provider
  60. */
  61. async isRoleAccountOfStorageProvider(storageProviderId, roleAccountId) {
  62. const id = new BN(storageProviderId)
  63. const roleAccount = this.base.identities.keyring.decodeAddress(roleAccountId)
  64. const providerAccount = await this.storageProviderRoleAccount(id)
  65. return providerAccount && providerAccount.eq(roleAccount)
  66. }
  67. /*
  68. * Returns true if the provider id is enrolled
  69. */
  70. async isStorageProvider(storageProviderId) {
  71. const worker = await this.storageWorkerByProviderId(storageProviderId)
  72. return worker !== null
  73. }
  74. /*
  75. * Returns a provider's role account or null if provider doesn't exist
  76. */
  77. async storageProviderRoleAccount(storageProviderId) {
  78. const worker = await this.storageWorkerByProviderId(storageProviderId)
  79. return worker ? worker.role_account_id : null
  80. }
  81. /*
  82. * Returns a Worker instance or null if provider does not exist
  83. */
  84. async storageWorkerByProviderId(storageProviderId) {
  85. const id = new BN(storageProviderId)
  86. const { providers } = await this.getAllProviders()
  87. return providers[id.toNumber()] || null
  88. }
  89. /*
  90. * Returns the the first found provider id with a role account or null if not found
  91. */
  92. async findProviderIdByRoleAccount(roleAccount) {
  93. const { ids, providers } = await this.getAllProviders()
  94. for (let i = 0; i < ids.length; i++) {
  95. const id = ids[i]
  96. if (providers[id].role_account_id.eq(roleAccount)) {
  97. return id
  98. }
  99. }
  100. return null
  101. }
  102. /*
  103. * Returns the set of ids and Worker instances of providers enrolled on the network
  104. */
  105. async getAllProviders() {
  106. const ids = []
  107. const providers = {}
  108. const entries = await this.base.api.query.storageWorkingGroup.workerById.entries()
  109. entries.forEach(([storageKey, worker]) => {
  110. const id = storageKey.args[0].toNumber()
  111. ids.push(id)
  112. providers[id] = worker
  113. })
  114. return { ids, providers }
  115. }
  116. async getLeadRoleAccount() {
  117. const currentLead = await this.base.api.query.storageWorkingGroup.currentLead()
  118. if (currentLead.isSome) {
  119. const leadWorkerId = currentLead.unwrap()
  120. const worker = await this.base.api.query.storageWorkingGroup.workerById(leadWorkerId)
  121. return worker.role_account_id
  122. }
  123. return null
  124. }
  125. // Helper methods below don't really belong in the colossus runtime api library.
  126. // They are only used by the dev-init command in the cli to setup a development environment
  127. /*
  128. * Add a new storage group opening using the lead account. Returns the
  129. * new opening id.
  130. */
  131. async devAddStorageOpening(info) {
  132. const openTx = this.devMakeAddOpeningTx('Worker', info)
  133. return this.devSubmitAddOpeningTx(openTx, await this.getLeadRoleAccount())
  134. }
  135. /*
  136. * Add a new storage working group lead opening using sudo account. Returns the
  137. * new opening id.
  138. */
  139. async devAddStorageLeadOpening(info) {
  140. const openTx = this.devMakeAddOpeningTx('Leader', info)
  141. const sudoTx = this.base.api.tx.sudo.sudo(openTx)
  142. return this.devSubmitAddOpeningTx(sudoTx, await this.base.identities.getSudoAccount())
  143. }
  144. /*
  145. * Constructs an addOpening tx of openingType
  146. */
  147. devMakeAddOpeningTx(openingType, info) {
  148. return this.base.api.tx.storageWorkingGroup.addOpening(
  149. 'CurrentBlock',
  150. {
  151. application_rationing_policy: {
  152. max_active_applicants: 1,
  153. },
  154. max_review_period_length: 10,
  155. // default values for everything else..
  156. },
  157. info || 'dev-opening',
  158. openingType
  159. )
  160. }
  161. /*
  162. * Submits a tx (expecting it to dispatch storageWorkingGroup.addOpening) and returns
  163. * the OpeningId from the resulting event.
  164. */
  165. async devSubmitAddOpeningTx(tx, senderAccount) {
  166. return this.base.signAndSendThenGetEventResult(senderAccount, tx, {
  167. module: 'storageWorkingGroup',
  168. event: 'OpeningAdded',
  169. type: 'OpeningId',
  170. index: 0,
  171. })
  172. }
  173. /*
  174. * Apply on an opening, returns the application id.
  175. */
  176. async devApplyOnOpening(openingId, memberId, memberAccount, roleAccount) {
  177. const applyTx = this.base.api.tx.storageWorkingGroup.applyOnOpening(
  178. memberId,
  179. openingId,
  180. roleAccount,
  181. null,
  182. null,
  183. `colossus-${memberId}`
  184. )
  185. return this.base.signAndSendThenGetEventResult(memberAccount, applyTx, {
  186. module: 'storageWorkingGroup',
  187. event: 'AppliedOnOpening',
  188. type: 'ApplicationId',
  189. index: 1,
  190. })
  191. }
  192. /*
  193. * Move lead opening to review state using sudo account
  194. */
  195. async devBeginLeadOpeningReview(openingId) {
  196. const beginReviewTx = this.devMakeBeginOpeningReviewTx(openingId)
  197. const sudoTx = this.base.api.tx.sudo.sudo(beginReviewTx)
  198. return this.base.signAndSend(await this.base.identities.getSudoAccount(), sudoTx)
  199. }
  200. /*
  201. * Move a storage opening to review state using lead account
  202. */
  203. async devBeginStorageOpeningReview(openingId) {
  204. const beginReviewTx = this.devMakeBeginOpeningReviewTx(openingId)
  205. return this.base.signAndSend(await this.getLeadRoleAccount(), beginReviewTx)
  206. }
  207. /*
  208. * Constructs a beingApplicantReview tx for openingId, which puts an opening into the review state
  209. */
  210. devMakeBeginOpeningReviewTx(openingId) {
  211. return this.base.api.tx.storageWorkingGroup.beginApplicantReview(openingId)
  212. }
  213. /*
  214. * Fill a lead opening, return the assigned worker id, using the sudo account
  215. */
  216. async devFillLeadOpening(openingId, applicationId) {
  217. const fillTx = this.devMakeFillOpeningTx(openingId, applicationId)
  218. const sudoTx = this.base.api.tx.sudo.sudo(fillTx)
  219. const filled = await this.devSubmitFillOpeningTx(await this.base.identities.getSudoAccount(), sudoTx)
  220. return getWorkerIdFromApplicationIdToWorkerIdMap(filled, applicationId)
  221. }
  222. /*
  223. * Fill a storage opening, return the assigned worker id, using the lead account
  224. */
  225. async devFillStorageOpening(openingId, applicationId) {
  226. const fillTx = this.devMakeFillOpeningTx(openingId, applicationId)
  227. const filled = await this.devSubmitFillOpeningTx(await this.getLeadRoleAccount(), fillTx)
  228. return getWorkerIdFromApplicationIdToWorkerIdMap(filled, applicationId)
  229. }
  230. /*
  231. * Constructs a FillOpening transaction
  232. */
  233. devMakeFillOpeningTx(openingId, applicationId) {
  234. return this.base.api.tx.storageWorkingGroup.fillOpening(openingId, [applicationId], null)
  235. }
  236. /*
  237. * Dispatches a fill opening tx and returns a map of the application id to their new assigned worker ids.
  238. */
  239. async devSubmitFillOpeningTx(senderAccount, tx) {
  240. return this.base.signAndSendThenGetEventResult(senderAccount, tx, {
  241. module: 'storageWorkingGroup',
  242. event: 'OpeningFilled',
  243. type: 'ApplicationIdToWorkerIdMap',
  244. index: 1,
  245. })
  246. }
  247. }
  248. module.exports = {
  249. WorkersApi,
  250. }