index.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 { registerJoystreamTypes } = require('@joystream/types');
  21. const { ApiPromise, WsProvider } = require('@polkadot/api');
  22. const { IdentitiesApi } = require('@joystream/runtime-api/identities');
  23. const { BalancesApi } = require('@joystream/runtime-api/balances');
  24. const { RolesApi } = require('@joystream/runtime-api/roles');
  25. const { AssetsApi } = require('@joystream/runtime-api/assets');
  26. const { DiscoveryApi } = require('@joystream/runtime-api/discovery');
  27. const AsyncLock = require('async-lock');
  28. /*
  29. * Initialize runtime (substrate) API and keyring.
  30. */
  31. class RuntimeApi
  32. {
  33. static async create(options)
  34. {
  35. const runtime_api = new RuntimeApi();
  36. await runtime_api.init(options || {});
  37. return runtime_api;
  38. }
  39. async init(options)
  40. {
  41. debug('Init');
  42. options = options || {};
  43. // Register joystream types
  44. registerJoystreamTypes();
  45. const provider = new WsProvider(options.provider_url || 'ws://localhost:9944');
  46. // Create the API instrance
  47. this.api = await ApiPromise.create({ provider });
  48. this.asyncLock = new AsyncLock();
  49. // Keep track locally of account nonces.
  50. this.nonces = {};
  51. // Ok, create individual APIs
  52. this.identities = await IdentitiesApi.create(this, {
  53. account_file: options.account_file,
  54. passphrase: options.passphrase,
  55. canPromptForPassphrase: options.canPromptForPassphrase
  56. });
  57. this.balances = await BalancesApi.create(this);
  58. this.roles = await RolesApi.create(this);
  59. this.assets = await AssetsApi.create(this);
  60. this.discovery = await DiscoveryApi.create(this);
  61. }
  62. disconnect()
  63. {
  64. this.api.disconnect();
  65. }
  66. executeWithAccountLock(account_id, func) {
  67. return this.asyncLock.acquire(`${account_id}`, func);
  68. }
  69. /*
  70. * Wait for an event. Filters out any events that don't match the module and
  71. * event name.
  72. *
  73. * The result of the Promise is an array containing first the full event
  74. * name, and then the event fields as an object.
  75. */
  76. async waitForEvent(module, name)
  77. {
  78. return this.waitForEvents([[module, name]]);
  79. }
  80. _matchingEvents(subscribed, events)
  81. {
  82. debug(`Number of events: ${events.length}; subscribed to ${subscribed}`);
  83. const filtered = events.filter((record) => {
  84. const { event, phase } = record;
  85. // Show what we are busy with
  86. debug(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`);
  87. debug(`\t\t${event.meta.documentation.toString()}`);
  88. // Skip events we're not interested in.
  89. const matching = subscribed.filter((value) => {
  90. return event.section == value[0] && event.method == value[1];
  91. });
  92. return matching.length > 0;
  93. });
  94. debug(`Filtered: ${filtered.length}`);
  95. const mapped = filtered.map((record) => {
  96. const { event } = record;
  97. const types = event.typeDef;
  98. // Loop through each of the parameters, displaying the type and data
  99. const payload = {};
  100. event.data.forEach((data, index) => {
  101. debug(`\t\t\t${types[index].type}: ${data.toString()}`);
  102. payload[types[index].type] = data;
  103. });
  104. const full_name = `${event.section}.${event.method}`;
  105. return [full_name, payload];
  106. });
  107. debug('Mapped', mapped);
  108. return mapped;
  109. }
  110. /*
  111. * Same as waitForEvent, but filter on multiple events. The parameter is an
  112. * array of arrays containing module and name. Calling waitForEvent is
  113. * identical to calling this with [[module, name]].
  114. *
  115. * Returns the first matched event *only*.
  116. */
  117. async waitForEvents(subscribed)
  118. {
  119. return new Promise((resolve, reject) => {
  120. this.api.query.system.events((events) => {
  121. const matches = this._matchingEvents(subscribed, events);
  122. if (matches && matches.length) {
  123. resolve(matches);
  124. }
  125. });
  126. });
  127. }
  128. /*
  129. * Nonce-aware signAndSend(). Also allows you to use the accountId instead
  130. * of the key, making calls a little simpler. Will lock to prevent concurrent
  131. * calls so correct nonce is used.
  132. *
  133. * If the subscribed events are given, and a callback as well, then the
  134. * callback is invoked with matching events.
  135. */
  136. async signAndSend(accountId, tx, attempts, subscribed, callback)
  137. {
  138. // Prepare key
  139. const from_key = this.identities.keyring.getPair(accountId);
  140. if (from_key.isLocked) {
  141. throw new Error('Must unlock key before using it to sign!');
  142. }
  143. const finalizedPromise = newExternallyControlledPromise();
  144. let unsubscribe = await this.executeWithAccountLock(accountId, async () => {
  145. // Try to get the next nonce to use
  146. let nonce = this.nonces[accountId];
  147. let incrementNonce = () => {
  148. // only increment once
  149. incrementNonce = () => {}; // turn it into a no-op
  150. nonce = nonce.addn(1);
  151. this.nonces[accountId] = nonce;
  152. }
  153. // If the nonce isn't available, get it from chain.
  154. if (!nonce) {
  155. // current nonce
  156. nonce = await this.api.query.system.accountNonce(accountId);
  157. debug(`Got nonce for ${accountId} from chain: ${nonce}`);
  158. }
  159. return new Promise((resolve, reject) => {
  160. debug('Signing and sending tx');
  161. // send(statusUpdates) returns a function for unsubscribing from status updates
  162. let unsubscribe = tx.sign(from_key, { nonce })
  163. .send(({events = [], status}) => {
  164. debug(`TX status: ${status.type}`);
  165. // Whatever events we get, process them if there's someone interested.
  166. // It is critical that this event handling doesn't prevent
  167. try {
  168. if (subscribed && callback) {
  169. const matched = this._matchingEvents(subscribed, events);
  170. debug('Matching events:', matched);
  171. if (matched.length) {
  172. callback(matched);
  173. }
  174. }
  175. } catch(err) {
  176. debug(`Error handling events ${err.stack}`)
  177. }
  178. // We want to release lock as early as possible, sometimes Ready status
  179. // doesn't occur, so we do it on Broadcast instead
  180. if (status.isReady) {
  181. debug('TX Ready.');
  182. incrementNonce();
  183. resolve(unsubscribe); //releases lock
  184. } else if (status.isBroadcast) {
  185. debug('TX Broadcast.');
  186. incrementNonce();
  187. resolve(unsubscribe); //releases lock
  188. } else if (status.isFinalized) {
  189. debug('TX Finalized.');
  190. finalizedPromise.resolve(status)
  191. } else if (status.isFuture) {
  192. // comes before ready.
  193. // does that mean it will remain in mempool or in api internal queue?
  194. // nonce was set in the future. Treating it as an error for now.
  195. debug('TX Future!')
  196. // nonce is likely out of sync, delete it so we reload it from chain on next attempt
  197. delete this.nonces[accountId];
  198. const err = new Error('transaction nonce set in future');
  199. finalizedPromise.reject(err);
  200. reject(err);
  201. }
  202. /* why don't we see these status updates on local devchain (single node)
  203. isUsurped
  204. isBroadcast
  205. isDropped
  206. isInvalid
  207. */
  208. })
  209. .catch((err) => {
  210. // 1014 error: Most likely you are sending transaction with the same nonce,
  211. // so it assumes you want to replace existing one, but the priority is too low to replace it (priority = fee = len(encoded_transaction) currently)
  212. // Remember this can also happen if in the past we sent a tx with a future nonce, and the current nonce
  213. // now matches it.
  214. if (err) {
  215. const errstr = err.toString();
  216. // not the best way to check error code.
  217. // https://github.com/polkadot-js/api/blob/master/packages/rpc-provider/src/coder/index.ts#L52
  218. if (errstr.indexOf('Error: 1014:') < 0 && // low priority
  219. errstr.indexOf('Error: 1010:') < 0) // bad transaction
  220. {
  221. // Error but not nonce related. (bad arguments maybe)
  222. debug('TX error', err);
  223. } else {
  224. // nonce is likely out of sync, delete it so we reload it from chain on next attempt
  225. delete this.nonces[accountId];
  226. }
  227. }
  228. finalizedPromise.reject(err);
  229. // releases lock
  230. reject(err);
  231. });
  232. });
  233. })
  234. // when does it make sense to manyally unsubscribe?
  235. // at this point unsubscribe.then and unsubscribe.catch have been deleted
  236. // unsubscribe(); // don't unsubscribe if we want to wait for additional status
  237. // updates to know when the tx has been finalized
  238. return finalizedPromise.promise;
  239. }
  240. }
  241. module.exports = {
  242. RuntimeApi: RuntimeApi,
  243. }
  244. function newExternallyControlledPromise () {
  245. // externally controller promise
  246. let resolve, reject;
  247. const promise = new Promise((res, rej) => {
  248. resolve = res;
  249. reject = rej;
  250. });
  251. return ({resolve, reject, promise});
  252. }