index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 Promise = require('bluebird')
  30. const { startsWith } = require('lodash')
  31. Promise.config({
  32. cancellation: true,
  33. })
  34. // const ASYNC_LOCK_TIMEOUT = 30 * 1000
  35. const TX_TIMEOUT = 20 * 1000
  36. /*
  37. * Initialize runtime (substrate) API and keyring.
  38. */
  39. class RuntimeApi {
  40. static async create(options) {
  41. const runtimeApi = new RuntimeApi()
  42. await runtimeApi.init(options || {})
  43. return runtimeApi
  44. }
  45. async init(options) {
  46. debug('Init')
  47. options = options || {}
  48. // Register joystream types
  49. registerJoystreamTypes()
  50. const provider = new WsProvider(options.provider_url || 'ws://localhost:9944')
  51. // Create the API instrance
  52. this.api = await ApiPromise.create({ provider })
  53. // this.asyncLock = new AsyncLock({ timeout: ASYNC_LOCK_TIMEOUT, maxPending: 100 })
  54. this.asyncLock = new AsyncLock()
  55. // Keep track locally of account nonces.
  56. this.nonces = {}
  57. // The storage provider id to use
  58. this.storageProviderId = parseInt(options.storageProviderId) // u64 instead ?
  59. // Ok, create individual APIs
  60. this.identities = await IdentitiesApi.create(this, {
  61. accountFile: options.account_file,
  62. passphrase: options.passphrase,
  63. canPromptForPassphrase: options.canPromptForPassphrase,
  64. })
  65. this.balances = await BalancesApi.create(this)
  66. this.workers = await WorkersApi.create(this)
  67. this.assets = await AssetsApi.create(this)
  68. this.discovery = await DiscoveryApi.create(this)
  69. this.system = await SystemApi.create(this)
  70. }
  71. disconnect() {
  72. this.api.disconnect()
  73. }
  74. executeWithAccountLock(accountId, func) {
  75. return this.asyncLock.acquire(`${accountId}`, func)
  76. }
  77. static matchingEvents(subscribed = [], events = []) {
  78. const filtered = events.filter((record) => {
  79. const { event } = record
  80. // Skip events we're not interested in.
  81. const matching = subscribed.filter((value) => {
  82. if (value[0] === '*' && value[1] === '*') {
  83. return true
  84. } else if (value[0] === '*') {
  85. return event.method === value[1]
  86. } else if (value[1] === '*') {
  87. return event.section === value[0]
  88. } else {
  89. return event.section === value[0] && event.method === value[1]
  90. }
  91. })
  92. return matching.length > 0
  93. })
  94. return filtered.map((record) => {
  95. const { event } = record
  96. const types = event.typeDef
  97. const payload = new Map()
  98. event.data.forEach((data, index) => {
  99. const type = types[index].type
  100. payload.set(index, { type, data })
  101. })
  102. const fullName = `${event.section}.${event.method}`
  103. debug(`matched event: ${fullName} =>`, ...event.data.map((data) => `${data},`))
  104. return [fullName, payload]
  105. })
  106. }
  107. /*
  108. * signAndSend() with nonce tracking, to enable concurrent sending of transacctions
  109. * so that they can be included in the same block. Allows you to use the accountId instead
  110. * of the key, without requiring an external Signer configured on the underlying ApiPromie
  111. *
  112. * If the subscribed events are given, and a callback as well, then the
  113. * callback is invoked with matching events.
  114. */
  115. async signAndSend(accountId, tx, subscribed) {
  116. // Accept both a string or AccountId as argument
  117. accountId = this.identities.keyring.encodeAddress(accountId)
  118. // Throws if keyPair is not found
  119. const fromKey = this.identities.keyring.getPair(accountId)
  120. // Key must be unlocked to use
  121. if (fromKey.isLocked) {
  122. throw new Error('Must unlock key before using it to sign!')
  123. }
  124. // Functions to be called when the submitted transaction is finalized. They are initialized
  125. // after the transaction is submitted to the resolve and reject function of the final promise
  126. // returned by signAndSend
  127. // on extrinsic success
  128. let onFinalizedSuccess
  129. // on extrinsic failure
  130. let onFinalizedFailed
  131. // Function assigned when transaction is successfully submitted. Invoking it ubsubscribes from
  132. // listening to tx status updates.
  133. let unsubscribe
  134. let lastTxUpdateResult
  135. const handleTxUpdates = (result) => {
  136. const { events = [], status } = result
  137. if (!result || !status) {
  138. return
  139. }
  140. lastTxUpdateResult = result
  141. if (result.isError) {
  142. unsubscribe()
  143. onFinalizedFailed &&
  144. onFinalizedFailed({ err: status.type, result, tx: status.isUsurped ? status.asUsurped : undefined })
  145. } else if (result.isFinalized) {
  146. unsubscribe()
  147. const mappedEvents = RuntimeApi.matchingEvents(subscribed, events)
  148. const failed = result.findRecord('system', 'ExtrinsicFailed')
  149. const success = result.findRecord('system', 'ExtrinsicSuccess')
  150. const sudid = result.findRecord('sudo', 'Sudid')
  151. const sudoAsDone = result.findRecord('sudo', 'SudoAsDone')
  152. if (failed) {
  153. const {
  154. event: { data },
  155. } = failed
  156. const dispatchError = data[0]
  157. onFinalizedFailed({
  158. err: 'ExtrinsicFailed',
  159. mappedEvents,
  160. result,
  161. block: status.asFinalized,
  162. dispatchError, // we get module number/id and index into the Error enum
  163. })
  164. } else if (success) {
  165. // Note: For root origin calls, the dispatch error is logged to the joystream-node
  166. // console, we cannot get it in the events
  167. if (sudid) {
  168. const dispatchSuccess = sudid.event.data[0]
  169. if (dispatchSuccess.isTrue) {
  170. onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
  171. } else {
  172. onFinalizedFailed({ err: 'SudoFailed', mappedEvents, result, tx: status.asFinalized })
  173. }
  174. } else if (sudoAsDone) {
  175. const dispatchSuccess = sudoAsDone.event.data[0]
  176. if (dispatchSuccess.isTrue) {
  177. onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
  178. } else {
  179. onFinalizedFailed({ err: 'SudoAsFailed', mappedEvents, result, tx: status.asFinalized })
  180. }
  181. } else {
  182. onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
  183. }
  184. }
  185. }
  186. }
  187. // synchronize access to nonce
  188. await this.executeWithAccountLock(accountId, async () => {
  189. const nonce = this.nonces[accountId] || (await this.api.query.system.accountNonce(accountId))
  190. // In future use this rpc method to take the pending tx pool into account when fetching the nonce
  191. // const nonce = await this.api.rpc.system.accountNextIndex(accountId)
  192. try {
  193. unsubscribe = await tx.sign(fromKey, { nonce }).send(handleTxUpdates)
  194. debug('TransactionSubmitted')
  195. // transaction submitted successfully, increment and save nonce.
  196. this.nonces[accountId] = nonce.addn(1)
  197. } catch (err) {
  198. const errstr = err.toString()
  199. debug('TransactionRejected:', errstr)
  200. // This happens when nonce is already used in finalized transactions, ie. the selected nonce
  201. // was less than current account nonce. A few scenarios where this happens (other than incorrect code)
  202. // 1. When a past future tx got finalized because we submitted some transactions
  203. // using up the nonces upto that point.
  204. // 2. Can happen while storage-node is talkig to a joystream-node that is still not fully
  205. // synced.
  206. // 3. Storage role account holder sent a transaction just ahead of us via another app.
  207. if (errstr.indexOf('ExtrinsicStatus:: 1010: Invalid Transaction: Stale') !== -1) {
  208. // In case 1 or 3 a quick recovery could work by just incrementing, but since we
  209. // cannot detect which case we are in just reset and force re-reading nonce. Even
  210. // that may not be sufficient expect after a few more failures..
  211. delete this.nonces[accountId]
  212. }
  213. // Technically it means a transaction in the mempool with same
  214. // nonce and same fees being paid so we cannot replace it, either we didn't correctly
  215. // increment the nonce or someone external to this application sent a transaction
  216. // with same nonce ahead of us.
  217. if (errstr.indexOf('ExtrinsicStatus:: 1014: Priority is too low') !== -1) {
  218. delete this.nonces[accountId]
  219. }
  220. throw err
  221. }
  222. })
  223. // We cannot get tx updates for a future tx so return now to avoid blocking caller
  224. if (lastTxUpdateResult.status.isFuture) {
  225. debug('Warning: Submitted extrinsic with future nonce')
  226. return {}
  227. }
  228. // Return a promise that will resolve when the transaction finalizes.
  229. // On timeout it will be rejected. Timeout is a workaround for dealing with the
  230. // fact that if rpc connection is lost to node we have no way of detecting it or recovering.
  231. // Timeout can also occur if a transaction that was part of batch of transactions submitted
  232. // gets usurped.
  233. return new Promise((resolve, reject) => {
  234. onFinalizedSuccess = resolve
  235. onFinalizedFailed = reject
  236. }).timeout(TX_TIMEOUT)
  237. }
  238. /*
  239. * Sign and send a transaction expect event from
  240. * module and return eventProperty from the event.
  241. */
  242. async signAndSendThenGetEventResult(senderAccountId, tx, { module, event, index, type }) {
  243. if (!module || !event || index === undefined || !type) {
  244. throw new Error('MissingSubscribeEventDetails')
  245. }
  246. const subscribed = [[module, event]]
  247. const { mappedEvents } = await this.signAndSend(senderAccountId, tx, subscribed)
  248. if (!mappedEvents) {
  249. // The tx was a future so it was not possible and will not be possible to get events
  250. throw new Error('NoEventsWereCaptured')
  251. }
  252. if (!mappedEvents.length) {
  253. // our expected event was not emitted
  254. throw new Error('ExpectedEventNotFound')
  255. }
  256. // fix - we may not necessarily want the first event
  257. // when there are multiple instances of the same event
  258. const firstEvent = mappedEvents[0]
  259. if (firstEvent[0] !== `${module}.${event}`) {
  260. throw new Error('WrongEventCaptured')
  261. }
  262. const payload = firstEvent[1]
  263. if (!payload.has(index)) {
  264. throw new Error('DataIndexOutOfRange')
  265. }
  266. const value = payload.get(index)
  267. if (value.type !== type) {
  268. throw new Error('DataTypeNotExpectedType')
  269. }
  270. return value.data
  271. }
  272. }
  273. module.exports = {
  274. RuntimeApi,
  275. }