index.js 12 KB

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