index.js 11 KB

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