index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 { GenericExtrinsicPayloadV2 } = require('../../../pioneer/packages/apps/build/main.a723bde4')
  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. // Deal with statuses which will prevent
  142. // extrinsic from finalizing.
  143. if (status.isUsurped) {
  144. debug(status.type)
  145. debug(JSON.stringify(status.asUsurped))
  146. onFinalizedFailed && onFinalizedFailed({ err: 'Usurped', result, tx: status.asFinalized })
  147. }
  148. if (status.isDropped) {
  149. debug(status.type)
  150. debug(JSON.stringify(status.asDropped))
  151. onFinalizedFailed && onFinalizedFailed({ err: 'Dropped', result, tx: status.asFinalized })
  152. }
  153. // My gutt says this comes before isReady and causes await send() to throw
  154. // and therefore onFinalizedFailed isn't initialized.
  155. // We don't need to do anything other than log it?
  156. if (status.isInvalid) {
  157. debug(status.type)
  158. debug(JSON.stringify(status.asInvalid))
  159. onFinalizedFailed && onFinalizedFailed({ err: 'Invalid', result, tx: status.asFinalized })
  160. }
  161. if (status.isFinalized) {
  162. const mappedEvents = RuntimeApi.matchingEvents(subscribed, events)
  163. const failed = result.findRecord('system', 'ExtrinsicFailed')
  164. const success = result.findRecord('system', 'ExtrinsicSuccess')
  165. const sudid = result.findRecord('sudo', 'Sudid')
  166. const sudoAsDone = result.findRecord('sudo', 'SudoAsDone')
  167. if (failed) {
  168. const {
  169. event: { data },
  170. } = failed
  171. const dispatchError = data[0]
  172. onFinalizedFailed({
  173. err: 'ExtrinsicFailed',
  174. mappedEvents,
  175. result,
  176. tx: status.asFinalized,
  177. dispatchError, // we get module number/id and index into the Error enum
  178. })
  179. } else if (success) {
  180. // Note: For root origin calls, the dispatch error is logged to console
  181. // we cannot get it in the events
  182. if (sudid) {
  183. const dispatchSuccess = sudid.event.data[0]
  184. if (dispatchSuccess.isTrue) {
  185. onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
  186. } else {
  187. onFinalizedFailed({ err: 'SudoFailed', mappedEvents, result, tx: status.asFinalized })
  188. }
  189. } else if (sudoAsDone) {
  190. const dispatchSuccess = sudoAsDone.event.data[0]
  191. if (dispatchSuccess.isTrue) {
  192. onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
  193. } else {
  194. onFinalizedFailed({ err: 'SudoAsFailed', mappedEvents, result, tx: status.asFinalized })
  195. }
  196. } else {
  197. onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
  198. }
  199. }
  200. }
  201. if (result.isCompleted) {
  202. unsubscribe()
  203. }
  204. }
  205. // synchronize access to nonce
  206. await this.executeWithAccountLock(accountId, async () => {
  207. const nonce = this.nonces[accountId] || (await this.api.query.system.accountNonce(accountId))
  208. try {
  209. unsubscribe = await tx.sign(fromKey, { nonce }).send(handleTxUpdates)
  210. debug('TransactionSubmitted')
  211. // transaction submitted successfully, increment and save nonce.
  212. this.nonces[accountId] = nonce.addn(1)
  213. } catch (err) {
  214. const errstr = err.toString()
  215. debug('TransactionRejected:', errstr)
  216. // This happens when nonce is already used in finalized transactions, ie. the selected nonce
  217. // was less than current account nonce. A few scenarios where this happens (other than incorrect code)
  218. // 1. When a past future tx got finalized because we submitted some transactions
  219. // using up the nonces upto that point.
  220. // 2. Can happen while storage-node is talkig to a joystream-node that is still not fully
  221. // synced.
  222. // 3. Storage role account holder sent a transaction just ahead of us via another app.
  223. if (errstr.indexOf('ExtrinsicStatus:: 1010: Invalid Transaction: Stale') !== -1) {
  224. // In case 1 or 3 a quick recovery could work by just incrementing, but since we
  225. // cannot detect which case we are in just reset and force re-reading nonce. Even
  226. // that may not be sufficient expect after a few more failures..
  227. delete this.nonces[accountId]
  228. }
  229. // Technically it means a transaction in the mempool with same
  230. // nonce and same fees being paid so we cannot replace it, either we didn't correctly
  231. // increment the nonce or someone external to this application sent a transaction
  232. // with same nonce ahead of us.
  233. if (errstr.indexOf('ExtrinsicStatus:: 1014: Priority is too low') !== -1) {
  234. delete this.nonces[accountId]
  235. }
  236. throw err
  237. }
  238. })
  239. // We cannot get tx updates for a future tx so return now to avoid blocking caller
  240. if (lastTxUpdateResult.status.isFuture) {
  241. debug('Warning: Submitted extrinsic with future nonce')
  242. return {}
  243. }
  244. // Return a promise that will resolve when the transaction finalizes.
  245. // On timeout it will be rejected. Timeout is a workaround for dealing with the
  246. // fact that if rpc connection is lost to node we have no way of detecting it or recovering.
  247. return new Promise((resolve, reject) => {
  248. onFinalizedSuccess = resolve
  249. onFinalizedFailed = reject
  250. }).timeout(TX_TIMEOUT)
  251. }
  252. /*
  253. * Sign and send a transaction expect event from
  254. * module and return eventProperty from the event.
  255. */
  256. async signAndSendThenGetEventResult(senderAccountId, tx, { module, event, index, type }) {
  257. if (!module || !event || index === undefined || !type) {
  258. throw new Error('MissingSubscribeEventDetails')
  259. }
  260. const subscribed = [[module, event]]
  261. const { mappedEvents } = await this.signAndSend(senderAccountId, tx, subscribed)
  262. if (!mappedEvents) {
  263. // The tx was a future so it was not possible and will not be possible to get events
  264. throw new Error('NoEventsWereCaptured')
  265. }
  266. if (!mappedEvents.length) {
  267. // our expected event was not emitted
  268. throw new Error('ExpectedEventNotFound')
  269. }
  270. // fix - we may not necessarily want the first event
  271. // when there are multiple instances of the same event
  272. const firstEvent = mappedEvents[0]
  273. if (firstEvent[0] !== `${module}.${event}`) {
  274. throw new Error('WrongEventCaptured')
  275. }
  276. const payload = firstEvent[1]
  277. if (!payload.has(index)) {
  278. throw new Error('DataIndexOutOfRange')
  279. }
  280. const value = payload.get(index)
  281. if (value.type !== type) {
  282. throw new Error('DataTypeNotExpectedType')
  283. }
  284. return value.data
  285. }
  286. }
  287. module.exports = {
  288. RuntimeApi,
  289. }