index.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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:base')
  20. const { registerJoystreamTypes } = require('@joystream/types')
  21. const { ApiPromise, WsProvider } = require('@polkadot/api')
  22. const { IdentitiesApi } = require('@joystream/storage-runtime-api/identities')
  23. const { BalancesApi } = require('@joystream/storage-runtime-api/balances')
  24. const { WorkersApi } = require('@joystream/storage-runtime-api/workers')
  25. const { AssetsApi } = require('@joystream/storage-runtime-api/assets')
  26. const { DiscoveryApi } = require('@joystream/storage-runtime-api/discovery')
  27. const { SystemApi } = require('@joystream/storage-runtime-api/system')
  28. const AsyncLock = require('async-lock')
  29. const { newExternallyControlledPromise } = require('@joystream/storage-utils/externalPromise')
  30. /*
  31. * Initialize runtime (substrate) API and keyring.
  32. */
  33. class RuntimeApi {
  34. static async create(options) {
  35. const runtimeApi = new RuntimeApi()
  36. await runtimeApi.init(options || {})
  37. return runtimeApi
  38. }
  39. async init(options) {
  40. debug('Init')
  41. options = options || {}
  42. // Register joystream types
  43. registerJoystreamTypes()
  44. const provider = new WsProvider(options.provider_url || 'ws://localhost:9944')
  45. // Create the API instrance
  46. this.api = await ApiPromise.create({ provider })
  47. this.asyncLock = new AsyncLock()
  48. // Keep track locally of account nonces.
  49. this.nonces = {}
  50. // The storage provider id to use
  51. this.storageProviderId = parseInt(options.storageProviderId) // u64 instead ?
  52. // Ok, create individual APIs
  53. this.identities = await IdentitiesApi.create(this, {
  54. accountFile: options.account_file,
  55. passphrase: options.passphrase,
  56. canPromptForPassphrase: options.canPromptForPassphrase,
  57. })
  58. this.balances = await BalancesApi.create(this)
  59. this.workers = await WorkersApi.create(this)
  60. this.assets = await AssetsApi.create(this)
  61. this.discovery = await DiscoveryApi.create(this)
  62. this.system = await SystemApi.create(this)
  63. }
  64. disconnect() {
  65. this.api.disconnect()
  66. }
  67. executeWithAccountLock(accountId, func) {
  68. return this.asyncLock.acquire(`${accountId}`, func)
  69. }
  70. static matchingEvents(subscribed, events) {
  71. if (!events.length) return []
  72. const filtered = events.filter((record) => {
  73. const { event /*phase*/ } = record
  74. // Show what we are busy with
  75. // debug(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`)
  76. // debug(`\t\t${event.meta.documentation.toString()}`)
  77. // Skip events we're not interested in.
  78. const matching = subscribed.filter((value) => {
  79. return event.section === value[0] && event.method === value[1]
  80. })
  81. return matching.length > 0
  82. })
  83. const mapped = filtered.map((record) => {
  84. const { event } = record
  85. const types = event.typeDef
  86. // Loop through each of the parameters, displaying the type and data
  87. const payload = {}
  88. event.data.forEach((data, index) => {
  89. // debug(`\t${types[index].type}: ${data.toString()}`)
  90. payload[types[index].type] = data
  91. })
  92. const fullName = `${event.section}.${event.method}`
  93. return [fullName, payload]
  94. })
  95. debug('Events', JSON.stringify(mapped))
  96. return mapped
  97. }
  98. // Returns a function that takes events from transaction lifecycle updates
  99. // that look for matching events and makes a callback and absorbs any expections
  100. // raised by the callback to ensure we continue to process the complete
  101. // transaction lifecyle.
  102. static makeEventsHandler(subscribed, callback) {
  103. return function eventsHandler(events) {
  104. try {
  105. if (subscribed && callback) {
  106. const matched = RuntimeApi.matchingEvents(subscribed, events)
  107. if (matched.length) {
  108. callback(matched)
  109. }
  110. }
  111. } catch (err) {
  112. debug(`Error handling events ${err.stack}`)
  113. }
  114. }
  115. }
  116. /*
  117. * signAndSend() with nonce tracking, to enable concurrent sending of transacctions
  118. * so that they can be included in the same block. Allows you to use the accountId instead
  119. * of the key, without requiring an external Signer configured on the underlying ApiPromie
  120. *
  121. * If the subscribed events are given, and a callback as well, then the
  122. * callback is invoked with matching events.
  123. */
  124. async signAndSend(accountId, tx, subscribed, callback) {
  125. accountId = this.identities.keyring.encodeAddress(accountId)
  126. // Key must be unlocked
  127. const fromKey = this.identities.keyring.getPair(accountId)
  128. if (fromKey.isLocked) {
  129. throw new Error('Must unlock key before using it to sign!')
  130. }
  131. // Promise that will be resolved when the submitted transaction is finalized
  132. // it will be rejected if the transaction is rejected by the node.
  133. const finalizedPromise = newExternallyControlledPromise()
  134. // function assigned when transaction is successfully submitted. Call
  135. // it to unsubsribe from events.
  136. let unsubscribe
  137. const handleEvents = RuntimeApi.makeEventsHandler(subscribed, callback)
  138. const handleTxUpdates = ({ events = [], status }) => {
  139. // when handling tx life cycle we cannot detect api disconnect and could be waiting
  140. // for events for ever!
  141. handleEvents(events)
  142. if (status.isFinalized) {
  143. // transaction was included in block (finalized)
  144. // resolve with the transaction hash
  145. unsubscribe()
  146. finalizedPromise.resolve(status.asFinalized)
  147. } else if (status.isFuture) {
  148. // This can happen if the code is incorrect, but also in a scenario where a joystream-node
  149. // lost connectivity, the storage node submitted a few transactions, and incremented the nonce.
  150. // The joystream-node later was restarted and storage-node continues using cached nonce.
  151. // Can we detect api disconnect and reset nonce?
  152. debug(`== Error: Submitted transaction with future nonce ==`)
  153. delete this.nonces[accountId]
  154. finalizedPromise.reject('Future Tx Nonce')
  155. }
  156. }
  157. // synchronize access to nonce
  158. await this.executeWithAccountLock(accountId, async () => {
  159. // Try to get the next nonce to use
  160. let nonce = this.nonces[accountId]
  161. // Remember if we read a previously saved nonce
  162. const nonceWasCached = nonce !== undefined
  163. // If it wasn't cached read it from chain and save it
  164. nonce = this.nonces[accountId] = nonce || (await this.api.query.system.accountNonce(accountId))
  165. try {
  166. unsubscribe = await tx.sign(fromKey, { nonce }).send(handleTxUpdates)
  167. // transaction submitted successfully, increment and save nonce,
  168. // unless it was reset in handleTxCycle()
  169. if (this.nonces[accountId] !== undefined) {
  170. this.nonces[accountId] = nonce.addn(1)
  171. }
  172. } catch (err) {
  173. debug('Transaction Rejected:', err.toString())
  174. // Error here could be simply bad input to the transactions. It may also
  175. // be due to bad nonce, resulting in attempt to replace transactions with same nonce
  176. // either that were future transactions,
  177. // or because of stale nonces (this will happen while a joystream-node is far behind in syncing because
  178. // we will read the nonce from chain and by the time we submit the transaction, the node would have fetched a few more blocks
  179. // where the nonce of the account might have changed to a higher value)
  180. // Occasionally the storage node operator will use their role account from another application
  181. // to send transactions to manage their role which will change the nonce, and due to a race condition
  182. // between reading the nonce from chain, and signing a transaction, the selected nonce may become stale.
  183. // All we can do is reset the nonce and re-read it from chain on next tx submit attempt.
  184. // The storage node will eventually recover.
  185. if (nonceWasCached) {
  186. delete this.nonces[accountId]
  187. }
  188. finalizedPromise.reject(err)
  189. }
  190. })
  191. return finalizedPromise.promise
  192. }
  193. /*
  194. * Sign and send a transaction expect event from
  195. * module and return eventProperty from the event.
  196. */
  197. async signAndSendThenGetEventResult(senderAccountId, tx, { eventModule, eventName, eventProperty }) {
  198. // event from a module,
  199. const subscribed = [[eventModule, eventName]]
  200. // TODO: rewrite this method to async-await style
  201. // eslint-disable-next-line no-async-promise-executor
  202. return new Promise(async (resolve, reject) => {
  203. try {
  204. await this.signAndSend(senderAccountId, tx, subscribed, (events) => {
  205. events.forEach((event) => {
  206. // fix - we may not necessarily want the first event
  207. // if there are multiple events emitted,
  208. resolve(event[1][eventProperty])
  209. })
  210. })
  211. } catch (err) {
  212. reject(err)
  213. }
  214. })
  215. }
  216. }
  217. module.exports = {
  218. RuntimeApi,
  219. }