index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 debugTx = require('debug')('joystream:runtime:base:tx')
  21. const { types } = require('@joystream/types')
  22. const { ApiPromise, WsProvider } = require('@polkadot/api')
  23. const { IdentitiesApi } = require('@joystream/storage-runtime-api/identities')
  24. const { BalancesApi } = require('@joystream/storage-runtime-api/balances')
  25. const { WorkersApi } = require('@joystream/storage-runtime-api/workers')
  26. const { AssetsApi } = require('@joystream/storage-runtime-api/assets')
  27. const { DiscoveryApi } = require('@joystream/storage-runtime-api/discovery')
  28. const { SystemApi } = require('@joystream/storage-runtime-api/system')
  29. const AsyncLock = require('async-lock')
  30. const Promise = require('bluebird')
  31. const { sleep } = require('@joystream/storage-utils/sleep')
  32. Promise.config({
  33. cancellation: true,
  34. })
  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. const provider = new WsProvider(options.provider_url || 'ws://localhost:9944')
  49. // Create the API instrance
  50. this.api = await ApiPromise.create({ provider, types: types })
  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. async untilChainIsSynced() {
  72. debug('Waiting for chain to be synced before proceeding.')
  73. while (true) {
  74. const isSyncing = await this.chainIsSyncing()
  75. if (isSyncing) {
  76. debug('Still waiting for chain to be synced.')
  77. await sleep(1 * 30 * 1000)
  78. } else {
  79. return
  80. }
  81. }
  82. }
  83. async chainIsSyncing() {
  84. const { isSyncing } = await this.api.rpc.system.health()
  85. return isSyncing.isTrue
  86. }
  87. async providerHasMinimumBalance(minimumBalance) {
  88. const providerAccountId = this.identities.key.address
  89. return this.balances.hasMinimumBalanceOf(providerAccountId, minimumBalance)
  90. }
  91. executeWithAccountLock(accountId, func) {
  92. return this.asyncLock.acquire(`${accountId}`, func)
  93. }
  94. static matchingEvents(subscribed = [], events = []) {
  95. const filtered = events.filter((record) => {
  96. const { event } = record
  97. // Skip events we're not interested in.
  98. const matching = subscribed.filter((value) => {
  99. if (value[0] === '*' && value[1] === '*') {
  100. return true
  101. } else if (value[0] === '*') {
  102. return event.method === value[1]
  103. } else if (value[1] === '*') {
  104. return event.section === value[0]
  105. } else {
  106. return event.section === value[0] && event.method === value[1]
  107. }
  108. })
  109. return matching.length > 0
  110. })
  111. return filtered.map((record) => {
  112. const { event } = record
  113. const types = event.typeDef
  114. const payload = new Map()
  115. // this check may be un-necessary but doing it just incase
  116. if (event.data) {
  117. event.data.forEach((data, index) => {
  118. const type = types[index].type
  119. payload.set(index, { type, data })
  120. })
  121. }
  122. const fullName = `${event.section}.${event.method}`
  123. debugTx(`matched event: ${fullName} =>`, event.data && event.data.join(', '))
  124. return [fullName, payload]
  125. })
  126. }
  127. // Get cached nonce and use unless system nonce is greater, to avoid stale nonce if
  128. // there was a long gap in time between calls to signAndSend during which an external app
  129. // submitted a transaction.
  130. async selectBestNonce(accountId) {
  131. const cachedNonce = this.nonces[accountId]
  132. // In future use this rpc method to take the pending tx pool into account when fetching the nonce
  133. // const nonce = await this.api.rpc.system.accountNextIndex(accountId)
  134. const { nonce } = await this.api.query.system.account(accountId)
  135. const systemNonce = nonce
  136. const bestNonce = cachedNonce && cachedNonce.gte(systemNonce) ? cachedNonce : systemNonce
  137. this.nonces[accountId] = bestNonce
  138. return bestNonce.toNumber()
  139. }
  140. incrementAndSaveNonce(accountId) {
  141. this.nonces[accountId] = this.nonces[accountId].addn(1)
  142. }
  143. /*
  144. * signAndSend() with nonce tracking, to enable concurrent sending of transacctions
  145. * so that they can be included in the same block. Allows you to use the accountId instead
  146. * of the key, without requiring an external Signer configured on the underlying ApiPromie
  147. *
  148. * If the subscribed events are given, then the matchedEvents will be returned in the resolved
  149. * value.
  150. * Resolves when a transaction finalizes with a successful dispatch (for both signed and root origins)
  151. * Rejects in all other cases.
  152. * Will also reject on timeout if the transaction doesn't finalize in time.
  153. */
  154. async signAndSend(accountId, tx, subscribed) {
  155. // Accept both a string or AccountId as argument
  156. accountId = this.identities.keyring.encodeAddress(accountId)
  157. // Throws if keyPair is not found
  158. const fromKey = this.identities.keyring.getPair(accountId)
  159. // Key must be unlocked to use
  160. if (fromKey.isLocked) {
  161. throw new Error('Must unlock key before using it to sign!')
  162. }
  163. const callbacks = {
  164. // Functions to be called when the submitted transaction is finalized. They are initialized
  165. // after the transaction is submitted to the resolve and reject function of the final promise
  166. // returned by signAndSend
  167. // on extrinsic success
  168. onFinalizedSuccess: null,
  169. // on extrinsic failure
  170. onFinalizedFailed: null,
  171. // Function assigned when transaction is successfully submitted. Invoking it ubsubscribes from
  172. // listening to tx status updates.
  173. unsubscribe: null,
  174. }
  175. // object used to communicate back information from the tx updates handler
  176. const out = {
  177. lastResult: { status: {} },
  178. }
  179. // synchronize access to nonce
  180. await this.executeWithAccountLock(accountId, async () => {
  181. const nonce = await this.selectBestNonce(accountId)
  182. const signed = tx.sign(fromKey, { nonce })
  183. const txhash = signed.hash
  184. try {
  185. callbacks.unsubscribe = await signed.send(
  186. RuntimeApi.createTxUpdateHandler(callbacks, { nonce, txhash, subscribed }, out)
  187. )
  188. const serialized = JSON.stringify({
  189. nonce,
  190. txhash,
  191. tx: signed.toHex(),
  192. })
  193. // We are depending on the behaviour that at this point the Ready status
  194. // Elaboration: when the tx is rejected and therefore the tx isn't added
  195. // to the tx pool ready queue status is not updated and
  196. // .send() throws, so we don't reach this code.
  197. if (out.lastResult.status.isFuture) {
  198. debugTx(`Warning: Submitted Tx with future nonce: ${serialized}`)
  199. } else {
  200. debugTx(`Submitted: ${serialized}`)
  201. }
  202. // transaction submitted successfully, increment and save nonce.
  203. this.incrementAndSaveNonce(accountId)
  204. } catch (err) {
  205. const errstr = err.toString()
  206. debugTx(`Rejected: ${errstr} txhash: ${txhash} nonce: ${nonce}`)
  207. throw err
  208. }
  209. })
  210. // Here again we assume that the transaction has been accepted into the tx pool
  211. // and status was updated.
  212. // We cannot get tx updates for a future tx so return now to avoid blocking caller
  213. if (out.lastResult.status.isFuture) {
  214. return {}
  215. }
  216. // Return a promise that will resolve when the transaction finalizes.
  217. // On timeout it will be rejected. Timeout is a workaround for dealing with the
  218. // fact that if rpc connection is lost to node we have no way of detecting it or recovering.
  219. // Timeout can also occur if a transaction that was part of batch of transactions submitted
  220. // gets usurped.
  221. return new Promise((resolve, reject) => {
  222. callbacks.onFinalizedSuccess = resolve
  223. callbacks.onFinalizedFailed = reject
  224. }).timeout(TX_TIMEOUT)
  225. }
  226. /*
  227. * Sign and send a transaction expect event from
  228. * module and return specific(index) value from event data
  229. */
  230. async signAndSendThenGetEventResult(senderAccountId, tx, { module, event, index, type }) {
  231. if (!module || !event || index === undefined || !type) {
  232. throw new Error('MissingSubscribeEventDetails')
  233. }
  234. const subscribed = [[module, event]]
  235. const { mappedEvents } = await this.signAndSend(senderAccountId, tx, subscribed)
  236. if (!mappedEvents) {
  237. // The tx was a future so it was not possible and will not be possible to get events
  238. throw new Error('NoEventsWereCaptured')
  239. }
  240. if (!mappedEvents.length) {
  241. // our expected event was not emitted
  242. throw new Error('ExpectedEventNotFound')
  243. }
  244. // fix - we may not necessarily want the first event
  245. // when there are multiple instances of the same event
  246. const firstEvent = mappedEvents[0]
  247. if (firstEvent[0] !== `${module}.${event}`) {
  248. throw new Error('WrongEventCaptured')
  249. }
  250. const payload = firstEvent[1]
  251. if (!payload.has(index)) {
  252. throw new Error('DataIndexOutOfRange')
  253. }
  254. const value = payload.get(index)
  255. if (value.type !== type) {
  256. throw new Error('DataTypeNotExpectedType')
  257. }
  258. return value.data
  259. }
  260. static createTxUpdateHandler(callbacks, submittedTx, out = {}) {
  261. const { nonce, txhash, subscribed } = submittedTx
  262. return function handleTxUpdates(result) {
  263. const { events = [], status } = result
  264. const { unsubscribe, onFinalizedFailed, onFinalizedSuccess } = callbacks
  265. if (!result || !status) {
  266. return
  267. }
  268. out.lastResult = result
  269. const txinfo = () => {
  270. return JSON.stringify({
  271. nonce,
  272. txhash,
  273. })
  274. }
  275. if (result.isError) {
  276. unsubscribe()
  277. debugTx(`Error: ${status.type}`, txinfo())
  278. onFinalizedFailed &&
  279. onFinalizedFailed({ err: status.type, result, tx: status.isUsurped ? status.asUsurped : undefined })
  280. } else if (result.isCompleted) {
  281. unsubscribe()
  282. debugTx('Finalized', txinfo())
  283. const mappedEvents = RuntimeApi.matchingEvents(subscribed, events)
  284. const failed = result.findRecord('system', 'ExtrinsicFailed')
  285. const success = result.findRecord('system', 'ExtrinsicSuccess')
  286. const sudid = result.findRecord('sudo', 'Sudid')
  287. const sudoAsDone = result.findRecord('sudo', 'SudoAsDone')
  288. if (failed) {
  289. const {
  290. event: { data },
  291. } = failed
  292. const dispatchError = data[0]
  293. onFinalizedFailed({
  294. err: 'ExtrinsicFailed',
  295. mappedEvents,
  296. result,
  297. block: status.asCompleted,
  298. dispatchError, // we get module number/id and index into the Error enum
  299. })
  300. } else if (success) {
  301. // Note: For root origin calls, the dispatch error is logged to the joystream-node
  302. // console, we cannot get it in the events
  303. if (sudid) {
  304. const dispatchSuccess = sudid.event.data[0]
  305. if (dispatchSuccess.isOk) {
  306. onFinalizedSuccess({ mappedEvents, result, block: status.asCompleted })
  307. } else {
  308. onFinalizedFailed({ err: 'SudoFailed', mappedEvents, result, block: status.asCompleted })
  309. }
  310. } else if (sudoAsDone) {
  311. const dispatchSuccess = sudoAsDone.event.data[0]
  312. if (dispatchSuccess.isOk) {
  313. onFinalizedSuccess({ mappedEvents, result, block: status.asCompleted })
  314. } else {
  315. onFinalizedFailed({ err: 'SudoAsFailed', mappedEvents, result, block: status.asCompleted })
  316. }
  317. } else {
  318. onFinalizedSuccess({ mappedEvents, result, block: status.asCompleted })
  319. }
  320. }
  321. }
  322. }
  323. }
  324. }
  325. module.exports = {
  326. RuntimeApi,
  327. }