workers.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 { Text } = require('@polkadot/types')
  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 storage provider's general purpose storage value from chain
  91. */
  92. async getWorkerStorageValue(id) {
  93. const value = await this.base.api.query.storageWorkingGroup.workerStorage(id)
  94. return new Text(this.base.api.registry, value).toString()
  95. }
  96. /*
  97. * Set storage provider's general purpose storage value on chain
  98. */
  99. async setWorkerStorageValue(value) {
  100. const id = this.base.storageProviderId
  101. const tx = this.base.api.tx.storageWorkingGroup.updateRoleStorage(id, value)
  102. const senderAccount = await this.storageProviderRoleAccount(id)
  103. return this.base.signAndSend(senderAccount, tx)
  104. }
  105. /*
  106. * Returns the the first found provider id with a role account or null if not found
  107. */
  108. async findProviderIdByRoleAccount(roleAccount) {
  109. const { ids, providers } = await this.getAllProviders()
  110. for (let i = 0; i < ids.length; i++) {
  111. const id = ids[i]
  112. if (providers[id].role_account_id.eq(roleAccount)) {
  113. return id
  114. }
  115. }
  116. return null
  117. }
  118. /*
  119. * Returns the set of ids and Worker instances of providers enrolled on the network
  120. */
  121. async getAllProviders() {
  122. const ids = []
  123. const providers = {}
  124. const entries = await this.base.api.query.storageWorkingGroup.workerById.entries()
  125. entries.forEach(([storageKey, worker]) => {
  126. const id = storageKey.args[0].toNumber()
  127. ids.push(id)
  128. providers[id] = worker
  129. })
  130. return { ids, providers }
  131. }
  132. async getLeadRoleAccount() {
  133. const currentLead = await this.base.api.query.storageWorkingGroup.currentLead()
  134. if (currentLead.isSome) {
  135. const leadWorkerId = currentLead.unwrap()
  136. const worker = await this.base.api.query.storageWorkingGroup.workerById(leadWorkerId)
  137. return worker.role_account_id
  138. }
  139. return null
  140. }
  141. // Helper methods below don't really belong in the colossus runtime api library.
  142. // They are only used by the dev-init command in the cli to setup a development environment
  143. /*
  144. * Add a new storage group opening using the lead account. Returns the
  145. * new opening id.
  146. */
  147. async devAddStorageOpening(info) {
  148. const openTx = this.devMakeAddOpeningTx('Worker', info)
  149. return this.devSubmitAddOpeningTx(openTx, await this.getLeadRoleAccount())
  150. }
  151. /*
  152. * Add a new storage working group lead opening using sudo account. Returns the
  153. * new opening id.
  154. */
  155. async devAddStorageLeadOpening(info) {
  156. const openTx = this.devMakeAddOpeningTx('Leader', info)
  157. const sudoTx = this.base.api.tx.sudo.sudo(openTx)
  158. return this.devSubmitAddOpeningTx(sudoTx, await this.base.identities.getSudoAccount())
  159. }
  160. /*
  161. * Constructs an addOpening tx of openingType
  162. */
  163. devMakeAddOpeningTx(openingType, info) {
  164. return this.base.api.tx.storageWorkingGroup.addOpening(
  165. 'CurrentBlock',
  166. {
  167. application_rationing_policy: {
  168. max_active_applicants: 1,
  169. },
  170. max_review_period_length: 10,
  171. // default values for everything else..
  172. },
  173. info || 'dev-opening',
  174. openingType
  175. )
  176. }
  177. /*
  178. * Submits a tx (expecting it to dispatch storageWorkingGroup.addOpening) and returns
  179. * the OpeningId from the resulting event.
  180. */
  181. async devSubmitAddOpeningTx(tx, senderAccount) {
  182. return this.base.signAndSendThenGetEventResult(senderAccount, tx, {
  183. module: 'storageWorkingGroup',
  184. event: 'OpeningAdded',
  185. type: 'OpeningId',
  186. index: 0,
  187. })
  188. }
  189. /*
  190. * Apply on an opening, returns the application id.
  191. */
  192. async devApplyOnOpening(openingId, memberId, memberAccount, roleAccount) {
  193. const applyTx = this.base.api.tx.storageWorkingGroup.applyOnOpening(
  194. memberId,
  195. openingId,
  196. roleAccount,
  197. null,
  198. null,
  199. `colossus-${memberId}`
  200. )
  201. return this.base.signAndSendThenGetEventResult(memberAccount, applyTx, {
  202. module: 'storageWorkingGroup',
  203. event: 'AppliedOnOpening',
  204. type: 'ApplicationId',
  205. index: 1,
  206. })
  207. }
  208. /*
  209. * Move lead opening to review state using sudo account
  210. */
  211. async devBeginLeadOpeningReview(openingId) {
  212. const beginReviewTx = this.devMakeBeginOpeningReviewTx(openingId)
  213. const sudoTx = this.base.api.tx.sudo.sudo(beginReviewTx)
  214. return this.base.signAndSend(await this.base.identities.getSudoAccount(), sudoTx)
  215. }
  216. /*
  217. * Move a storage opening to review state using lead account
  218. */
  219. async devBeginStorageOpeningReview(openingId) {
  220. const beginReviewTx = this.devMakeBeginOpeningReviewTx(openingId)
  221. return this.base.signAndSend(await this.getLeadRoleAccount(), beginReviewTx)
  222. }
  223. /*
  224. * Constructs a beingApplicantReview tx for openingId, which puts an opening into the review state
  225. */
  226. devMakeBeginOpeningReviewTx(openingId) {
  227. return this.base.api.tx.storageWorkingGroup.beginApplicantReview(openingId)
  228. }
  229. /*
  230. * Fill a lead opening, return the assigned worker id, using the sudo account
  231. */
  232. async devFillLeadOpening(openingId, applicationId) {
  233. const fillTx = this.devMakeFillOpeningTx(openingId, applicationId)
  234. const sudoTx = this.base.api.tx.sudo.sudo(fillTx)
  235. const filled = await this.devSubmitFillOpeningTx(await this.base.identities.getSudoAccount(), sudoTx)
  236. return getWorkerIdFromApplicationIdToWorkerIdMap(filled, applicationId)
  237. }
  238. /*
  239. * Fill a storage opening, return the assigned worker id, using the lead account
  240. */
  241. async devFillStorageOpening(openingId, applicationId) {
  242. const fillTx = this.devMakeFillOpeningTx(openingId, applicationId)
  243. const filled = await this.devSubmitFillOpeningTx(await this.getLeadRoleAccount(), fillTx)
  244. return getWorkerIdFromApplicationIdToWorkerIdMap(filled, applicationId)
  245. }
  246. /*
  247. * Constructs a FillOpening transaction
  248. */
  249. devMakeFillOpeningTx(openingId, applicationId) {
  250. return this.base.api.tx.storageWorkingGroup.fillOpening(openingId, [applicationId], null)
  251. }
  252. /*
  253. * Dispatches a fill opening tx and returns a map of the application id to their new assigned worker ids.
  254. */
  255. async devSubmitFillOpeningTx(senderAccount, tx) {
  256. return this.base.signAndSendThenGetEventResult(senderAccount, tx, {
  257. module: 'storageWorkingGroup',
  258. event: 'OpeningFilled',
  259. type: 'ApplicationIdToWorkerIdMap',
  260. index: 1,
  261. })
  262. }
  263. }
  264. module.exports = {
  265. WorkersApi,
  266. }