index.js 12 KB

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