index.js 12 KB

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