index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. account_file: 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. /*
  71. * Wait for an event. Filters out any events that don't match the module and
  72. * event name.
  73. *
  74. * The result of the Promise is an array containing first the full event
  75. * name, and then the event fields as an object.
  76. */
  77. async waitForEvent(module, name) {
  78. return this.waitForEvents([[module, name]])
  79. }
  80. static matchingEvents(subscribed, events) {
  81. debug(`Number of events: ${events.length} subscribed to ${subscribed}`)
  82. const filtered = events.filter((record) => {
  83. const { event, phase } = record
  84. // Show what we are busy with
  85. debug(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`)
  86. debug(`\t\t${event.meta.documentation.toString()}`)
  87. // Skip events we're not interested in.
  88. const matching = subscribed.filter((value) => {
  89. return event.section === value[0] && event.method === value[1]
  90. })
  91. return matching.length > 0
  92. })
  93. debug(`Filtered: ${filtered.length}`)
  94. const mapped = filtered.map((record) => {
  95. const { event } = record
  96. const types = event.typeDef
  97. // Loop through each of the parameters, displaying the type and data
  98. const payload = {}
  99. event.data.forEach((data, index) => {
  100. debug(`\t\t\t${types[index].type}: ${data.toString()}`)
  101. payload[types[index].type] = data
  102. })
  103. const fullName = `${event.section}.${event.method}`
  104. return [fullName, payload]
  105. })
  106. debug('Mapped', mapped)
  107. return mapped
  108. }
  109. /*
  110. * Same as waitForEvent, but filter on multiple events. The parameter is an
  111. * array of arrays containing module and name. Calling waitForEvent is
  112. * identical to calling this with [[module, name]].
  113. *
  114. * Returns the first matched event *only*.
  115. */
  116. async waitForEvents(subscribed) {
  117. return new Promise((resolve) => {
  118. this.api.query.system.events((events) => {
  119. const matches = RuntimeApi.matchingEvents(subscribed, events)
  120. if (matches && matches.length) {
  121. resolve(matches)
  122. }
  123. })
  124. })
  125. }
  126. /*
  127. * Nonce-aware signAndSend(). Also allows you to use the accountId instead
  128. * of the key, making calls a little simpler. Will lock to prevent concurrent
  129. * calls so correct nonce is used.
  130. *
  131. * If the subscribed events are given, and a callback as well, then the
  132. * callback is invoked with matching events.
  133. */
  134. async signAndSend(accountId, tx, attempts, subscribed, callback) {
  135. accountId = this.identities.keyring.encodeAddress(accountId)
  136. // Key must be unlocked
  137. const fromKey = this.identities.keyring.getPair(accountId)
  138. if (fromKey.isLocked) {
  139. throw new Error('Must unlock key before using it to sign!')
  140. }
  141. const finalizedPromise = newExternallyControlledPromise()
  142. await this.executeWithAccountLock(accountId, async () => {
  143. // Try to get the next nonce to use
  144. let nonce = this.nonces[accountId]
  145. let incrementNonce = () => {
  146. // only increment once
  147. incrementNonce = () => {
  148. /* turn it into a no-op */
  149. }
  150. nonce = nonce.addn(1)
  151. this.nonces[accountId] = nonce
  152. }
  153. // If the nonce isn't available, get it from chain.
  154. if (!nonce) {
  155. // current nonce
  156. // TODO: possible race condition here found by the linter
  157. // eslint-disable-next-line require-atomic-updates
  158. nonce = await this.api.query.system.accountNonce(accountId)
  159. debug(`Got nonce for ${accountId} from chain: ${nonce}`)
  160. }
  161. return new Promise((resolve, reject) => {
  162. debug('Signing and sending tx')
  163. // send(statusUpdates) returns a function for unsubscribing from status updates
  164. const unsubscribe = tx
  165. .sign(fromKey, { nonce })
  166. .send(({ events = [], status }) => {
  167. debug(`TX status: ${status.type}`)
  168. // Whatever events we get, process them if there's someone interested.
  169. // It is critical that this event handling doesn't prevent
  170. try {
  171. if (subscribed && callback) {
  172. const matched = RuntimeApi.matchingEvents(subscribed, events)
  173. debug('Matching events:', matched)
  174. if (matched.length) {
  175. callback(matched)
  176. }
  177. }
  178. } catch (err) {
  179. debug(`Error handling events ${err.stack}`)
  180. }
  181. // We want to release lock as early as possible, sometimes Ready status
  182. // doesn't occur, so we do it on Broadcast instead
  183. if (status.isReady) {
  184. debug('TX Ready.')
  185. incrementNonce()
  186. resolve(unsubscribe) // releases lock
  187. } else if (status.isBroadcast) {
  188. debug('TX Broadcast.')
  189. incrementNonce()
  190. resolve(unsubscribe) // releases lock
  191. } else if (status.isFinalized) {
  192. debug('TX Finalized.')
  193. finalizedPromise.resolve(status)
  194. } else if (status.isFuture) {
  195. // comes before ready.
  196. // does that mean it will remain in mempool or in api internal queue?
  197. // nonce was set in the future. Treating it as an error for now.
  198. debug('TX Future!')
  199. // nonce is likely out of sync, delete it so we reload it from chain on next attempt
  200. delete this.nonces[accountId]
  201. const err = new Error('transaction nonce set in future')
  202. finalizedPromise.reject(err)
  203. reject(err)
  204. }
  205. /* why don't we see these status updates on local devchain (single node)
  206. isUsurped
  207. isBroadcast
  208. isDropped
  209. isInvalid
  210. */
  211. })
  212. .catch((err) => {
  213. // 1014 error: Most likely you are sending transaction with the same nonce,
  214. // so it assumes you want to replace existing one, but the priority is too low to replace it (priority = fee = len(encoded_transaction) currently)
  215. // Remember this can also happen if in the past we sent a tx with a future nonce, and the current nonce
  216. // now matches it.
  217. if (err) {
  218. const errstr = err.toString()
  219. // not the best way to check error code.
  220. // https://github.com/polkadot-js/api/blob/master/packages/rpc-provider/src/coder/index.ts#L52
  221. if (
  222. errstr.indexOf('Error: 1014:') < 0 && // low priority
  223. errstr.indexOf('Error: 1010:') < 0
  224. ) {
  225. // bad transaction
  226. // Error but not nonce related. (bad arguments maybe)
  227. debug('TX error', err)
  228. } else {
  229. // nonce is likely out of sync, delete it so we reload it from chain on next attempt
  230. delete this.nonces[accountId]
  231. }
  232. }
  233. finalizedPromise.reject(err)
  234. // releases lock
  235. reject(err)
  236. })
  237. })
  238. })
  239. // when does it make sense to manyally unsubscribe?
  240. // at this point unsubscribe.then and unsubscribe.catch have been deleted
  241. // unsubscribe() // don't unsubscribe if we want to wait for additional status
  242. // updates to know when the tx has been finalized
  243. return finalizedPromise.promise
  244. }
  245. /*
  246. * Sign and send a transaction expect event from
  247. * module and return eventProperty from the event.
  248. */
  249. async signAndSendThenGetEventResult(senderAccountId, tx, { eventModule, eventName, eventProperty }) {
  250. // event from a module,
  251. const subscribed = [[eventModule, eventName]]
  252. // TODO: rewrite this method to async-await style
  253. // eslint-disable-next-line no-async-promise-executor
  254. return new Promise(async (resolve, reject) => {
  255. try {
  256. await this.signAndSend(senderAccountId, tx, 1, subscribed, (events) => {
  257. events.forEach((event) => {
  258. // fix - we may not necessarily want the first event
  259. // if there are multiple events emitted,
  260. resolve(event[1][eventProperty])
  261. })
  262. })
  263. } catch (err) {
  264. reject(err)
  265. }
  266. })
  267. }
  268. }
  269. module.exports = {
  270. RuntimeApi,
  271. }