workers.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. /*
  22. * Add worker related functionality to the substrate API.
  23. */
  24. class WorkersApi {
  25. static async create (base) {
  26. const ret = new WorkersApi()
  27. ret.base = base
  28. await ret.init()
  29. return ret
  30. }
  31. async init () {
  32. debug('Init')
  33. }
  34. /*
  35. * Check whether the given account and id represent an active storage provider
  36. */
  37. async isRoleAccountOfStorageProvider (storageProviderId, roleAccountId) {
  38. storageProviderId = new BN(storageProviderId)
  39. roleAccountId = this.base.identities.keyring.decodeAddress(roleAccountId)
  40. const worker = await this.storageWorkerByProviderId(storageProviderId)
  41. return worker && worker.role_account.eq(roleAccountId)
  42. }
  43. async isStorageProvider (storageProviderId) {
  44. const worker = await this.storageWorkerByProviderId(storageProviderId)
  45. return worker !== null
  46. }
  47. async storageWorkerByProviderId (storageProviderId) {
  48. storageProviderId = new BN(storageProviderId)
  49. const nextWorkerId = await this.base.api.query.storageWorkingGroup.nextWorkerId()
  50. if (storageProviderId.gte(nextWorkerId)) {
  51. return null
  52. }
  53. const workerEntry = await this.base.api.query.storageWorkingGroup.workerById(storageProviderId)
  54. return workerEntry[0]
  55. }
  56. async storageProviderRoleAccount (storageProviderId) {
  57. const worker = await this.storageWorkerByProviderId(storageProviderId)
  58. if (worker == null) {
  59. throw new Error('Storage Provider Does Not Exist')
  60. } else {
  61. return worker.role_account
  62. }
  63. }
  64. async getAllProviders () {
  65. const workerEntries = await this.base.api.query.storageWorkingGroup.workerById()
  66. return workerEntries[0] // keys
  67. }
  68. }
  69. module.exports = {
  70. WorkersApi
  71. }