index.js 13 KB

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