index.js 13 KB

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