index.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. const 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. const unsubscribe = tx
  159. .sign(from_key, { nonce })
  160. .send(({ events = [], status }) => {
  161. debug(`TX status: ${status.type}`)
  162. // Whatever events we get, process them if there's someone interested.
  163. // It is critical that this event handling doesn't prevent
  164. try {
  165. if (subscribed && callback) {
  166. const matched = this._matchingEvents(subscribed, events)
  167. debug('Matching events:', matched)
  168. if (matched.length) {
  169. callback(matched)
  170. }
  171. }
  172. } catch (err) {
  173. debug(`Error handling events ${err.stack}`)
  174. }
  175. // We want to release lock as early as possible, sometimes Ready status
  176. // doesn't occur, so we do it on Broadcast instead
  177. if (status.isReady) {
  178. debug('TX Ready.')
  179. incrementNonce()
  180. resolve(unsubscribe) // releases lock
  181. } else if (status.isBroadcast) {
  182. debug('TX Broadcast.')
  183. incrementNonce()
  184. resolve(unsubscribe) // releases lock
  185. } else if (status.isFinalized) {
  186. debug('TX Finalized.')
  187. finalizedPromise.resolve(status)
  188. } else if (status.isFuture) {
  189. // comes before ready.
  190. // does that mean it will remain in mempool or in api internal queue?
  191. // nonce was set in the future. Treating it as an error for now.
  192. debug('TX Future!')
  193. // nonce is likely out of sync, delete it so we reload it from chain on next attempt
  194. delete this.nonces[accountId]
  195. const err = new Error('transaction nonce set in future')
  196. finalizedPromise.reject(err)
  197. reject(err)
  198. }
  199. /* why don't we see these status updates on local devchain (single node)
  200. isUsurped
  201. isBroadcast
  202. isDropped
  203. isInvalid
  204. */
  205. })
  206. .catch((err) => {
  207. // 1014 error: Most likely you are sending transaction with the same nonce,
  208. // so it assumes you want to replace existing one, but the priority is too low to replace it (priority = fee = len(encoded_transaction) currently)
  209. // Remember this can also happen if in the past we sent a tx with a future nonce, and the current nonce
  210. // now matches it.
  211. if (err) {
  212. const errstr = err.toString()
  213. // not the best way to check error code.
  214. // https://github.com/polkadot-js/api/blob/master/packages/rpc-provider/src/coder/index.ts#L52
  215. if (
  216. errstr.indexOf('Error: 1014:') < 0 && // low priority
  217. errstr.indexOf('Error: 1010:') < 0
  218. ) {
  219. // bad transaction
  220. // Error but not nonce related. (bad arguments maybe)
  221. debug('TX error', err)
  222. } else {
  223. // nonce is likely out of sync, delete it so we reload it from chain on next attempt
  224. delete this.nonces[accountId]
  225. }
  226. }
  227. finalizedPromise.reject(err)
  228. // releases lock
  229. reject(err)
  230. })
  231. })
  232. })
  233. // when does it make sense to manyally unsubscribe?
  234. // at this point unsubscribe.then and unsubscribe.catch have been deleted
  235. // unsubscribe() // don't unsubscribe if we want to wait for additional status
  236. // updates to know when the tx has been finalized
  237. return finalizedPromise.promise
  238. }
  239. /*
  240. * Sign and send a transaction expect event from
  241. * module and return eventProperty from the event.
  242. */
  243. async signAndSendThenGetEventResult(senderAccountId, tx, { eventModule, eventName, eventProperty }) {
  244. // event from a module,
  245. const subscribed = [[eventModule, eventName]]
  246. return new Promise(async (resolve, reject) => {
  247. try {
  248. await this.signAndSend(senderAccountId, tx, 1, subscribed, (events) => {
  249. events.forEach((event) => {
  250. // fix - we may not necessarily want the first event
  251. // if there are multiple events emitted,
  252. resolve(event[1][eventProperty])
  253. })
  254. })
  255. } catch (err) {
  256. reject(err)
  257. }
  258. })
  259. }
  260. }
  261. module.exports = {
  262. RuntimeApi,
  263. }