index.js 9.8 KB

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