index.js 12 KB

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