index.js 11 KB

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