diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000..6f368922ee --- /dev/null +++ b/.eslintignore @@ -0,0 +1,9 @@ +# +# Copyright 2018 IBM All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +coverage +node_modules +config +.nyc_output diff --git a/build/tasks/ca.js b/build/tasks/ca.js index f143b72bf8..5a8ed51e7f 100644 --- a/build/tasks/ca.js +++ b/build/tasks/ca.js @@ -5,8 +5,8 @@ */ 'use strict'; -var gulp = require('gulp'); -var debug = require('gulp-debug'); +const gulp = require('gulp'); +const debug = require('gulp-debug'); const DEPS = [ 'fabric-client/lib/api.js', @@ -31,7 +31,7 @@ const DEPS = [ 'fabric-client/types/base.d.ts' ]; -gulp.task('ca', function() { +gulp.task('ca', () => { return gulp.src(DEPS, { base: 'fabric-client/' }) .pipe(debug()) .pipe(gulp.dest('fabric-ca-client/')) diff --git a/build/tasks/doc.js b/build/tasks/doc.js index 9af8c64f79..d4809058c6 100644 --- a/build/tasks/doc.js +++ b/build/tasks/doc.js @@ -14,15 +14,15 @@ limitations under the License. */ -var gulp = require('gulp'); -var jsdoc = require('gulp-jsdoc3'); -var del = require('del'); +const gulp = require('gulp'); +const jsdoc = require('gulp-jsdoc3'); +const del = require('del'); -gulp.task('clean', function(){ +gulp.task('clean', () => { return del('./docs/gen/**', {force:true}); }); -gulp.task('doc', ['clean'], function () { +gulp.task('doc', ['clean'], () => { gulp.src([ 'docs/index.md', 'fabric-network/index.js', @@ -37,14 +37,14 @@ gulp.task('doc', ['clean'], function () { 'fabric-ca-client/lib/AffiliationService.js', 'fabric-ca-client/lib/IdentityService.js', ], { read: false }) - .pipe(jsdoc({ - opts: { - tutorials: './docs/tutorials', - destination: './docs/gen' - }, - templates: { - systemName: 'Hyperledger Fabric SDK for node.js', - theme: 'cosmo' //cerulean, cosmo, cyborg, flatly, journal, lumen, paper, readable, sandstone, simplex, slate, spacelab, superhero, united, yeti - } - })); + .pipe(jsdoc({ + opts: { + tutorials: './docs/tutorials', + destination: './docs/gen' + }, + templates: { + systemName: 'Hyperledger Fabric SDK for node.js', + theme: 'cosmo' //cerulean, cosmo, cyborg, flatly, journal, lumen, paper, readable, sandstone, simplex, slate, spacelab, superhero, united, yeti + } + })); }); diff --git a/build/tasks/watch.js b/build/tasks/watch.js index e21b511a7d..a0c12e7979 100644 --- a/build/tasks/watch.js +++ b/build/tasks/watch.js @@ -9,15 +9,15 @@ let gulp = require('gulp'), fs = require('fs'), ca = require('./ca.js'); -gulp.task('watch', function () { +gulp.task('watch', () => { watch(ca.DEPS, { ignoreInitial: false, base: 'fabric-client/' }) - .pipe(debug()) - .pipe(gulp.dest('fabric-ca-client/')); + .pipe(debug()) + .pipe(gulp.dest('fabric-ca-client/')); // only do the following if node_modules/fabric-client and // node_modules/fabric-ca-client are NOT created as sym links - let statsA = fs.lstatSync('node_modules/fabric-client'); - let statsB = fs.lstatSync('node_modules/fabric-ca-client'); + const statsA = fs.lstatSync('node_modules/fabric-client'); + const statsB = fs.lstatSync('node_modules/fabric-ca-client'); if (!statsA.isSymbolicLink() && !statsB.isSymbolicLink()) { watch([ 'fabric-client/index.js', @@ -27,7 +27,7 @@ gulp.task('watch', function () { 'fabric-ca-client/config/**/*', 'fabric-ca-client/lib/**/*' ], { ignoreInitial: false, base: './' }) - .pipe(debug()) - .pipe(gulp.dest('node_modules')); + .pipe(debug()) + .pipe(gulp.dest('node_modules')); } }); diff --git a/fabric-ca-client/.eslintignore b/fabric-ca-client/.eslintignore new file mode 100644 index 0000000000..6f368922ee --- /dev/null +++ b/fabric-ca-client/.eslintignore @@ -0,0 +1,9 @@ +# +# Copyright 2018 IBM All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +coverage +node_modules +config +.nyc_output diff --git a/fabric-ca-client/package.json b/fabric-ca-client/package.json index 3ed5b23a02..b12e684c26 100644 --- a/fabric-ca-client/package.json +++ b/fabric-ca-client/package.json @@ -5,7 +5,8 @@ "version": "1.3.0-snapshot", "main": "index.js", "scripts": { - "test": "nyc mocha --recursive -t 10000" + "lint": "eslint .", + "test": "nyc mocha --exclude 'test/data/**/*.js' --recursive -t 10000" }, "repository": { "type": "github (read mirror)", diff --git a/fabric-client/.eslintignore b/fabric-client/.eslintignore new file mode 100644 index 0000000000..8541390dd6 --- /dev/null +++ b/fabric-client/.eslintignore @@ -0,0 +1,10 @@ +# +# Copyright 2018 IBM All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +coverage +node_modules +config +.nyc_output + diff --git a/fabric-client/lib/Channel.js b/fabric-client/lib/Channel.js index cc31853b55..266bba7cb2 100755 --- a/fabric-client/lib/Channel.js +++ b/fabric-client/lib/Channel.js @@ -2982,7 +2982,7 @@ const Channel = class { if (!request.proposal) { throw Error('Missing "proposal" parameter in transaction request'); } - let proposalResponses = request.proposalResponses; + const proposalResponses = request.proposalResponses; const chaincodeProposal = request.proposal; const endorsements = []; diff --git a/fabric-client/lib/impl/BasicCommitHandler.js b/fabric-client/lib/impl/BasicCommitHandler.js index 4fddcf0812..ffffcfbacd 100644 --- a/fabric-client/lib/impl/BasicCommitHandler.js +++ b/fabric-client/lib/impl/BasicCommitHandler.js @@ -107,7 +107,7 @@ class BasicCommitHandler extends api.CommitHandler { if(orderers && orderers.length > 0) { logger.debug('%s - found %s orderers assigned to channel', method, orderers.length); // loop through the orderers trying to complete one successfully - for(let orderer of orderers) { + for(const orderer of orderers) { logger.debug('%s - starting orderer %s', method, orderer.getName()); try { const results = await orderer.sendBroadcast(envelope, timeout); diff --git a/fabric-client/lib/impl/CouchDBKeyValueStore.js b/fabric-client/lib/impl/CouchDBKeyValueStore.js index 0bd0d2cd32..9afa264d51 100644 --- a/fabric-client/lib/impl/CouchDBKeyValueStore.js +++ b/fabric-client/lib/impl/CouchDBKeyValueStore.js @@ -7,12 +7,12 @@ 'use strict'; -var api = require('../api.js'); -var util = require('util'); -var utils = require('../utils'); -var nano = require('nano'); +const api = require('../api.js'); +const util = require('util'); +const utils = require('../utils'); +const nano = require('nano'); -var logger = utils.getLogger('CouchDBKeyValueStore.js'); +const logger = utils.getLogger('CouchDBKeyValueStore.js'); /** * This is a sample database implementation of the [KeyValueStore]{@link module:api.KeyValueStore} API. @@ -21,7 +21,7 @@ var logger = utils.getLogger('CouchDBKeyValueStore.js'); * @class * @extends module:api.KeyValueStore */ -var CouchDBKeyValueStore = class extends api.KeyValueStore { +const CouchDBKeyValueStore = class extends api.KeyValueStore { /** * @typedef {Object} CouchDBOpts * @property {string} url The CouchDB instance url, in the form of http(s)://:@host:port @@ -43,7 +43,7 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { // Create the keyValStore instance super(); - var self = this; + const self = this; // url is the database instance url this._url = options.url; // Name of the database, optional @@ -53,18 +53,18 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { this._name = options.name; } - return new Promise(function (resolve, reject) { + return new Promise(((resolve, reject) => { // Initialize the CouchDB database client - var dbClient = nano(self._url); + const dbClient = nano(self._url); // Check if the database already exists. If not, create it. - dbClient.db.get(self._name, function (err) { + dbClient.db.get(self._name, (err) => { // Check for error if (err) { // Database doesn't exist if (err.error == 'not_found') { logger.debug('No %s found, creating %s', self._name, self._name); - dbClient.db.create(self._name, function (err) { + dbClient.db.create(self._name, (err) => { if (err) { return reject(new Error(util.format('Failed to create %s database due to error: %s', self._name, err.stack ? err.stack : err))); } @@ -86,15 +86,15 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { resolve(self); } }); - }); + })); } getValue(name) { logger.debug('getValue', { key: name }); - var self = this; - return new Promise(function (resolve, reject) { - self._database.get(name, function (err, body) { + const self = this; + return new Promise(((resolve, reject) => { + self._database.get(name, (err, body) => { // Check for error on retrieving from database if (err) { if (err.error !== 'not_found') { @@ -109,17 +109,17 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { return resolve(body.member); } }); - }); + })); } setValue(name, value) { logger.debug('setValue', { key: name }); - var self = this; + const self = this; - return new Promise(function (resolve, reject) { + return new Promise(((resolve, reject) => { // Attempt to retrieve from the database to see if the entry exists - self._database.get(name, function (err, body) { + self._database.get(name, (err, body) => { // Check for error on retrieving from database if (err) { if (err.error !== 'not_found') { @@ -129,7 +129,7 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { // Entry does not exist logger.debug('setValue: %s, Entry does not exist, insert it.', name); self._dbInsert({ _id: name, member: value }) - .then(function (status) { + .then((status) => { logger.debug('setValue add: ' + name + ', status: ' + status); if (status == true) resolve(value); else reject(new Error('Couch database insert add failed.')); @@ -141,21 +141,21 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { logger.debug('setValue: %s, Retrieved entry from %s. Latest rev number: %s', name, self._name, body._rev); self._dbInsert({ _id: name, _rev: body._rev, member: value }) - .then(function (status) { + .then((status) => { logger.debug('setValue update: ' + name + ', status: ' + status); if (status == true) resolve(value); else reject(new Error('Couch database insert update failed.')); }); } }); - }); + })); } _dbInsert(options) { logger.debug('setValue, _dbInsert', { options: options }); - var self = this; - return new Promise(function (resolve, reject) { - self._database.insert(options, function (err) { + const self = this; + return new Promise(((resolve, reject) => { + self._database.insert(options, (err) => { if (err) { logger.error('setValue, _dbInsert, ERROR: [%s.insert] - ', self._name, err.error); reject(new Error(err.error)); @@ -164,7 +164,7 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { resolve(true); } }); - }); + })); } }; diff --git a/fabric-client/lib/impl/CryptoKeyStore.js b/fabric-client/lib/impl/CryptoKeyStore.js index d2e4056899..3da3bbf32d 100644 --- a/fabric-client/lib/impl/CryptoKeyStore.js +++ b/fabric-client/lib/impl/CryptoKeyStore.js @@ -7,27 +7,27 @@ 'use strict'; -var jsrsasign = require('jsrsasign'); -var KEYUTIL = jsrsasign.KEYUTIL; +const jsrsasign = require('jsrsasign'); +const KEYUTIL = jsrsasign.KEYUTIL; -var utils = require('../utils.js'); -var ECDSAKey = require('./ecdsa/key.js'); +const utils = require('../utils.js'); +const ECDSAKey = require('./ecdsa/key.js'); /* * The mixin enforces the special indexing mechanism with private and public * keys on top of a standard implementation of the KeyValueStore interface * with the getKey() and putKey() methods */ -var CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { +const CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { getKey(ski) { - var self = this; + const self = this; // first try the private key entry, since it encapsulates both // the private key and public key return this.getValue(_getKeyIndex(ski, true)) .then((raw) => { if (raw !== null) { - var privKey = KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(raw); + const privKey = KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(raw); // TODO: for now assuming ECDSA keys only, need to add support for RSA keys return new ECDSAKey(privKey); } @@ -40,15 +40,15 @@ var CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { return key; if (key !== null) { - var pubKey = KEYUTIL.getKey(key); + const pubKey = KEYUTIL.getKey(key); return new ECDSAKey(pubKey); } }); } putKey(key) { - var idx = _getKeyIndex(key.getSKI(), key.isPrivate()); - var pem = key.toBytes(); + const idx = _getKeyIndex(key.getSKI(), key.isPrivate()); + const pem = key.toBytes(); return this.setValue(idx, pem) .then(() => { return key; @@ -68,8 +68,8 @@ var CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { * * @class */ -var CryptoKeyStore = function(KVSImplClass, opts) { - var superClass; +const CryptoKeyStore = function(KVSImplClass, opts) { + let superClass; if (typeof KVSImplClass !== 'function') { let impl_class = utils.getConfigSetting('crypto-value-store'); @@ -84,7 +84,7 @@ var CryptoKeyStore = function(KVSImplClass, opts) { opts = KVSImplClass; } - var MyClass = class extends CryptoKeyStoreMixin(superClass) {}; + const MyClass = class extends CryptoKeyStoreMixin(superClass) {}; return new MyClass(opts); }; diff --git a/fabric-client/lib/impl/FileKeyValueStore.js b/fabric-client/lib/impl/FileKeyValueStore.js index 1084510254..e6f3b35cfe 100644 --- a/fabric-client/lib/impl/FileKeyValueStore.js +++ b/fabric-client/lib/impl/FileKeyValueStore.js @@ -7,12 +7,12 @@ 'use strict'; -var api = require('../api.js'); -var fs = require('fs-extra'); -var path = require('path'); -var utils = require('../utils'); +const api = require('../api.js'); +const fs = require('fs-extra'); +const path = require('path'); +const utils = require('../utils'); -var logger = utils.getLogger('FileKeyValueStore.js'); +const logger = utils.getLogger('FileKeyValueStore.js'); /** * This is a default implementation of the [KeyValueStore]{@link module:api.KeyValueStore} API. @@ -21,7 +21,7 @@ var logger = utils.getLogger('FileKeyValueStore.js'); * @class * @extends module:api.KeyValueStore */ -var FileKeyValueStore = class extends api.KeyValueStore { +const FileKeyValueStore = class extends api.KeyValueStore { /** * constructor @@ -39,27 +39,27 @@ var FileKeyValueStore = class extends api.KeyValueStore { // Create the keyValStore instance super(); - var self = this; + const self = this; this._dir = options.path; - return new Promise(function (resolve, reject) { - fs.mkdirs(self._dir, function (err) { + return new Promise(((resolve, reject) => { + fs.mkdirs(self._dir, (err) => { if (err) { logger.error('constructor, error creating directory, code: %s' , err.code); return reject(err); } return resolve(self); }); - }); + })); } getValue(name) { logger.debug('getValue', { key: name }); - var self = this; + const self = this; - return new Promise(function (resolve, reject) { - var p = path.join(self._dir, name); - fs.readFile(p, 'utf8', function (err, data) { + return new Promise(((resolve, reject) => { + const p = path.join(self._dir, name); + fs.readFile(p, 'utf8', (err, data) => { if (err) { if (err.code !== 'ENOENT') { return reject(err); @@ -69,24 +69,24 @@ var FileKeyValueStore = class extends api.KeyValueStore { } return resolve(data); }); - }); + })); } setValue(name, value) { logger.debug('setValue', { key: name }); - var self = this; + const self = this; - return new Promise(function (resolve, reject) { - var p = path.join(self._dir, name); - fs.writeFile(p, value, function (err) { + return new Promise(((resolve, reject) => { + const p = path.join(self._dir, name); + fs.writeFile(p, value, (err) => { if (err) { reject(err); } else { return resolve(value); } }); - }); + })); } }; diff --git a/fabric-client/lib/impl/NetworkConfig_1_0.js b/fabric-client/lib/impl/NetworkConfig_1_0.js index 943593a155..e3c09dd989 100644 --- a/fabric-client/lib/impl/NetworkConfig_1_0.js +++ b/fabric-client/lib/impl/NetworkConfig_1_0.js @@ -7,15 +7,15 @@ 'use strict'; -var fs = require('fs-extra'); -var path = require('path'); -var utils = require('../utils'); -var Constants = require('../Constants.js'); -var Channel = require('../Channel.js'); -var Organization = require('../Organization.js'); -var CertificateAuthority = require('../CertificateAuthority.js'); - -var logger = utils.getLogger('NetworkConfig101.js'); +const fs = require('fs-extra'); +const path = require('path'); +const utils = require('../utils'); +const Constants = require('../Constants.js'); +const Channel = require('../Channel.js'); +const Organization = require('../Organization.js'); +const CertificateAuthority = require('../CertificateAuthority.js'); + +const logger = utils.getLogger('NetworkConfig101.js'); const CHANNELS_CONFIG = 'channels'; const ORGS_CONFIG = 'organizations'; const PEERS_CONFIG = 'peers'; @@ -37,7 +37,7 @@ const EVENTHUB = 3; const EVENTREG = 4; const TYPES = ['unknown', 'endorser', 'orderer', 'eventHub', 'eventReg']; const REQUEST_TIMEOUT = 'request-timeout'; -var ROLES = Constants.NetworkConfig.ROLES; +const ROLES = Constants.NetworkConfig.ROLES; /** * This is an implementation of the [NetworkConfig]{@link module:api.NetworkConfig} API. @@ -99,7 +99,7 @@ const NetworkConfig_1_0 = class { const result = {}; if(this._network_config && this._network_config.client) { const client_config = this._network_config.client; - for(let setting in client_config) { + for(const setting in client_config) { // copy all except credentialStore, special case to handle paths if(setting !== 'credentialStore') { result[setting] = client_config[setting]; @@ -110,7 +110,7 @@ const NetworkConfig_1_0 = class { if(client_config.credentialStore.path) { result.credentialStore.path = path.resolve(client_config.credentialStore.path); } - for(let setting in client_config.credentialStore) { + for(const setting in client_config.credentialStore) { if(setting !== 'cryptoStore' && setting != 'path') { result.credentialStore[setting] = client_config.credentialStore[setting]; } @@ -120,7 +120,7 @@ const NetworkConfig_1_0 = class { if(client_config.credentialStore.cryptoStore.path) { result.credentialStore.cryptoStore.path = path.resolve(client_config.credentialStore.cryptoStore.path); } - for(let setting in client_config.credentialStore.cryptoStore) { + for(const setting in client_config.credentialStore.cryptoStore) { if(setting != 'path') { result.credentialStore.cryptoStore[setting] = client_config.credentialStore.cryptoStore[setting]; } @@ -227,7 +227,7 @@ const NetworkConfig_1_0 = class { const method = 'getOrganization'; logger.debug('%s - mspid %s',method, mspid); if(mspid && this._network_config && this._network_config[ORGS_CONFIG]) { - for(let name in this._network_config[ORGS_CONFIG]) { + for(const name in this._network_config[ORGS_CONFIG]) { const organization_config = this._network_config[ORGS_CONFIG][name]; if(organization_config.mspid === mspid) { return this.getOrganization(name, only_client); @@ -244,7 +244,7 @@ const NetworkConfig_1_0 = class { if(organization_config) { organization = new Organization(name, organization_config.mspid); if(organization_config[PEERS_CONFIG] && !only_client) { - for(let i in organization_config[PEERS_CONFIG]) { + for(const i in organization_config[PEERS_CONFIG]) { const peer_name = organization_config[PEERS_CONFIG][i]; const peer = this.getPeer(peer_name); if(peer) { @@ -253,7 +253,7 @@ const NetworkConfig_1_0 = class { } } if(organization_config[CAS_CONFIG]) { - for(let i in organization_config[CAS_CONFIG]) { + for(const i in organization_config[CAS_CONFIG]) { const ca_name = organization_config[CAS_CONFIG][i]; const ca = this.getCertificateAuthority(ca_name); if(ca) organization.addCertificateAuthority(ca); @@ -278,7 +278,7 @@ const NetworkConfig_1_0 = class { logger.debug('%s - start',method); const organizations = []; if(this._network_config && this._network_config[ORGS_CONFIG]) { - for(let organization_name in this._network_config[ORGS_CONFIG]) { + for(const organization_name in this._network_config[ORGS_CONFIG]) { const organization = this.getOrganization(organization_name); organizations.push(organization); } @@ -317,8 +317,8 @@ const NetworkConfig_1_0 = class { if(this._network_config && this._network_config[CHANNELS_CONFIG] && this._network_config[CHANNELS_CONFIG][channel.getName()] ) { - let orderer_names = this._network_config[CHANNELS_CONFIG][channel.getName()][ORDERERS_CONFIG]; - if(Array.isArray(orderer_names)) for(let i in orderer_names){ + const orderer_names = this._network_config[CHANNELS_CONFIG][channel.getName()][ORDERERS_CONFIG]; + if(Array.isArray(orderer_names)) for(const i in orderer_names){ const orderer_name = orderer_names[i]; const orderer = this.getOrderer(orderer_name); if(orderer) channel.addOrderer(orderer); @@ -335,12 +335,12 @@ const NetworkConfig_1_0 = class { if(this._network_config && this._network_config[CHANNELS_CONFIG] && this._network_config[CHANNELS_CONFIG][channel.getName()] ) { - let channel_peers = this._network_config[CHANNELS_CONFIG][channel.getName()][PEERS_CONFIG]; - if(channel_peers) for(let peer_name in channel_peers) { + const channel_peers = this._network_config[CHANNELS_CONFIG][channel.getName()][PEERS_CONFIG]; + if(channel_peers) for(const peer_name in channel_peers) { const channel_peer = channel_peers[peer_name]; const peer = this.getPeer(peer_name); const roles = {}; - for(let i in ROLES) { + for(const i in ROLES) { if(typeof channel_peer[ROLES[i]] === 'boolean') { roles[ROLES[i]] = channel_peer[ROLES[i]]; } @@ -361,9 +361,9 @@ const NetworkConfig_1_0 = class { */ _getOrganizationForPeer(peer_name) { if(this._network_config && this._network_config[ORGS_CONFIG]) { - for(let organization_name in this._network_config[ORGS_CONFIG]) { - let organization = this.getOrganization(organization_name); - for(let i in organization._peers) { + for(const organization_name in this._network_config[ORGS_CONFIG]) { + const organization = this.getOrganization(organization_name); + for(const i in organization._peers) { if(peer_name === organization._peers[i].getName()) { return organization_name; } @@ -379,7 +379,7 @@ const NetworkConfig_1_0 = class { */ _getMspIdForOrganization(org_name) { if(this._network_config && this._network_config[ORGS_CONFIG]) { - let organization = this.getOrganization(org_name); + const organization = this.getOrganization(org_name); if(organization) { return organization.getMspid(); } @@ -414,8 +414,8 @@ function getPEMfromConfig(config) { function readFileSync(config_path) { try { - let config_loc = path.resolve(config_path); - let data = fs.readFileSync(config_loc); + const config_loc = path.resolve(config_path); + const data = fs.readFileSync(config_loc); return Buffer.from(data).toString(); } catch(err) { logger.error('NetworkConfig101 - problem reading the PEM file :: ' + err); diff --git a/fabric-client/lib/impl/aes/pkcs11_key.js b/fabric-client/lib/impl/aes/pkcs11_key.js index f122f4bc9a..7707d44320 100644 --- a/fabric-client/lib/impl/aes/pkcs11_key.js +++ b/fabric-client/lib/impl/aes/pkcs11_key.js @@ -7,9 +7,9 @@ 'use strict'; -var api = require('../../api.js'); +const api = require('../../api.js'); -var PKCS11_AES_KEY = class extends api.Key { +const PKCS11_AES_KEY = class extends api.Key { constructor(attr, size) { if (typeof attr === 'undefined' || attr === null) diff --git a/fabric-client/lib/impl/ecdsa/key.js b/fabric-client/lib/impl/ecdsa/key.js index a0be017de6..b39046d60d 100644 --- a/fabric-client/lib/impl/ecdsa/key.js +++ b/fabric-client/lib/impl/ecdsa/key.js @@ -138,7 +138,7 @@ module.exports = class ECDSA_KEY extends api.Key { */ generateX509Certificate(commonName) { - var subjectDN = '/CN=self'; + let subjectDN = '/CN=self'; if (commonName) { subjectDN = '/CN=' + commonName; } @@ -150,7 +150,7 @@ module.exports = class ECDSA_KEY extends api.Key { try { //var before = Date.now() - 60000; //var after = Date.now() + 60000; - var certPEM = asn1.x509.X509Util.newCertPEM({ + const certPEM = asn1.x509.X509Util.newCertPEM({ serial: { int: 4 }, sigalg: { name: 'SHA256withECDSA' }, issuer: { str: subjectDN }, diff --git a/fabric-client/lib/impl/ecdsa/pkcs11_key.js b/fabric-client/lib/impl/ecdsa/pkcs11_key.js index afe472cffe..7179ae36b8 100644 --- a/fabric-client/lib/impl/ecdsa/pkcs11_key.js +++ b/fabric-client/lib/impl/ecdsa/pkcs11_key.js @@ -7,12 +7,12 @@ 'use strict'; -var api = require('../../api.js'); -var jsrsa = require('jsrsasign'); -var asn1 = jsrsa.asn1; +const api = require('../../api.js'); +const jsrsa = require('jsrsasign'); +const asn1 = jsrsa.asn1; -var elliptic = require('elliptic'); -var EC = elliptic.ec; +const elliptic = require('elliptic'); +const EC = elliptic.ec; /** @@ -22,7 +22,7 @@ var EC = elliptic.ec; * @class PKCS11_ECDSA_KEY * @extends module:api.Key */ -var PKCS11_ECDSA_KEY = class extends api.Key { +const PKCS11_ECDSA_KEY = class extends api.Key { constructor(attr, size) { if (typeof attr === 'undefined' || attr === null) @@ -74,39 +74,39 @@ var PKCS11_ECDSA_KEY = class extends api.Key { csr.asn1SignatureAlg = new asn1.x509.AlgorithmIdentifier({'name': sigAlgName}); - var digest = this._cryptoSuite.hash(Buffer.from(csr.asn1CSRInfo.getEncodedHex(), 'hex')); - var sig = this._cryptoSuite.sign(this, Buffer.from(digest, 'hex')); + const digest = this._cryptoSuite.hash(Buffer.from(csr.asn1CSRInfo.getEncodedHex(), 'hex')); + const sig = this._cryptoSuite.sign(this, Buffer.from(digest, 'hex')); csr.hexSig = sig.toString('hex'); csr.asn1Sig = new asn1.DERBitString({'hex': '00' + csr.hexSig}); - var seq = new asn1.DERSequence({'array': [csr.asn1CSRInfo, csr.asn1SignatureAlg, csr.asn1Sig]}); + const seq = new asn1.DERSequence({'array': [csr.asn1CSRInfo, csr.asn1SignatureAlg, csr.asn1Sig]}); csr.hTLV = seq.getEncodedHex(); csr.isModified = false; } newCSRPEM(param) { - var _KJUR_asn1_csr = asn1.csr; + const _KJUR_asn1_csr = asn1.csr; if (param.subject === undefined) throw 'parameter subject undefined'; if (param.sbjpubkey === undefined) throw 'parameter sbjpubkey undefined'; if (param.sigalg === undefined) throw 'parameter sigalg undefined'; if (param.sbjprvkey === undefined) throw 'parameter sbjpubkey undefined'; - var ecdsa = new EC(this._cryptoSuite._ecdsaCurve); - var pubKey = ecdsa.keyFromPublic(this._pub._ecpt); - var csri = new _KJUR_asn1_csr.CertificationRequestInfo(); + const ecdsa = new EC(this._cryptoSuite._ecdsaCurve); + const pubKey = ecdsa.keyFromPublic(this._pub._ecpt); + const csri = new _KJUR_asn1_csr.CertificationRequestInfo(); csri.setSubjectByParam(param.subject); csri.setSubjectPublicKeyByGetKey({xy: pubKey.getPublic('hex'), curve: 'secp256r1'}); if (param.ext !== undefined && param.ext.length !== undefined) { - for (let ext of param.ext) { - for (let key in ext) { + for (const ext of param.ext) { + for (const key in ext) { csri.appendExtensionByName(key, ext[key]); } } } - var csr = new _KJUR_asn1_csr.CertificationRequest({'csrinfo': csri}); + const csr = new _KJUR_asn1_csr.CertificationRequest({'csrinfo': csri}); this.signCSR(csr, param.sigalg); - var pem = csr.getPEMString(); + const pem = csr.getPEMString(); return pem; } @@ -127,7 +127,7 @@ var PKCS11_ECDSA_KEY = class extends api.Key { } try { - var csr = this.newCSRPEM({ + const csr = this.newCSRPEM({ subject: { str: asn1.x509.X500Name.ldapToOneline(subjectDN)}, sbjpubkey: this._pub, sigalg: 'SHA256withECDSA', diff --git a/fabric-client/lib/msp/identity.js b/fabric-client/lib/msp/identity.js index 8024074daa..7517e2ade2 100755 --- a/fabric-client/lib/msp/identity.js +++ b/fabric-client/lib/msp/identity.js @@ -112,7 +112,7 @@ class Identity { * @returns {Buffer} protobuf-based serialization with two fields: "mspid" and "certificate PEM bytes" */ serialize() { - var serializedIdentity = new identityProto.SerializedIdentity(); + const serializedIdentity = new identityProto.SerializedIdentity(); serializedIdentity.setMspid(this.getMSPId()); serializedIdentity.setIdBytes(Buffer.from(this._certificate)); return serializedIdentity.toBuffer(); @@ -219,7 +219,7 @@ class SigningIdentity extends Identity { */ sign(msg, opts) { // calculate the hash for the message before signing - var hashFunction; + let hashFunction; if (opts && opts.hashFunction) { if (typeof opts.hashFunction !== 'function') { throw new Error('The "hashFunction" field must be a function'); @@ -230,7 +230,7 @@ class SigningIdentity extends Identity { hashFunction = this._cryptoSuite.hash.bind(this._cryptoSuite); } - var digest = hashFunction(msg); + const digest = hashFunction(msg); return this._signer.sign(Buffer.from(digest, 'hex'), null); } diff --git a/fabric-client/lib/msp/msp-manager.js b/fabric-client/lib/msp/msp-manager.js index 1fcb15d074..c445455ade 100755 --- a/fabric-client/lib/msp/msp-manager.js +++ b/fabric-client/lib/msp/msp-manager.js @@ -7,16 +7,16 @@ 'use strict'; -var util = require('util'); -var path = require('path'); -var grpc = require('grpc'); +const util = require('util'); +const path = require('path'); +const grpc = require('grpc'); -var MSP = require('./msp.js'); -var utils = require('../utils.js'); -var logger = utils.getLogger('MSPManager.js'); +const MSP = require('./msp.js'); +const utils = require('../utils.js'); +const logger = utils.getLogger('MSPManager.js'); -var mspProto = grpc.load(path.join(__dirname, '../protos/msp/msp_config.proto')).msp; -var identityProto = grpc.load(path.join(__dirname, '../protos/msp/identities.proto')).msp; +const mspProto = grpc.load(path.join(__dirname, '../protos/msp/msp_config.proto')).msp; +const identityProto = grpc.load(path.join(__dirname, '../protos/msp/identities.proto')).msp; /** * MSPManager is an interface defining a manager of one or more MSPs. This essentially acts @@ -25,7 +25,7 @@ var identityProto = grpc.load(path.join(__dirname, '../protos/msp/identities.pro * * @class */ -var MSPManager = class { +const MSPManager = class { constructor() { this._msps = {}; } @@ -41,7 +41,7 @@ var MSPManager = class { */ loadMSPs(mspConfigs) { logger.debug('loadMSPs - start number of msps=%s',mspConfigs.length); - var self = this; + const self = this; if (!mspConfigs || !Array.isArray(mspConfigs)) throw new Error('"mspConfigs" argument must be an array'); @@ -52,7 +52,7 @@ var MSPManager = class { if (!config.getConfig || !config.getConfig()) throw new Error('MSP Configuration object missing the payload in the "Config" property'); - var fabricConfig = mspProto.FabricMSPConfig.decode(config.getConfig()); + const fabricConfig = mspProto.FabricMSPConfig.decode(config.getConfig()); if (!fabricConfig.getName()) throw new Error('MSP Configuration does not have a name'); @@ -65,20 +65,20 @@ var MSPManager = class { // TODO: for now using application-scope defaults but crypto parameters like key size, hash family // and digital signature algorithm should be from the config itself - var cs = utils.newCryptoSuite(); + const cs = utils.newCryptoSuite(); cs.setCryptoKeyStore(utils.newCryptoKeyStore()); // get the application org names - var orgs = []; - let org_units = fabricConfig.getOrganizationalUnitIdentifiers(); + const orgs = []; + const org_units = fabricConfig.getOrganizationalUnitIdentifiers(); if(org_units) for(let i = 0; i < org_units.length; i++) { - let org_unit = org_units[i]; - let org_id = org_unit.organizational_unit_identifier; + const org_unit = org_units[i]; + const org_id = org_unit.organizational_unit_identifier; logger.debug('loadMSPs - found org of :: %s',org_id); orgs.push(org_id); } - var newMSP = new MSP({ + const newMSP = new MSP({ rootCerts: fabricConfig.getRootCerts(), intermediateCerts: fabricConfig.getIntermediateCerts(), admins: fabricConfig.getAdmins(), @@ -111,7 +111,7 @@ var MSPManager = class { */ addMSP(config) { if(!config.cryptoSuite) config.cryptoSuite = utils.newCryptoSuite(); - var msp = new MSP(config); + const msp = new MSP(config); logger.debug('addMSP - msp=',msp.getId()); this._msps[msp.getId()] = msp; return msp; @@ -138,9 +138,9 @@ var MSPManager = class { * @returns {Promise} Promise for an {@link Identity} instance */ deserializeIdentity(serializedIdentity) { - var sid = identityProto.SerializedIdentity.decode(serializedIdentity); - var mspid = sid.getMspid(); - var msp = this._msps[mspid]; + const sid = identityProto.SerializedIdentity.decode(serializedIdentity); + const mspid = sid.getMspid(); + const msp = this._msps[mspid]; if (!msp) throw new Error(util.format('Failed to locate an MSP instance matching the requested id "%s" in the deserialized identity', mspid)); diff --git a/fabric-client/lib/msp/msp.js b/fabric-client/lib/msp/msp.js index ef1ad5a6bc..e77f4e9e1b 100755 --- a/fabric-client/lib/msp/msp.js +++ b/fabric-client/lib/msp/msp.js @@ -5,16 +5,16 @@ */ 'use strict'; -var api = require('../api.js'); -var idModule = require('./identity.js'); -var Identity = idModule.Identity; -var SigningIdentity = idModule.SigningIdentity; -var utils = require('../utils.js'); -var logger = utils.getLogger('msp.js'); +const api = require('../api.js'); +const idModule = require('./identity.js'); +const Identity = idModule.Identity; +const SigningIdentity = idModule.SigningIdentity; +const utils = require('../utils.js'); +const logger = utils.getLogger('msp.js'); -var grpc = require('grpc'); -var identityProto = grpc.load(__dirname + '/../protos/msp/identities.proto').msp; -var _mspConfigProto = grpc.load(__dirname + '/../protos/msp/msp_config.proto').msp; +const grpc = require('grpc'); +const identityProto = grpc.load(__dirname + '/../protos/msp/identities.proto').msp; +const _mspConfigProto = grpc.load(__dirname + '/../protos/msp/msp_config.proto').msp; /** @@ -24,7 +24,7 @@ var _mspConfigProto = grpc.load(__dirname + '/../protos/msp/msp_config.proto').m * and PKIs (software-managed or HSM based) * @class */ -var MSP = class { +const MSP = class { /** * Setup the MSP instance according to configuration information * @param {Object} config A configuration object specific to the implementation. For this @@ -114,9 +114,9 @@ var MSP = class { * Returns the Protobuf representation of this MSP Config */ toProtobuf() { - var proto_msp_config = new _mspConfigProto.MSPConfig(); + const proto_msp_config = new _mspConfigProto.MSPConfig(); proto_msp_config.setType(0); //FABRIC - var proto_fabric_msp_config = new _mspConfigProto.FabricMSPConfig(); + const proto_fabric_msp_config = new _mspConfigProto.FabricMSPConfig(); proto_fabric_msp_config.setName(this._id); proto_fabric_msp_config.setRootCerts(this._rootCerts); if(this._intermediateCerts) { @@ -150,18 +150,18 @@ var MSP = class { */ deserializeIdentity(serializedIdentity, storeKey) { logger.debug('importKey - start'); - var store_key = true; //default + let store_key = true; //default // if storing is not required and therefore a promise will not be returned // then storeKey must be set to false; if(typeof storeKey === 'boolean') { store_key = storeKey; } - var sid = identityProto.SerializedIdentity.decode(serializedIdentity); - var cert = sid.getIdBytes().toBinary(); + const sid = identityProto.SerializedIdentity.decode(serializedIdentity); + const cert = sid.getIdBytes().toBinary(); logger.debug('Encoded cert from deserialized identity: %s', cert); if(!store_key) { - var publicKey =this.cryptoSuite.importKey(cert, { algorithm: api.CryptoAlgorithms.X509Certificate, ephemeral: true }); - var sdk_identity = new Identity(cert, publicKey, this.getId(), this.cryptoSuite); + const publicKey =this.cryptoSuite.importKey(cert, { algorithm: api.CryptoAlgorithms.X509Certificate, ephemeral: true }); + const sdk_identity = new Identity(cert, publicKey, this.getId(), this.cryptoSuite); return sdk_identity; } else { diff --git a/fabric-client/package.json b/fabric-client/package.json index fa2ea8a23d..420a53e188 100644 --- a/fabric-client/package.json +++ b/fabric-client/package.json @@ -5,7 +5,8 @@ "version": "1.3.0-snapshot", "main": "index.js", "scripts": { - "test": "nyc mocha --recursive -t 10000" + "lint": "eslint .", + "test": "nyc mocha --exclude 'test/data/**/*.js' --recursive -t 10000" }, "repository": { "type": "github (read mirror)", diff --git a/fabric-client/test/Peer.js b/fabric-client/test/Peer.js index 140a580887..ed82404fa8 100644 --- a/fabric-client/test/Peer.js +++ b/fabric-client/test/Peer.js @@ -302,7 +302,6 @@ describe('Peer', () => { error: () => {} }; - const debugStub = sandbox.stub(FakeLogger, 'debug'); PeerRewire.__set__('logger', FakeLogger); PeerRewire.__set__('Peer.prototype.waitForReady', sinon.stub().resolves()); const endorserClient = sinon.stub(); diff --git a/fabric-client/test/User.js b/fabric-client/test/User.js index 98b06b5e12..0ba5c49b8d 100644 --- a/fabric-client/test/User.js +++ b/fabric-client/test/User.js @@ -728,7 +728,7 @@ describe('User', () => { }; const FakeIdentity = sandbox.stub(); - const promise = new Promise(function(resolve, reject){ resolve( {isPrivate(){ return false;}});}); + const promise = new Promise(((resolve) => { resolve( {isPrivate(){ return false;}});})); sandbox.stub(FakeCryptoSuite, 'importKey').returns(promise); sandbox.stub(FakeSdkUtils, 'newCryptoSuite').returns(FakeCryptoSuite); diff --git a/fabric-client/test/utils.js b/fabric-client/test/utils.js index 7d73dca8e1..a2c8e68449 100644 --- a/fabric-client/test/utils.js +++ b/fabric-client/test/utils.js @@ -83,7 +83,6 @@ describe('Utils', () => { it('should throw an error if csImpl does not exist', () => { const settings = { }; - const MockCryptoSuite = sinon.stub(); const getConfigSettingStub = sandbox.stub(); getConfigSettingStub.withArgs('crypto-hsm').returns(true); getConfigSettingStub.withArgs('crypto-suite-hsm').returns({}); diff --git a/fabric-common/.eslintignore b/fabric-common/.eslintignore new file mode 100644 index 0000000000..6f368922ee --- /dev/null +++ b/fabric-common/.eslintignore @@ -0,0 +1,9 @@ +# +# Copyright 2018 IBM All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +coverage +node_modules +config +.nyc_output diff --git a/fabric-common/package.json b/fabric-common/package.json index ea79977b3c..c29bc4cf36 100644 --- a/fabric-common/package.json +++ b/fabric-common/package.json @@ -17,7 +17,8 @@ "email": "fabric@lists.hyperledger.org" }, "scripts": { - "test": "nyc mocha --recursive -t 10000" + "lint": "eslint .", + "test": "nyc mocha --exclude 'test/data/**/*.js' --recursive -t 10000" }, "dependencies": { }, diff --git a/fabric-network/.eslintignore b/fabric-network/.eslintignore new file mode 100644 index 0000000000..6f368922ee --- /dev/null +++ b/fabric-network/.eslintignore @@ -0,0 +1,9 @@ +# +# Copyright 2018 IBM All Rights Reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +coverage +node_modules +config +.nyc_output diff --git a/fabric-network/package.json b/fabric-network/package.json index 1e270a0447..e62d1372c9 100644 --- a/fabric-network/package.json +++ b/fabric-network/package.json @@ -1,7 +1,10 @@ { "name": "fabric-network", "description": "SDK for writing node.js applications to interact with Hyperledger Fabric. This package encapsulates the APIs to connect to a Fabric network, submit transactions and perform queries against the ledger.", - "keywords" : ["hyperledger", "blockchain"], + "keywords": [ + "hyperledger", + "blockchain" + ], "version": "1.3.0-snapshot", "main": "index.js", "repository": { @@ -14,7 +17,8 @@ "email": "fabric@lists.hyperledger.org" }, "scripts": { - "test": "nyc mocha --recursive -t 10000" + "lint": "eslint .", + "test": "nyc mocha --exclude 'test/data/**/*.js' --recursive -t 10000" }, "types": "./types/index.d.ts", "dependencies": { diff --git a/fabric-network/test/impl/wallet/inmemorywallet.js b/fabric-network/test/impl/wallet/inmemorywallet.js index 25ee5e8767..1dcf32e3d7 100644 --- a/fabric-network/test/impl/wallet/inmemorywallet.js +++ b/fabric-network/test/impl/wallet/inmemorywallet.js @@ -163,7 +163,7 @@ mb3MM6J+V7kciO3hSyP5OJSBPWGlsjxQj2m55aFutmlleVfr6YiaLnYd }); it('should test the non-existence of an identity from the wallet', async () => { - let exists = await wallet.exists('user3'); + const exists = await wallet.exists('user3'); exists.should.equal(false); }); }); @@ -201,7 +201,7 @@ mb3MM6J+V7kciO3hSyP5OJSBPWGlsjxQj2m55aFutmlleVfr6YiaLnYd describe('#list', () => { it('should return an empty list for no identities in the wallet', async () => { - let labels = await wallet.getAllLabels(); + const labels = await wallet.getAllLabels(); labels.forEach(async label => await wallet.delete(label)); const list = await wallet.list(); list.length.should.equal(0); diff --git a/gulpfile.js b/gulpfile.js index 5f5596cd80..76b312e129 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -3,12 +3,12 @@ # # SPDX-License-Identifier: Apache-2.0 */ -var requireDir = require('require-dir'); -var gulp = require('gulp'); +const requireDir = require('require-dir'); +const gulp = require('gulp'); // Require all tasks in gulp/tasks, including subfolders requireDir('./build/tasks', { recurse: true }); -gulp.task('default', ['lint', 'check_license'], function () { - // This will only run if the lint task is successful... +gulp.task('default', ['lint', 'check_license'], () => { + // This will only run if the lint task is successful... }); diff --git a/package.json b/package.json index da617c3d8f..66da2f9e0b 100644 --- a/package.json +++ b/package.json @@ -28,8 +28,8 @@ "elliptic": "^6.3.2", "eslint": "^5.1.0", "fabric-ca-client": "file:./fabric-ca-client", - "fabric-client": "file:./fabric-client", - "fabric-common": "file:./fabric-common", + "fabric-client": "file:./fabric-client", + "fabric-common": "file:./fabric-common", "fabric-network": "file:./fabric-network", "fs-extra": "^6.0.1", "gulp": "^3.9.1", @@ -69,10 +69,10 @@ "fabric-ca-client/lib/FabricCAClientImpl.js", "fabric-ca-client/lib/helper.js", "fabric-ca-client/lib/IdentityService.js", - "fabric-ca-client/lib/AffiliationService.js", - "fabric-client/lib/**/*.js", - "fabric-common/lib/**/*.js", - "fabric-network/lib/**/*.js" + "fabric-ca-client/lib/AffiliationService.js", + "fabric-client/lib/**/*.js", + "fabric-common/lib/**/*.js", + "fabric-network/lib/**/*.js" ], "reporter": [ "lcov", diff --git a/test/fixtures/src/node_cc/example_cc/chaincode.js b/test/fixtures/src/node_cc/example_cc/chaincode.js index b11482123c..282f32a7fe 100644 --- a/test/fixtures/src/node_cc/example_cc/chaincode.js +++ b/test/fixtures/src/node_cc/example_cc/chaincode.js @@ -19,19 +19,19 @@ limitations under the License. const shim = require('fabric-shim'); // An log4js logger instance -var logger = shim.newLogger('example_cc0'); +const logger = shim.newLogger('example_cc0'); // The logger level can also be set by environment variable 'CORE_CHAINCODE_LOGGING_SHIM' // to CRITICAL, ERROR, WARNING, DEBUG logger.level = 'info'; -var Chaincode = class { +const Chaincode = class { async Init(stub) { logger.info('########### example_cc0 Init ###########'); - let ret = stub.getFunctionAndParameters(); + const ret = stub.getFunctionAndParameters(); let A, B; // Entities let Aval, Bval; // Asset holdings - let args = ret.params; + const args = ret.params; if (args.length === 4) { A = args[0]; @@ -63,9 +63,9 @@ var Chaincode = class { async Invoke(stub) { logger.info('########### example_cc0 Invoke ###########'); - let ret = stub.getFunctionAndParameters(); - let fcn = ret.fcn; - let args = ret.params; + const ret = stub.getFunctionAndParameters(); + const fcn = ret.fcn; + const args = ret.params; if (fcn === 'delete') { return this.delete(stub, args); @@ -106,7 +106,7 @@ var Chaincode = class { B = args[1]; try { - let Avalbytes = await stub.getState(A); + const Avalbytes = await stub.getState(A); if (!Avalbytes) { return shim.error('Entity A not found'); } @@ -117,7 +117,7 @@ var Chaincode = class { } try { - let Bvalbytes = await stub.getState(B); + const Bvalbytes = await stub.getState(B); if (!Bvalbytes) { return shim.error('Entity B not found'); } @@ -154,7 +154,7 @@ var Chaincode = class { return shim.error('Incorrect number of arguments. Expecting 1'); } - let A = args[0]; + const A = args[0]; try { await stub.deleteState(A); @@ -172,11 +172,11 @@ var Chaincode = class { return shim.error('Incorrect number of arguments. Expecting name of the person to query'); } - let A = args[0]; + const A = args[0]; let Aval; // Get the state from the ledger try { - let Avalbytes = await stub.getState(A); + const Avalbytes = await stub.getState(A); if (!Avalbytes) { return shim.error('Entity A not found'); } @@ -185,7 +185,7 @@ var Chaincode = class { return shim.error('Failed to get state A'); } - let jsonResp = { + const jsonResp = { Name: A, Amount: Aval }; @@ -205,7 +205,7 @@ var Chaincode = class { return shim.error('Incorrect number of arguments. Expecting name of the chaincode and function to call'); } - let chaincode_name = args.shift().toString(); + const chaincode_name = args.shift().toString(); logger.info('Calling chaincode:%s with function:%s argument 1:%s \n', chaincode_name, args[0].toString(), parseInt(args[1])); diff --git a/test/fixtures/src/node_cc/example_cc1/chaincode.js b/test/fixtures/src/node_cc/example_cc1/chaincode.js index 89d41fac59..0dc3a520a8 100644 --- a/test/fixtures/src/node_cc/example_cc1/chaincode.js +++ b/test/fixtures/src/node_cc/example_cc1/chaincode.js @@ -19,12 +19,12 @@ limitations under the License. const shim = require('fabric-shim'); // An log4js logger instance -var logger = shim.newLogger('example_cc1'); +const logger = shim.newLogger('example_cc1'); // The logger level can also be set by environment variable 'CORE_CHAINCODE_LOGGING_SHIM' // to CRITICAL, ERROR, WARNING, DEBUG logger.level = 'info'; -var Chaincode = class { +const Chaincode = class { async Init(stub) { logger.info('########### example_cc1 Init ###########'); @@ -34,9 +34,9 @@ var Chaincode = class { async Invoke(stub) { logger.info('########### example_cc1 Invoke ###########'); - let ret = stub.getFunctionAndParameters(); - let fcn = ret.fcn; - let args = ret.params; + const ret = stub.getFunctionAndParameters(); + const fcn = ret.fcn; + const args = ret.params; if (fcn === 'delete') { return this.delete(stub, args); @@ -77,7 +77,7 @@ var Chaincode = class { B = args[1]; try { - let Avalbytes = await stub.getState(A); + const Avalbytes = await stub.getState(A); if (!Avalbytes) { return shim.error('Entity A not found'); } @@ -88,7 +88,7 @@ var Chaincode = class { } try { - let Bvalbytes = await stub.getState(B); + const Bvalbytes = await stub.getState(B); if (!Bvalbytes) { return shim.error('Entity B not found'); } @@ -122,7 +122,7 @@ var Chaincode = class { return shim.error('Incorrect number of arguments. Expecting 1'); } - let A = args[0]; + const A = args[0]; try { await stub.deleteState(A); @@ -138,11 +138,11 @@ var Chaincode = class { return shim.error('Incorrect number of arguments. Expecting name of the person to query'); } - let A = args[0]; + const A = args[0]; let Aval; // Get the state from the ledger try { - let Avalbytes = await stub.getState(A); + const Avalbytes = await stub.getState(A); if (!Avalbytes) { return shim.error('Entity A not found'); } @@ -151,7 +151,7 @@ var Chaincode = class { return shim.error('Failed to get state A'); } - let jsonResp = { + const jsonResp = { Name: A, Amount: Aval }; @@ -174,7 +174,7 @@ var Chaincode = class { return shim.error(Buffer.from('{"Error":"Did not find expected transient map in the proposal}')); } - let v = tm.map.test; + const v = tm.map.test; if (!v) { logger.error('Did not find expected key "test" in the transient map of the proposal'); diff --git a/test/integration/channel-event-hub.js b/test/integration/channel-event-hub.js index 1414dc5571..28525fdc75 100644 --- a/test/integration/channel-event-hub.js +++ b/test/integration/channel-event-hub.js @@ -57,7 +57,7 @@ test('***** Test channel events', async (t) => { }; })(t, eventhubs, t.end); - let tlsInfo = await e2eUtils.tlsEnroll('org1'); + const tlsInfo = await e2eUtils.tlsEnroll('org1'); client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); const store = await Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg('peerOrg1')}); client.setStateStore(store); @@ -454,7 +454,7 @@ test('***** Test channel events', async (t) => { t.fail('Failed to replay all the block events'); throw new Error('Replay Error callback was called with ::' + error); }, - {startBlock : 0, endBlock : current_block} + {startBlock : 0, endBlock : current_block} ); eh2.connect(true); }); @@ -495,7 +495,7 @@ test('***** Test channel events', async (t) => { } }, - {startBlock : 0, endBlock : 'newest'} + {startBlock : 0, endBlock : 'newest'} ); eh2.connect(true); //need to connect as disconnect was called }); diff --git a/test/integration/client.js b/test/integration/client.js index f6924f67e5..95d7ea6d91 100644 --- a/test/integration/client.js +++ b/test/integration/client.js @@ -6,38 +6,38 @@ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('integration.client'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('integration.client'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var path = require('path'); -var fs = require('fs-extra'); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const path = require('path'); +const fs = require('fs-extra'); -var Client = require('fabric-client'); -var testUtil = require('../unit/util.js'); -var couchdbUtil = require('./couchdb-util.js'); +const Client = require('fabric-client'); +const testUtil = require('../unit/util.js'); +const couchdbUtil = require('./couchdb-util.js'); -var tag = 'integration.client: '; -var caImport; +const tag = 'integration.client: '; +let caImport; logger.debug('caImport = %s', JSON.stringify(caImport)); -test('\n\n ** createUser happy path - file store **\n\n', function (t) { +test('\n\n ** createUser happy path - file store **\n\n', (t) => { testUtil.resetDefaults(); Client.addConfigFile(path.join(__dirname, '../fixtures/caimport.json')); caImport = utils.getConfigSetting('ca-import', 'notfound'); utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); utils.setConfigSetting('crypto-keysize', 256); - var userOrg = 'org1'; + const userOrg = 'org1'; - var prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); - var sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); + const prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); + const sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); - var keyStoreOpts = {path: path.join(testUtil.getTempDir(), caImport.orgs[userOrg].storePath)}; - var client = new Client(); - var cryptoSuite = Client.newCryptoSuite(); + const keyStoreOpts = {path: path.join(testUtil.getTempDir(), caImport.orgs[userOrg].storePath)}; + const client = new Client(); + const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); @@ -49,186 +49,186 @@ test('\n\n ** createUser happy path - file store **\n\n', function (t) { } return utils.newKeyValueStore(keyStoreOpts) - .then((store) => { - logger.debug('store: %s',store); - client.setStateStore(store); - return ''; - }).then(() => { - return client.createUser( - {username: caImport.orgs[userOrg].username, - mspid: caImport.orgs[userOrg].mspid, - cryptoContent: { privateKey: prvKey, signedCert: sgnCert } - }); - }, (err) => { - logger.error(err.stack ? err.stack : err); - throw new Error('Failed createUser.'); - }).then((user) => { - if (user) { - t.pass(tag+': got user'); + .then((store) => { + logger.debug('store: %s',store); + client.setStateStore(store); + return ''; + }).then(() => { + return client.createUser( + {username: caImport.orgs[userOrg].username, + mspid: caImport.orgs[userOrg].mspid, + cryptoContent: { privateKey: prvKey, signedCert: sgnCert } + }); + }, (err) => { + logger.error(err.stack ? err.stack : err); + throw new Error('Failed createUser.'); + }).then((user) => { + if (user) { + t.pass(tag+': got user'); + t.end(); + } else { + t.fail(tag+'createUser returned null'); + t.end(); + } + }).catch((err) => { + t.fail(tag+': error, did not get user'); + t.comment(err.stack ? err.stack : err); t.end(); - } else { - t.fail(tag+'createUser returned null'); - t.end(); - } - }).catch((err) => { - t.fail(tag+': error, did not get user'); - t.comment(err.stack ? err.stack : err); - t.end(); - }); + }); }); -test('\n\n ** createUser happy path - CouchDB **\n\n', function (t) { +test('\n\n ** createUser happy path - CouchDB **\n\n', (t) => { // Use the CouchDB specific config file Client.addConfigFile('test/fixtures/couchdb.json'); utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js');//override - var couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); - var couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); - var keyValStorePath = couchdbIPAddr + ':' + couchdbPort; + const couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); + const couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); + const keyValStorePath = couchdbIPAddr + ':' + couchdbPort; // Clean up the couchdb test database - var userOrg = 'org1'; - var dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); - var keyStoreOpts = {name: dbname, url: keyValStorePath}; + const userOrg = 'org1'; + const dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); + const keyStoreOpts = {name: dbname, url: keyValStorePath}; logger.debug('couch keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); - var prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); - var sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); + const prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); + const sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); - var client = new Client(); - var cryptoSuite = Client.newCryptoSuite(); + const client = new Client(); + const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); couchdbUtil.destroy(dbname, keyValStorePath) - .then(() => { - return utils.newKeyValueStore(keyStoreOpts); - }).then((store) => { - logger.debug('store: %s',store); - client.setStateStore(store); - return true; - }).then(() => { - return client.createUser( - {username: caImport.orgs[userOrg].username, - mspid: caImport.orgs[userOrg].mspid, - cryptoContent: { privateKey: prvKey, signedCert: sgnCert }, - keyStoreOpts: keyStoreOpts - }); - }).then((user) => { - if (user) { - t.pass(tag+': got user'); - t.end(); - } else { - t.fail(tag+'createUser returned null'); + .then(() => { + return utils.newKeyValueStore(keyStoreOpts); + }).then((store) => { + logger.debug('store: %s',store); + client.setStateStore(store); + return true; + }).then(() => { + return client.createUser( + {username: caImport.orgs[userOrg].username, + mspid: caImport.orgs[userOrg].mspid, + cryptoContent: { privateKey: prvKey, signedCert: sgnCert }, + keyStoreOpts: keyStoreOpts + }); + }).then((user) => { + if (user) { + t.pass(tag+': got user'); + t.end(); + } else { + t.fail(tag+'createUser returned null'); + t.end(); + } + }).catch((err) => { + t.fail(tag+'error, did not get user'); + t.comment(err.stack ? err.stack : err); t.end(); - } - }).catch((err) => { - t.fail(tag+'error, did not get user'); - t.comment(err.stack ? err.stack : err); - t.end(); - }); + }); }); -test('\n\n ** createUser happy path - Cloudant **\n\n', function (t) { +test('\n\n ** createUser happy path - Cloudant **\n\n', (t) => { // Use the Cloudant specific config file Client.addConfigFile('test/fixtures/cloudant.json'); utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js');//override - var cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); - var cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); - var cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); - var cloudantUrl = 'https://' + cloudantUsername + ':' + cloudantPassword + cloudantBluemix; + const cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); + const cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); + const cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); + const cloudantUrl = 'https://' + cloudantUsername + ':' + cloudantPassword + cloudantBluemix; // Clean up the cloudant test database - var userOrg = 'org1'; - var dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); - var keyStoreOpts = {name: dbname, url: cloudantUrl}; + const userOrg = 'org1'; + const dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); + const keyStoreOpts = {name: dbname, url: cloudantUrl}; logger.debug('cloudant keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); - var prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); - var sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); + const prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); + const sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); - var client = new Client(); - var cryptoSuite = Client.newCryptoSuite(); + const client = new Client(); + const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); couchdbUtil.destroy(dbname, cloudantUrl) - .then(() => { - return utils.newKeyValueStore(keyStoreOpts); - }).then((store) => { - logger.debug('store: %s',store); - client.setStateStore(store); - return true; - }).then(() => { - return client.createUser( - {username: caImport.orgs[userOrg].username, - mspid: caImport.orgs[userOrg].mspid, - cryptoContent: { privateKey: prvKey, signedCert: sgnCert } - }); - }).then((user) => { - if (user) { - t.pass(tag+': got user'); + .then(() => { + return utils.newKeyValueStore(keyStoreOpts); + }).then((store) => { + logger.debug('store: %s',store); + client.setStateStore(store); + return true; + }).then(() => { + return client.createUser( + {username: caImport.orgs[userOrg].username, + mspid: caImport.orgs[userOrg].mspid, + cryptoContent: { privateKey: prvKey, signedCert: sgnCert } + }); + }).then((user) => { + if (user) { + t.pass(tag+': got user'); + t.end(); + } else { + t.fail(tag+'createUser returned null'); + t.end(); + } + }).catch((err) => { + t.fail(tag+'error, did not get user'); + t.comment(err.stack ? err.stack : err); t.end(); - } else { - t.fail(tag+'createUser returned null'); - t.end(); - } - }).catch((err) => { - t.fail(tag+'error, did not get user'); - t.comment(err.stack ? err.stack : err); - t.end(); - }); + }); }); -test('\n\n ** createUser happy path - Cloudant - PEM Strings **\n\n', function (t) { +test('\n\n ** createUser happy path - Cloudant - PEM Strings **\n\n', (t) => { // Use the Cloudant specific config file Client.addConfigFile('test/fixtures/cloudant.json'); utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js');//override - var cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); - var cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); - var cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); - var cloudantUrl = 'https://' + cloudantUsername + ':' + cloudantPassword + cloudantBluemix; + const cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); + const cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); + const cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); + const cloudantUrl = 'https://' + cloudantUsername + ':' + cloudantPassword + cloudantBluemix; // Clean up the cloudant test database - var userOrg = 'org2'; - var dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); - var keyStoreOpts = {name: dbname, url: cloudantUrl}; + const userOrg = 'org2'; + const dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); + const keyStoreOpts = {name: dbname, url: cloudantUrl}; logger.debug('cloudant keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); - var client = new Client(); - var cryptoSuite = Client.newCryptoSuite(); + const client = new Client(); + const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); couchdbUtil.destroy(dbname, cloudantUrl) - .then(() => { - return utils.newKeyValueStore(keyStoreOpts); - }).then((store) => { - logger.debug('store: %s',store); - client.setStateStore(store); - return true; - }).then(() => { - return client.createUser( - {username: caImport.orgs[userOrg].username, - mspid: caImport.orgs[userOrg].mspid, - cryptoContent: caImport.orgs[userOrg].cryptoContent - }); - }, (err) => { - logger.error(err.stack ? err.stack : err); - throw new Error('Failed createUser.'); - }).then((user) => { - if (user) { - t.pass(tag+': got user'); - t.end(); - } else { - t.fail(tag+'createUser returned null'); + .then(() => { + return utils.newKeyValueStore(keyStoreOpts); + }).then((store) => { + logger.debug('store: %s',store); + client.setStateStore(store); + return true; + }).then(() => { + return client.createUser( + {username: caImport.orgs[userOrg].username, + mspid: caImport.orgs[userOrg].mspid, + cryptoContent: caImport.orgs[userOrg].cryptoContent + }); + }, (err) => { + logger.error(err.stack ? err.stack : err); + throw new Error('Failed createUser.'); + }).then((user) => { + if (user) { + t.pass(tag+': got user'); + t.end(); + } else { + t.fail(tag+'createUser returned null'); + t.end(); + } + }).catch((err) => { + t.fail(tag+'error, did not get user'); + t.comment(err.stack ? err.stack : err); t.end(); - } - }).catch((err) => { - t.fail(tag+'error, did not get user'); - t.comment(err.stack ? err.stack : err); - t.end(); - }); + }); }); diff --git a/test/integration/cloudant-fabricca-tests.js b/test/integration/cloudant-fabricca-tests.js index 4921ece010..e5336fe2db 100644 --- a/test/integration/cloudant-fabricca-tests.js +++ b/test/integration/cloudant-fabricca-tests.js @@ -4,27 +4,27 @@ * SPDX-License-Identifier: Apache-2.0 */ -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('cloudant-fabricca'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('cloudant-fabricca'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var Client = require('fabric-client'); -var User = require('fabric-client/lib/User.js'); -var FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); -var testUtil = require('../unit/util.js'); +const path = require('path'); +const Client = require('fabric-client'); +const User = require('fabric-client/lib/User.js'); +const FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); +const testUtil = require('../unit/util.js'); -var couchdbUtil = require('./couchdb-util.js'); +const couchdbUtil = require('./couchdb-util.js'); -var cloudantUrl = 'https://1421acc7-6faa-491a-8e10-951e2e190684-bluemix:7179ef7a72602189243deeabe207889bde1c2fada173ae1022b5592e5a79dacc@1421acc7-6faa-491a-8e10-951e2e190684-bluemix.cloudant.com'; +const cloudantUrl = 'https://1421acc7-6faa-491a-8e10-951e2e190684-bluemix:7179ef7a72602189243deeabe207889bde1c2fada173ae1022b5592e5a79dacc@1421acc7-6faa-491a-8e10-951e2e190684-bluemix.cloudant.com'; -var ORGS; -var userOrg = 'org1'; +let ORGS; +const userOrg = 'org1'; -var tlsOptions = { +const tlsOptions = { trustedRoots: [], verify: false }; @@ -34,14 +34,14 @@ var tlsOptions = { // FabricCAClientImpl to enroll a user, and saves the enrollment materials into the // CouchDB KeyValueStore. Then the test uses the Chain class to load the member // from the key value store. -test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { +test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', (t) => { testUtil.resetDefaults(); Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); - var fabricCAEndpoint = ORGS[userOrg].ca.url; + const fabricCAEndpoint = ORGS[userOrg].ca.url; Client.addConfigFile('test/fixtures/cloudant.json'); - var keyValueStore = Client.getConfigSetting('key-value-store'); + const keyValueStore = Client.getConfigSetting('key-value-store'); logger.debug('cloudant Key Value Store = ' + keyValueStore); // override t.end function so it'll always clear the config settings @@ -55,116 +55,116 @@ test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { })(t, t.end); //var user = new User(); - var client = new Client(); + const client = new Client(); // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js'); // Clean up the cloudant couchdb test database - var dbname = 'member_db'; + const dbname = 'member_db'; - var cryptoSuite, member, options; + let cryptoSuite, member, options; couchdbUtil.destroy(dbname, cloudantUrl) - .then( function() { - options = {name: dbname, url: cloudantUrl}; - utils.newKeyValueStore(options) - .then( - function(kvs) { - member = new User('admin2'); - cryptoSuite = Client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(options)); - client.setCryptoSuite(cryptoSuite); - member.setCryptoSuite(cryptoSuite); - - client.setStateStore(kvs); - if (client.getStateStore() === kvs) { - t.pass('Successfully set Cloudant CouchDB KeyValueStore for client'); - } else { - t.pass('Cloudant CouchDB KeyValStore is not set successfully on this client!'); - t.end(); - process.exit(1); - } - return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, cryptoSuite); - }, - function(err) { - t.fail('Error initializing Cloudant KeyValueStore. Exiting.'); - logger.error(err.stack ? err.stack : err); - t.end(); - process.exit(1); - }) - .then( - function(caService) { - logger.debug('ADD: caService - ' + caService); - t.pass('Successfully initialized the Fabric CA service.'); - - return caService.enroll({ - enrollmentID: 'admin', - enrollmentSecret: 'adminpw' - }); - }, - function(err) { - t.fail('Failed to initilize the Fabric CA service. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ) - .then( - function(admin2) { - t.pass('Successfully enrolled admin2 with CA server'); - - // Persist the user state - return member.setEnrollment(admin2.key, admin2.certificate, ORGS[userOrg].mspid); - }, - function(err) { - t.fail('Failed to use obtained private key and certificate to construct a User object. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ).then( - function() { - if (member.isEnrolled()) { - t.pass('Member isEnrolled successfully.'); - } else { - t.fail('Member isEnrolled failed.'); - } - return client.setUserContext(member); - }, - function(err) { - t.fail('Failed to enroll admin2 with CA server. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - }) - .then( - function() { - return client.setUserContext(new User('userx')); - }) - .then( - function() { - client.setCryptoSuite(cryptoSuite); - return client.getUserContext('admin2', true); - } - ).then( - function(user) { - if (user && user.getName() === 'admin2') { - t.pass('Successfully loaded the user from key value store'); - t.end(); - } else { - t.fail('Failed to load the user from key value store'); - t.end(); - } - }, - function(err) { - t.fail('Failed to load the user admin2 from key value store. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ).catch( - function(err) { - t.fail('Failed cloudant-fabricca-test with error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ); - }); + .then( () => { + options = {name: dbname, url: cloudantUrl}; + utils.newKeyValueStore(options) + .then( + (kvs) => { + member = new User('admin2'); + cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(options)); + client.setCryptoSuite(cryptoSuite); + member.setCryptoSuite(cryptoSuite); + + client.setStateStore(kvs); + if (client.getStateStore() === kvs) { + t.pass('Successfully set Cloudant CouchDB KeyValueStore for client'); + } else { + t.pass('Cloudant CouchDB KeyValStore is not set successfully on this client!'); + t.end(); + process.exit(1); + } + return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, cryptoSuite); + }, + (err) => { + t.fail('Error initializing Cloudant KeyValueStore. Exiting.'); + logger.error(err.stack ? err.stack : err); + t.end(); + process.exit(1); + }) + .then( + (caService) => { + logger.debug('ADD: caService - ' + caService); + t.pass('Successfully initialized the Fabric CA service.'); + + return caService.enroll({ + enrollmentID: 'admin', + enrollmentSecret: 'adminpw' + }); + }, + (err) => { + t.fail('Failed to initilize the Fabric CA service. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ) + .then( + (admin2) => { + t.pass('Successfully enrolled admin2 with CA server'); + + // Persist the user state + return member.setEnrollment(admin2.key, admin2.certificate, ORGS[userOrg].mspid); + }, + (err) => { + t.fail('Failed to use obtained private key and certificate to construct a User object. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ).then( + () => { + if (member.isEnrolled()) { + t.pass('Member isEnrolled successfully.'); + } else { + t.fail('Member isEnrolled failed.'); + } + return client.setUserContext(member); + }, + (err) => { + t.fail('Failed to enroll admin2 with CA server. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + }) + .then( + () => { + return client.setUserContext(new User('userx')); + }) + .then( + () => { + client.setCryptoSuite(cryptoSuite); + return client.getUserContext('admin2', true); + } + ).then( + (user) => { + if (user && user.getName() === 'admin2') { + t.pass('Successfully loaded the user from key value store'); + t.end(); + } else { + t.fail('Failed to load the user from key value store'); + t.end(); + } + }, + (err) => { + t.fail('Failed to load the user admin2 from key value store. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ).catch( + (err) => { + t.fail('Failed cloudant-fabricca-test with error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ); + }); }); diff --git a/test/integration/configtxlator.js b/test/integration/configtxlator.js index 8b4fe38f35..3d13a53f20 100644 --- a/test/integration/configtxlator.js +++ b/test/integration/configtxlator.js @@ -66,7 +66,7 @@ test('\n\n***** configtxlator flow for create and then update *****\n\n', async const tlsInfo = await e2eUtils.tlsEnroll(org); client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); t.pass('Successfully retrieved TLS certificate'); - let store = await Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(org)}); + const store = await Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(org)}); client.setStateStore(store); /* diff --git a/test/integration/couchdb-fabricca-tests.js b/test/integration/couchdb-fabricca-tests.js index b1fee39caa..a57ed2c59f 100644 --- a/test/integration/couchdb-fabricca-tests.js +++ b/test/integration/couchdb-fabricca-tests.js @@ -4,26 +4,26 @@ * SPDX-License-Identifier: Apache-2.0 */ -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('couchdb-fabricca'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('couchdb-fabricca'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var Client = require('fabric-client'); +const path = require('path'); +const Client = require('fabric-client'); -var User = require('fabric-client/lib/User.js'); -var FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); -var testUtil = require('../unit/util.js'); +const User = require('fabric-client/lib/User.js'); +const FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); +const testUtil = require('../unit/util.js'); -var couchdbUtil = require('./couchdb-util.js'); +const couchdbUtil = require('./couchdb-util.js'); -var ORGS; -var userOrg = 'org1'; +let ORGS; +const userOrg = 'org1'; -var tlsOptions = { +const tlsOptions = { trustedRoots: [], verify: false }; @@ -33,7 +33,7 @@ var tlsOptions = { // FabricCAClientImpl to enroll a user, and saves the enrollment materials into the // CouchDB KeyValueStore. Then the test uses the Client class to load the member // from the key value store. -test('Use FabricCAServices with a CouchDB KeyValueStore', function(t) { +test('Use FabricCAServices with a CouchDB KeyValueStore', (t) => { testUtil.resetDefaults(); Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); @@ -41,13 +41,13 @@ test('Use FabricCAServices with a CouchDB KeyValueStore', function(t) { // Use the CouchDB specific config file Client.addConfigFile('test/fixtures/couchdb.json'); - var fabricCAEndpoint = ORGS[userOrg].ca.url; - var keyValueStore = Client.getConfigSetting('key-value-store'); + const fabricCAEndpoint = ORGS[userOrg].ca.url; + const keyValueStore = Client.getConfigSetting('key-value-store'); logger.info('couchdb Key Value Store = ' + keyValueStore); - var couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); - var couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); - var keyValStorePath = couchdbIPAddr + ':' + couchdbPort; + const couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); + const couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); + const keyValStorePath = couchdbIPAddr + ':' + couchdbPort; logger.info('couch keyValStorePath: '+keyValStorePath); // override t.end function so it'll always clear the config settings @@ -60,118 +60,118 @@ test('Use FabricCAServices with a CouchDB KeyValueStore', function(t) { }; })(t, t.end); - var client = new Client(); + const client = new Client(); // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js'); // Clean up the couchdb test database - var dbname = 'my_member_db'; + const dbname = 'my_member_db'; - var cryptoSuite, member; + let cryptoSuite, member; couchdbUtil.destroy(dbname, keyValStorePath) - .then( function() { - var options = {name: dbname, url: keyValStorePath}; - utils.newKeyValueStore(options) - .then( - function(kvs) { - - member = new User('admin2'); - cryptoSuite = Client.newCryptoSuite(options); - cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(options)); - client.setCryptoSuite(cryptoSuite); - member.setCryptoSuite(cryptoSuite); - - client.setStateStore(kvs); - if (client.getStateStore() === kvs) { - t.pass('Successfully set CouchDB KeyValueStore for client'); - } else { - t.fail('CouchDB KeyValStore is not set successfully on this client!'); - t.end(); - process.exit(1); - } - return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, - cryptoSuite); - }, - function(err) { - t.fail('Error initializing CouchDB KeyValueStore. Exiting.'); - logger.error(err.stack ? err.stack : err); - t.end(); - process.exit(1); - }) - .then( - function(caService) { - logger.info('ADD: caService - ' + caService); - t.pass('Successfully initialized the Fabric CA service.'); - - return caService.enroll({ - enrollmentID: 'admin', - enrollmentSecret: 'adminpw' - }); - }, - function(err) { - t.fail('Failed to initialize the Fabric CA service. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ) - .then( - function(admin2) { - t.pass('Successfully enrolled admin2 with CA server'); - - // Persist the user state - return member.setEnrollment(admin2.key, admin2.certificate, ORGS[userOrg].mspid); - }, - function(err) { - t.fail('Failed to use obtained private key and certificate to construct a User object. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ).then( - function() { - if (member.isEnrolled()) { - t.pass('Member isEnrolled successfully.'); - } else { - t.fail('Member isEnrolled failed.'); - } - return client.setUserContext(member); - }, - function(err) { - t.fail('Failed to enroll admin2 with CA server. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - }) - .then( - function() { - return client.setUserContext(new User('userx')); - }) - .then( - function() { - client.setCryptoSuite(cryptoSuite); - return client.getUserContext('admin2', true); - }) - .then( - function(user) { - if (user && user.getName() === 'admin2') { - t.pass('Successfully loaded the user from key value store'); - t.end(); - } else { - t.fail('Failed to load the user from key value store'); - t.end(); - } - }, - function(err) { - t.fail('Failed to load the user admin2 from key value store. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ).catch( - function(err) { - t.fail('Failed couchdb-fabricca-test with error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ); - }); + .then( () => { + const options = {name: dbname, url: keyValStorePath}; + utils.newKeyValueStore(options) + .then( + (kvs) => { + + member = new User('admin2'); + cryptoSuite = Client.newCryptoSuite(options); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(options)); + client.setCryptoSuite(cryptoSuite); + member.setCryptoSuite(cryptoSuite); + + client.setStateStore(kvs); + if (client.getStateStore() === kvs) { + t.pass('Successfully set CouchDB KeyValueStore for client'); + } else { + t.fail('CouchDB KeyValStore is not set successfully on this client!'); + t.end(); + process.exit(1); + } + return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, + cryptoSuite); + }, + (err) => { + t.fail('Error initializing CouchDB KeyValueStore. Exiting.'); + logger.error(err.stack ? err.stack : err); + t.end(); + process.exit(1); + }) + .then( + (caService) => { + logger.info('ADD: caService - ' + caService); + t.pass('Successfully initialized the Fabric CA service.'); + + return caService.enroll({ + enrollmentID: 'admin', + enrollmentSecret: 'adminpw' + }); + }, + (err) => { + t.fail('Failed to initialize the Fabric CA service. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ) + .then( + (admin2) => { + t.pass('Successfully enrolled admin2 with CA server'); + + // Persist the user state + return member.setEnrollment(admin2.key, admin2.certificate, ORGS[userOrg].mspid); + }, + (err) => { + t.fail('Failed to use obtained private key and certificate to construct a User object. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ).then( + () => { + if (member.isEnrolled()) { + t.pass('Member isEnrolled successfully.'); + } else { + t.fail('Member isEnrolled failed.'); + } + return client.setUserContext(member); + }, + (err) => { + t.fail('Failed to enroll admin2 with CA server. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + }) + .then( + () => { + return client.setUserContext(new User('userx')); + }) + .then( + () => { + client.setCryptoSuite(cryptoSuite); + return client.getUserContext('admin2', true); + }) + .then( + (user) => { + if (user && user.getName() === 'admin2') { + t.pass('Successfully loaded the user from key value store'); + t.end(); + } else { + t.fail('Failed to load the user from key value store'); + t.end(); + } + }, + (err) => { + t.fail('Failed to load the user admin2 from key value store. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ).catch( + (err) => { + t.fail('Failed couchdb-fabricca-test with error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ); + }); }); diff --git a/test/integration/couchdb-util.js b/test/integration/couchdb-util.js index 143467c762..36faabd658 100644 --- a/test/integration/couchdb-util.js +++ b/test/integration/couchdb-util.js @@ -4,13 +4,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -var Client = require('fabric-client'); -var nano = require('nano'); -var Cloudant = require('@cloudant/cloudant'); +const Client = require('fabric-client'); +const nano = require('nano'); +const Cloudant = require('@cloudant/cloudant'); module.exports.getCloudantClient = function() { - var username = Client.getConfigSetting('cloudant-username', 'notfound'); - var password = Client.getConfigSetting('cloudant-password', 'notfound'); + const username = Client.getConfigSetting('cloudant-username', 'notfound'); + const password = Client.getConfigSetting('cloudant-password', 'notfound'); return Cloudant({account: username, password: password}); }; @@ -22,15 +22,15 @@ module.exports.destroy = function(name, url) { if (!name) { this._name = 'member_db'; } - var self = this; - return new Promise(function(resolve) { - var dbClient = nano(self._url); - dbClient.db.destroy(self._name, function(err) { + const self = this; + return new Promise(((resolve) => { + const dbClient = nano(self._url); + dbClient.db.destroy(self._name, (err) => { if (err) { resolve(false); } else { resolve(true); } }); - }); + })); }; diff --git a/test/integration/create-configtx-channel.js b/test/integration/create-configtx-channel.js index fcfa0bb8aa..df1e4436b1 100644 --- a/test/integration/create-configtx-channel.js +++ b/test/integration/create-configtx-channel.js @@ -5,161 +5,161 @@ */ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E create-channel'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E create-channel'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var Client = require('fabric-client'); -var fs = require('fs'); -var path = require('path'); +const Client = require('fabric-client'); +const fs = require('fs'); +const path = require('path'); -var testUtil = require('../unit/util.js'); -var e2eUtils = require('./e2e/e2eUtils.js'); +const testUtil = require('../unit/util.js'); +const e2eUtils = require('./e2e/e2eUtils.js'); -var ORGS; +let ORGS; // //Attempt to send a request to the orderer with the createChannel method // -test('\n\n***** Configtx Built config create flow *****\n\n', function(t) { +test('\n\n***** Configtx Built config create flow *****\n\n', (t) => { testUtil.resetDefaults(); Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); - var channel_name = 'mychanneltx'; + const channel_name = 'mychanneltx'; Client.setConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', channel_name); // // Create and configure the test channel // - var client = new Client(); + const client = new Client(); - var caRootsPath = ORGS.orderer.tls_cacerts; - let data = fs.readFileSync(path.join(__dirname, '/test', caRootsPath)); - let caroots = Buffer.from(data).toString(); + const caRootsPath = ORGS.orderer.tls_cacerts; + const data = fs.readFileSync(path.join(__dirname, '/test', caRootsPath)); + const caroots = Buffer.from(data).toString(); - var config = null; - var signatures = []; - var request = null; - var orderer = null; - var tlsInfo = null; + let config = null; + const signatures = []; + let request = null; + let orderer = null; + let tlsInfo = null; // Acting as a client in org1 when creating the channel - var org = ORGS.org1.name; + const org = ORGS.org1.name; utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); return e2eUtils.tlsEnroll('org1') - .then((enrollment) => { - t.pass('Successfully retrieved TLS certificate'); - tlsInfo = enrollment; - client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); - return Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(org)}); - }).then((store) => { - client.setStateStore(store); - - return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org1'); - }).then(() =>{ - t.pass('Successfully enrolled user \'admin\' for orderer (create-configtx-channel 1)'); - - orderer = client.newOrderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] + .then((enrollment) => { + t.pass('Successfully retrieved TLS certificate'); + tlsInfo = enrollment; + client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); + return Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(org)}); + }).then((store) => { + client.setStateStore(store); + + return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org1'); + }).then(() =>{ + t.pass('Successfully enrolled user \'admin\' for orderer (create-configtx-channel 1)'); + + orderer = client.newOrderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ); + + logger.info('\n\n***** Get the configtx config update configuration *****\n\n'); + // use the config update created by the configtx tool + const envelope_bytes = fs.readFileSync(path.join(__dirname, '../fixtures/channel/' + channel_name + '.tx')); + config = client.extractChannelConfig(envelope_bytes); + t.pass('Successfull extracted the config update from the configtx envelope'); + + // sign the config + const signature = client.signChannelConfig(config); + t.pass('Successfully signed config update'); + // collect signature from org1 admin + signatures.push(signature); + + // make sure we do not reuse the user + client._userContext = null; + return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org2'); + }).then(() => { + t.pass('Successfully enrolled user \'admin\' for org2'); + + // sign the config + const signature = client.signChannelConfig(config); + t.pass('Successfully signed config update'); + + // collect signature from org2 admin + signatures.push(signature); + + // make sure we do not reuse the user + client._userContext = null; + return testUtil.getOrderAdminSubmitter(client, t); + }).then(() => { + t.pass('Successfully enrolled user \'admin\' for orderer (create-configtx-channel 2)'); + + // sign the config + const signature = client.signChannelConfig(config); + t.pass('Successfully signed config update'); + + // collect signature from orderer org admin + signatures.push(signature); + + logger.debug('\n***\n done signing \n***\n'); + + // build up the create request + const tx_id = client.newTransactionID(); + request = { + config: config, + signatures : signatures, + name : channel_name, + orderer : orderer, + txId : tx_id + }; + + // send to create request to orderer + return client.createChannel(request); + }) + .then((result) => { + logger.debug('\n***\n completed the create \n***\n'); + + logger.debug(' response ::%j',result); + t.pass('Successfully created the channel.'); + if(result.status && result.status === 'SUCCESS') { + return e2eUtils.sleep(5000); + } else { + t.fail('Failed to create the channel. '); + t.end(); } - ); - - logger.info('\n\n***** Get the configtx config update configuration *****\n\n'); - // use the config update created by the configtx tool - let envelope_bytes = fs.readFileSync(path.join(__dirname, '../fixtures/channel/' + channel_name + '.tx')); - config = client.extractChannelConfig(envelope_bytes); - t.pass('Successfull extracted the config update from the configtx envelope'); - - // sign the config - var signature = client.signChannelConfig(config); - t.pass('Successfully signed config update'); - // collect signature from org1 admin - signatures.push(signature); - - // make sure we do not reuse the user - client._userContext = null; - return testUtil.getSubmitter(client, t, true /*get the org admin*/, 'org2'); - }).then(() => { - t.pass('Successfully enrolled user \'admin\' for org2'); - - // sign the config - var signature = client.signChannelConfig(config); - t.pass('Successfully signed config update'); - - // collect signature from org2 admin - signatures.push(signature); - - // make sure we do not reuse the user - client._userContext = null; - return testUtil.getOrderAdminSubmitter(client, t); - }).then(() => { - t.pass('Successfully enrolled user \'admin\' for orderer (create-configtx-channel 2)'); - - // sign the config - var signature = client.signChannelConfig(config); - t.pass('Successfully signed config update'); - - // collect signature from orderer org admin - signatures.push(signature); - - logger.debug('\n***\n done signing \n***\n'); - - // build up the create request - let tx_id = client.newTransactionID(); - request = { - config: config, - signatures : signatures, - name : channel_name, - orderer : orderer, - txId : tx_id - }; - - // send to create request to orderer - return client.createChannel(request); - }) - .then((result) => { - logger.debug('\n***\n completed the create \n***\n'); - - logger.debug(' response ::%j',result); - t.pass('Successfully created the channel.'); - if(result.status && result.status === 'SUCCESS') { - return e2eUtils.sleep(5000); - } else { - t.fail('Failed to create the channel. '); + }, (err) => { + t.fail('Failed to create the channel: ' + err.stack ? err.stack : err); t.end(); - } - }, (err) => { - t.fail('Failed to create the channel: ' + err.stack ? err.stack : err); - t.end(); - }) - .then(() => { - t.pass('Successfully waited to make sure new channel was created.'); - - logger.info('\n\n >>>>>> Should fail to create the existing channel again with name :: %s <<<<<<< \n\n',channel_name); - return client.createChannel(request); - }, (err) => { - t.fail('Failed to sleep due to error: ' + err.stack ? err.stack : err); - t.end(); - }) - .then((result) => { - logger.debug(' response ::%j',result); - if(result && result.status && result.status.toString().indexOf('BAD_REQUEST') >= 0) { - t.pass('Successfully received the error message due to the conflict of channel: ' + result.info); - } else { - t.fail('Failed to get error. response: ' + result.status); - } - t.end(); - }, (err) => { - t.fail('Got unexpected error: ' + err.stack ? err.stack : err); - t.end(); - }); + }) + .then(() => { + t.pass('Successfully waited to make sure new channel was created.'); + + logger.info('\n\n >>>>>> Should fail to create the existing channel again with name :: %s <<<<<<< \n\n',channel_name); + return client.createChannel(request); + }, (err) => { + t.fail('Failed to sleep due to error: ' + err.stack ? err.stack : err); + t.end(); + }) + .then((result) => { + logger.debug(' response ::%j',result); + if(result && result.status && result.status.toString().indexOf('BAD_REQUEST') >= 0) { + t.pass('Successfully received the error message due to the conflict of channel: ' + result.info); + } else { + t.fail('Failed to get error. response: ' + result.status); + } + t.end(); + }, (err) => { + t.fail('Got unexpected error: ' + err.stack ? err.stack : err); + t.end(); + }); }); diff --git a/test/integration/e2e/install-chaincode-fail.js b/test/integration/e2e/install-chaincode-fail.js index 39a0e93257..3f619a0327 100644 --- a/test/integration/e2e/install-chaincode-fail.js +++ b/test/integration/e2e/install-chaincode-fail.js @@ -8,36 +8,36 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E install-chaincode-fail'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E install-chaincode-fail'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('./e2eUtils.js'); -var testUtil = require('../../unit/util.js'); +const e2eUtils = require('./e2eUtils.js'); +const testUtil = require('../../unit/util.js'); test('\n\n***** End-to-end flow: chaincode install *****\n\n', (t) => { testUtil.setupChaincodeDeploy(); e2eUtils.installChaincode('org1', testUtil.CHAINCODE_PATH, null, 'v0', 'golang', t, false) - .then(() => { - t.fail('Successfully installed chaincode in peers of organization "org1"'); - return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, null, 'v0', 'golang', t, false); - }, (err) => { - t.pass('Failed to install chaincode in peers of organization "org1". ' + err.stack ? err.stack : err); - logger.error('Failed to install chaincode in peers of organization "org1". '); - return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, null, 'v0', 'golang', t, false); - }).then(() => { - t.fail('Successfully installed chaincode in peers of organization "org2"'); - t.end(); - }, (err) => { - t.pass('Failed to install chaincode in peers of organization "org2". ' + err.stack ? err.stack : err); - logger.error('Failed to install chaincode in peers of organization "org2". '); - t.end(); - }).catch((err) => { - t.fail('Test failed due to unexpected reasons. ' + err.stack ? err.stack : err); - t.end(); - }); + .then(() => { + t.fail('Successfully installed chaincode in peers of organization "org1"'); + return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, null, 'v0', 'golang', t, false); + }, (err) => { + t.pass('Failed to install chaincode in peers of organization "org1". ' + err.stack ? err.stack : err); + logger.error('Failed to install chaincode in peers of organization "org1". '); + return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, null, 'v0', 'golang', t, false); + }).then(() => { + t.fail('Successfully installed chaincode in peers of organization "org2"'); + t.end(); + }, (err) => { + t.pass('Failed to install chaincode in peers of organization "org2". ' + err.stack ? err.stack : err); + logger.error('Failed to install chaincode in peers of organization "org2". '); + t.end(); + }).catch((err) => { + t.fail('Test failed due to unexpected reasons. ' + err.stack ? err.stack : err); + t.end(); + }); }); diff --git a/test/integration/e2e/install-chaincode.js b/test/integration/e2e/install-chaincode.js index f9407712fc..cc73435230 100644 --- a/test/integration/e2e/install-chaincode.js +++ b/test/integration/e2e/install-chaincode.js @@ -8,38 +8,38 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E install-chaincode'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E install-chaincode'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('./e2eUtils.js'); -var testUtil = require('../../unit/util.js'); +const e2eUtils = require('./e2eUtils.js'); +const testUtil = require('../../unit/util.js'); -var version = 'v0'; +const version = 'v0'; test('\n\n***** End-to-end flow: chaincode install *****\n\n', (t) => { testUtil.setupChaincodeDeploy(); e2eUtils.installChaincode('org1', testUtil.CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'golang', t, true) - .then(() => { - t.pass('Successfully installed chaincode in peers of organization "org1"'); - return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'golang', t, true); - }, (err) => { - t.fail('Failed to install chaincode in peers of organization "org1". ' + err.stack ? err.stack : err); - logger.error('Failed to install chaincode in peers of organization "org1". '); - return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'golang', t, true); - }).then(() => { - t.pass('Successfully installed chaincode in peers of organization "org2"'); - t.end(); - }, (err) => { - t.fail('Failed to install chaincode in peers of organization "org2". ' + err.stack ? err.stack : err); - logger.error('Failed to install chaincode in peers of organization "org2". '); - t.end(); - }).catch((err) => { - t.fail('Test failed due to unexpected reasons. ' + err.stack ? err.stack : err); - t.end(); - }); + .then(() => { + t.pass('Successfully installed chaincode in peers of organization "org1"'); + return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'golang', t, true); + }, (err) => { + t.fail('Failed to install chaincode in peers of organization "org1". ' + err.stack ? err.stack : err); + logger.error('Failed to install chaincode in peers of organization "org1". '); + return e2eUtils.installChaincode('org2', testUtil.CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'golang', t, true); + }).then(() => { + t.pass('Successfully installed chaincode in peers of organization "org2"'); + t.end(); + }, (err) => { + t.fail('Failed to install chaincode in peers of organization "org2". ' + err.stack ? err.stack : err); + logger.error('Failed to install chaincode in peers of organization "org2". '); + t.end(); + }).catch((err) => { + t.fail('Test failed due to unexpected reasons. ' + err.stack ? err.stack : err); + t.end(); + }); }); diff --git a/test/integration/e2e/invoke-transaction.js b/test/integration/e2e/invoke-transaction.js index 5f26b029ba..d88e5cea90 100755 --- a/test/integration/e2e/invoke-transaction.js +++ b/test/integration/e2e/invoke-transaction.js @@ -20,7 +20,7 @@ test('\n\n***** End-to-end flow: invoke transaction to move money *****\n\n', as const args = ['a', 'b','100']; let expectedResult = 'move succeed'; try { - let result = await e2eUtils.invokeChaincode('org2', 'v0', chaincodeId, t, false/*useStore*/, fcn, args, expectedResult); + const result = await e2eUtils.invokeChaincode('org2', 'v0', chaincodeId, t, false/*useStore*/, fcn, args, expectedResult); if(result){ t.pass('Successfully invoke transaction chaincode on channel'); await testUtils.sleep(5000); diff --git a/test/integration/e2e/join-channel.js b/test/integration/e2e/join-channel.js index c86542e6dd..4b14968555 100644 --- a/test/integration/e2e/join-channel.js +++ b/test/integration/e2e/join-channel.js @@ -5,30 +5,30 @@ */ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E join-channel'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E join-channel'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var util = require('util'); -var path = require('path'); -var fs = require('fs'); +const util = require('util'); +const path = require('path'); +const fs = require('fs'); -var Client = require('fabric-client'); +const Client = require('fabric-client'); -var testUtil = require('../../unit/util.js'); -var e2eUtils = require('./e2eUtils.js'); +const testUtil = require('../../unit/util.js'); +const e2eUtils = require('./e2eUtils.js'); -var tx_id = null; +let tx_id = null; -var ORGS; +let ORGS; // //Attempt to send a request to the orderer with the createChannel method // -test('\n\n***** End-to-end flow: join channel *****\n\n', function(t) { +test('\n\n***** End-to-end flow: join channel *****\n\n', (t) => { Client.addConfigFile(path.join(__dirname, './config.json')); ORGS = Client.getConfigSetting('test-network'); @@ -47,29 +47,29 @@ test('\n\n***** End-to-end flow: join channel *****\n\n', function(t) { t.fail(util.format('Failed to join peers in organization "%s" to the channel. %s', ORGS['org2'].name), err.stack ? err.stack : err); t.end(); }) - .catch(function(err) { + .catch((err) => { t.fail('Failed request. ' + err); t.end(); }); }); function joinChannel(org, t) { - var channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); + const channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); // // Create and configure the test channel // - var client = new Client(); - var channel = client.newChannel(channel_name); + const client = new Client(); + const channel = client.newChannel(channel_name); - var orgName = ORGS[org].name; + const orgName = ORGS[org].name; - var targets = []; + const targets = []; - var caRootsPath = ORGS.orderer.tls_cacerts; + const caRootsPath = ORGS.orderer.tls_cacerts; let data = fs.readFileSync(path.join(__dirname, caRootsPath)); - let caroots = Buffer.from(data).toString(); - var genesis_block = null; - var tlsInfo = null; + const caroots = Buffer.from(data).toString(); + let genesis_block = null; + let tlsInfo = null; return e2eUtils.tlsEnroll(org) .then((enrollment) => { @@ -94,7 +94,7 @@ function joinChannel(org, t) { ) ); tx_id = client.newTransactionID(); - let request = { + const request = { txId : tx_id }; @@ -110,7 +110,7 @@ function joinChannel(org, t) { }).then(() => { t.pass('Successfully enrolled org (join_channel):' + org + ' \'admin\''); - for (let key in ORGS[org]) { + for (const key in ORGS[org]) { if (ORGS[org].hasOwnProperty(key)) { if (key.indexOf('peer') === 0) { data = fs.readFileSync(path.join(__dirname, ORGS[org][key]['tls_cacerts'])); @@ -128,7 +128,7 @@ function joinChannel(org, t) { } tx_id = client.newTransactionID(); - let request = { + const request = { targets : targets, block : genesis_block, txId : tx_id diff --git a/test/integration/e2e/query.js b/test/integration/e2e/query.js index 99f19176e2..8b196f04e5 100644 --- a/test/integration/e2e/query.js +++ b/test/integration/e2e/query.js @@ -21,7 +21,7 @@ test('\n\n***** End-to-end flow: query chaincode *****\n\n', async (t) => { let expectedResult = '300'; const targets = []; // empty array, meaning client will discover the peers try { - let result = await e2eUtils.queryChaincode('org2', 'v0', targets, fcn, args, expectedResult, chaincodeId, t); + const result = await e2eUtils.queryChaincode('org2', 'v0', targets, fcn, args, expectedResult, chaincodeId, t); if(result){ t.pass('Successfully query chaincode on the channel'); } @@ -34,7 +34,7 @@ test('\n\n***** End-to-end flow: query chaincode *****\n\n', async (t) => { try { expectedResult = new Error('throwError: an error occurred'); - let result = await e2eUtils.queryChaincode('org2', 'v0', targets, 'throwError', args, expectedResult, chaincodeId, t); + const result = await e2eUtils.queryChaincode('org2', 'v0', targets, 'throwError', args, expectedResult, chaincodeId, t); if(result){ t.pass('Successfully handled error from query'); } diff --git a/test/integration/e2e/upgrade.js b/test/integration/e2e/upgrade.js index a51ed9171b..7013acc01b 100644 --- a/test/integration/e2e/upgrade.js +++ b/test/integration/e2e/upgrade.js @@ -8,12 +8,12 @@ // in a happy-path scenario 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var e2eUtils = require('./e2eUtils.js'); -var testUtil = require('../../unit/util.js'); -var chaincodeId = testUtil.END2END.chaincodeId; +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const e2eUtils = require('./e2eUtils.js'); +const testUtil = require('../../unit/util.js'); +const chaincodeId = testUtil.END2END.chaincodeId; test('\n\n***** U P G R A D E flow: chaincode install *****\n\n', (t) => { testUtil.setupChaincodeDeploy(); diff --git a/test/integration/fabric-ca-affiliation-service-tests.js b/test/integration/fabric-ca-affiliation-service-tests.js index 00373a1ba5..a13ff8cc7e 100644 --- a/test/integration/fabric-ca-affiliation-service-tests.js +++ b/test/integration/fabric-ca-affiliation-service-tests.js @@ -4,15 +4,15 @@ * SPDX-License-Identifier: Apache-2.0 */ -let tape = require('tape'); -let _test = require('tape-promise').default; -let test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); const path = require('path'); -let FabricCAServices = require('../../fabric-ca-client'); +const FabricCAServices = require('../../fabric-ca-client'); const User = require('../../fabric-ca-client/lib/User'); -let userOrg = 'org1'; -let tlsOptions = { +const userOrg = 'org1'; +const tlsOptions = { trustedRoots: [], verify: false }; @@ -26,7 +26,7 @@ function checkResponse(response, name, t) { } function checkExist(response, affiliation, t) { - let res = response.affiliations.find((path) => { + const res = response.affiliations.find((path) => { if (path.name === affiliation) { return true; } @@ -41,7 +41,7 @@ function checkExist(response, affiliation, t) { } function checkNotExist(response, affiliation, t) { - let res = response.affiliations.find((path) => { + const res = response.affiliations.find((path) => { if (path.name === affiliation) { return true; } @@ -60,7 +60,7 @@ test('\n\n ** HFCAIdentityService Test **\n\n', (t) => { FabricCAServices.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = FabricCAServices.getConfigSetting('test-network'); - let fabricCAEndpoint = ORGS[userOrg].ca.url; + const fabricCAEndpoint = ORGS[userOrg].ca.url; FabricCAServices.getConfigSetting('crypto-keysize', '256'); //force for gulp test FabricCAServices.setConfigSetting('crypto-hash-algo', 'SHA2'); //force for gulp test @@ -143,7 +143,7 @@ test('\n\n ** HFCAIdentityService Test **\n\n', (t) => { return affiliationService.getAll(admin); }).then((resp) => { t.equal(resp.success, true, 'resp should have property \'success\' equals true'); - let org2 = resp.result.affiliations.find((affiliation) => affiliation.name === 'org2'); + const org2 = resp.result.affiliations.find((affiliation) => affiliation.name === 'org2'); checkExist(org2, updatedAffiliation.name, t); checkNotExist(org2, newAffiliationRequest.name, t); t.pass(`After update, ${newAffiliationRequest.name} does not exist, and ${updatedAffiliation.name} exists`); diff --git a/test/integration/fabric-ca-certificate-service-tests.js b/test/integration/fabric-ca-certificate-service-tests.js index b19b2ef255..c00a79d1ba 100644 --- a/test/integration/fabric-ca-certificate-service-tests.js +++ b/test/integration/fabric-ca-certificate-service-tests.js @@ -41,7 +41,7 @@ test('\n\n ** FabricCAServices - CertificateService Test **\n\n', async (t) => { let resp = await certificateService1.getCertificates(null, admin1); t.equal(resp.success, true, 'certificate service should response success'); t.equal(resp.result.certs.length > 0, true, 'there should be certificates for the admin user'); - let certsNum1 = resp.result.certs.length; + const certsNum1 = resp.result.certs.length; resp = await certificateService2.getCertificates(null, admin2); t.equal(resp.success, true, 'certificate service should response success'); @@ -49,7 +49,7 @@ test('\n\n ** FabricCAServices - CertificateService Test **\n\n', async (t) => { // admin1 create a new identity at ca-org1 // after enroll the new created identity, there should be a new certificate - let user1 = await createAndEnrollIdentity(caService1, admin1); + const user1 = await createAndEnrollIdentity(caService1, admin1); resp = await certificateService1.getCertificates(null, admin1); t.equal(resp.success, true, 'certificate service should response success'); t.equal(resp.result.certs.length, certsNum1 + 1, 'there should be a new certificate after a new identity was created'); diff --git a/test/integration/fabric-ca-identity-service-tests.js b/test/integration/fabric-ca-identity-service-tests.js index a2a7460314..522f5780ea 100644 --- a/test/integration/fabric-ca-identity-service-tests.js +++ b/test/integration/fabric-ca-identity-service-tests.js @@ -4,18 +4,18 @@ * SPDX-License-Identifier: Apache-2.0 */ -let tape = require('tape'); -let _test = require('tape-promise').default; -let test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); const path = require('path'); -let FabricCAServices = require('../../fabric-ca-client'); +const FabricCAServices = require('../../fabric-ca-client'); const { HFCAIdentityAttributes, HFCAIdentityType } = require('../../fabric-ca-client/lib/IdentityService'); const User = require('../../fabric-ca-client/lib/User'); -let userOrg1 = 'org1'; -let userOrg2 = 'org2'; -let tlsOptions = { +const userOrg1 = 'org1'; +const userOrg2 = 'org2'; +const tlsOptions = { trustedRoots: [], verify: false }; @@ -33,17 +33,17 @@ test('\n\n ** FabricCAServices - IdentityService Test **\n\n', async (t) => { FabricCAServices.getConfigSetting('crypto-keysize', '256'); //force for gulp test FabricCAServices.setConfigSetting('crypto-hash-algo', 'SHA2'); //force for gulp test - let caService1 = new FabricCAServices(fabricCAEndpoint1, tlsOptions, ORGS[userOrg1].ca.name); - let caService2 = new FabricCAServices(fabricCAEndpoint2, tlsOptions, ORGS[userOrg2].ca.name); + const caService1 = new FabricCAServices(fabricCAEndpoint1, tlsOptions, ORGS[userOrg1].ca.name); + const caService2 = new FabricCAServices(fabricCAEndpoint2, tlsOptions, ORGS[userOrg2].ca.name); - let bootstrapUser = { + const bootstrapUser = { enrollmentID: 'admin', enrollmentSecret: 'adminpw' }; let admin1; let admin2; - let testIdentity = { + const testIdentity = { enrollmentID: 'user_' + Math.random().toFixed(3).toString(), enrollmentSecret: 'userpw', affiliation: 'org1', @@ -52,7 +52,7 @@ test('\n\n ** FabricCAServices - IdentityService Test **\n\n', async (t) => { }; // update the enrollment secret for testIdentity - let update = { + const update = { enrollmentSecret: 'mysecret' }; let hfcaIdentityService1; diff --git a/test/integration/fileKeyValueStore-fabricca-tests.js b/test/integration/fileKeyValueStore-fabricca-tests.js index 1687d04cd0..aa6c1ac34f 100644 --- a/test/integration/fileKeyValueStore-fabricca-tests.js +++ b/test/integration/fileKeyValueStore-fabricca-tests.js @@ -4,24 +4,24 @@ * SPDX-License-Identifier: Apache-2.0 */ -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('fileKeyValStore-fabricca'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('fileKeyValStore-fabricca'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var testUtil = require('../unit/util.js'); -var fs = require('fs-extra'); +const testUtil = require('../unit/util.js'); +const fs = require('fs-extra'); -var path = require('path'); -var Client = require('fabric-client'); +const path = require('path'); +const Client = require('fabric-client'); -var User = require('fabric-client/lib/User.js'); -var FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); +const User = require('fabric-client/lib/User.js'); +const FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); -var userOrg = 'org1'; -var ORGS; +const userOrg = 'org1'; +let ORGS; // This test first checks to see if a user has already been enrolled. If so, @@ -29,128 +29,128 @@ var ORGS; // FabricCAClientImpl to enroll a user, and saves the enrollment materials into the // File KeyValueStore. Then the test uses the Client class to load the member // from the key value store. -test('Use FabricCAServices with a File KeyValueStore', function(t) { +test('Use FabricCAServices with a File KeyValueStore', (t) => { testUtil.resetDefaults(); Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); - var fabricCAEndpoint = ORGS[userOrg].ca.url; + const fabricCAEndpoint = ORGS[userOrg].ca.url; // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/FileKeyValueStore.js'); //var keyValueStore = Client.getConfigSetting('key-value-store'); - var keyValStorePath = path.join(testUtil.getTempDir(), 'customKeyValStorePath'); + const keyValStorePath = path.join(testUtil.getTempDir(), 'customKeyValStorePath'); - var client = new Client(); - var cryptoSuite, member; + const client = new Client(); + let cryptoSuite, member; // clean up if (testUtil.existsSync(keyValStorePath)) { fs.removeSync(keyValStorePath); } - var tlsOptions = { + const tlsOptions = { trustedRoots: [], verify: false }; utils.newKeyValueStore({path: keyValStorePath}) - .then( - function(kvs) { - - member = new User('admin2'); - cryptoSuite = Client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: keyValStorePath})); - member.setCryptoSuite(cryptoSuite); - - client.setStateStore(kvs); - if (client.getStateStore() === kvs) { - t.pass('Successfully set File KeyValueStore for client'); - } else { - t.fail('File KeyValStore is not set successfully on this client!'); + .then( + (kvs) => { + + member = new User('admin2'); + cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: keyValStorePath})); + member.setCryptoSuite(cryptoSuite); + + client.setStateStore(kvs); + if (client.getStateStore() === kvs) { + t.pass('Successfully set File KeyValueStore for client'); + } else { + t.fail('File KeyValStore is not set successfully on this client!'); + t.end(); + process.exit(1); + } + return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, + cryptoSuite); + }, + (err) => { + t.fail('Error initializing File KeyValueStore. Exiting.'); + logger.error(err.stack ? err.stack : err); t.end(); process.exit(1); + }) + .then( + (caService) => { + t.pass('Successfully initialized the Fabric CA service.'); + + return caService.enroll({ + enrollmentID: 'admin', + enrollmentSecret: 'adminpw' + }); + }, + (err) => { + t.fail('Failed to initialize the Fabric CA service. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); } - return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, - cryptoSuite); - }, - function(err) { - t.fail('Error initializing File KeyValueStore. Exiting.'); - logger.error(err.stack ? err.stack : err); - t.end(); - process.exit(1); - }) - .then( - function(caService) { - t.pass('Successfully initialized the Fabric CA service.'); - - return caService.enroll({ - enrollmentID: 'admin', - enrollmentSecret: 'adminpw' - }); - }, - function(err) { - t.fail('Failed to initialize the Fabric CA service. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ) - .then( - function(admin2) { - t.pass('Successfully enrolled admin2 with CA server'); - - // Persist the user state - return member.setEnrollment(admin2.key, admin2.certificate, ORGS[userOrg].mspid); - }, - function(err) { - t.fail('Failed to use obtained private key and certificate to construct a User object. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ).then( - function() { - if (member.isEnrolled()) { - t.pass('Member isEnrolled successfully.'); - } else { - t.fail('Member isEnrolled failed.'); + ) + .then( + (admin2) => { + t.pass('Successfully enrolled admin2 with CA server'); + + // Persist the user state + return member.setEnrollment(admin2.key, admin2.certificate, ORGS[userOrg].mspid); + }, + (err) => { + t.fail('Failed to use obtained private key and certificate to construct a User object. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); } - return client.setUserContext(member); - }, - function(err) { - t.fail('Failed to enroll admin2 with CA server. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - }) - .then( - function() { - return client.setUserContext(new User('userx')); - }) - .then( - function() { - client.setCryptoSuite(cryptoSuite); - return client.getUserContext('admin2', true); - }) - .then( - function(user) { - if (user && user.getName() === 'admin2') { - t.pass('Successfully loaded the user from key value store'); + ).then( + () => { + if (member.isEnrolled()) { + t.pass('Member isEnrolled successfully.'); + } else { + t.fail('Member isEnrolled failed.'); + } + return client.setUserContext(member); + }, + (err) => { + t.fail('Failed to enroll admin2 with CA server. Error:'); + logger.error(err.stack ? err.stack : err); t.end(); - } else { - t.fail('Failed to load the user from key value store'); + }) + .then( + () => { + return client.setUserContext(new User('userx')); + }) + .then( + () => { + client.setCryptoSuite(cryptoSuite); + return client.getUserContext('admin2', true); + }) + .then( + (user) => { + if (user && user.getName() === 'admin2') { + t.pass('Successfully loaded the user from key value store'); + t.end(); + } else { + t.fail('Failed to load the user from key value store'); + t.end(); + } + }, + (err) => { + t.fail('Failed to load the user admin2 from key value store. Error:'); + logger.error(err.stack ? err.stack : err); + t.end(); + } + ).catch( + (err) => { + t.fail('Failed fileKeyValueStore-fabricca-test with error:'); + logger.error(err.stack ? err.stack : err); t.end(); } - }, - function(err) { - t.fail('Failed to load the user admin2 from key value store. Error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ).catch( - function(err) { - t.fail('Failed fileKeyValueStore-fabricca-test with error:'); - logger.error(err.stack ? err.stack : err); - t.end(); - } - ); + ); }); diff --git a/test/integration/get-config.js b/test/integration/get-config.js index b6ea3e79ed..310c9a7d3c 100644 --- a/test/integration/get-config.js +++ b/test/integration/get-config.js @@ -8,29 +8,29 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('get-config'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('get-config'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var fs = require('fs'); -var e2eUtils = require('./e2e/e2eUtils.js'); +const path = require('path'); +const fs = require('fs'); +const e2eUtils = require('./e2e/e2eUtils.js'); -var Client = require('fabric-client'); -var testUtil = require('../unit/util.js'); -var Peer = require('fabric-client/lib/Peer.js'); -var Orderer = require('fabric-client/lib/Orderer.js'); +const Client = require('fabric-client'); +const testUtil = require('../unit/util.js'); +const Peer = require('fabric-client/lib/Peer.js'); +const Orderer = require('fabric-client/lib/Orderer.js'); -var client = new Client(); +const client = new Client(); // IMPORTANT ------>>>>> MUST RUN e2e/create-channel.js FIRST -var channel = client.newChannel(testUtil.END2END.channel); -var ORGS; +const channel = client.newChannel(testUtil.END2END.channel); +let ORGS; -var querys = []; +const querys = []; if (process.argv.length > 2) { for (let i=2; i 2) { } logger.info('Found query: %s', querys); -test(' ---->>>>> get config <<<<<-----', function(t) { +test(' ---->>>>> get config <<<<<-----', (t) => { testUtil.resetDefaults(); testUtil.setupChaincodeDeploy(); Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); - var org = 'org1'; - var orgName = ORGS[org].name; - var caRootsPath = ORGS.orderer.tls_cacerts; - let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); - let caroots = Buffer.from(data).toString(); - var tlsInfo = null; + const org = 'org1'; + const orgName = ORGS[org].name; + const caRootsPath = ORGS.orderer.tls_cacerts; + const data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + const caroots = Buffer.from(data).toString(); + let tlsInfo = null; e2eUtils.tlsEnroll(org) - .then((enrollment) => { - t.pass('Successfully retrieved TLS certificate'); - tlsInfo = enrollment; - client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); - return Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(orgName)}); - }).then( function (store) { - client.setStateStore(store); - var cryptoSuite = Client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); - client.setCryptoSuite(cryptoSuite); + .then((enrollment) => { + t.pass('Successfully retrieved TLS certificate'); + tlsInfo = enrollment; + client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); + return Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(orgName)}); + }).then( (store) => { + client.setStateStore(store); + const cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + client.setCryptoSuite(cryptoSuite); - testUtil.getSubmitter(client, t, org) - .then( - function() { - t.pass('Successfully enrolled user'); + testUtil.getSubmitter(client, t, org) + .then( + () => { + t.pass('Successfully enrolled user'); - channel.addOrderer( - new Orderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'clientCert': tlsInfo.certificate, - 'clientKey': tlsInfo.key, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) - ); + channel.addOrderer( + new Orderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'clientCert': tlsInfo.certificate, + 'clientKey': tlsInfo.key, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); - for (let key in ORGS[org]) { - if (ORGS[org].hasOwnProperty(key)) { - if (key.indexOf('peer') === 0) { - let data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); - let peer = new Peer( - ORGS[org][key].requests, - { - pem: Buffer.from(data).toString(), - 'clientCert': tlsInfo.certificate, - 'clientKey': tlsInfo.key, - 'ssl-target-name-override': ORGS[org][key]['server-hostname'] - }); - channel.addPeer(peer); + for (const key in ORGS[org]) { + if (ORGS[org].hasOwnProperty(key)) { + if (key.indexOf('peer') === 0) { + const data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); + const peer = new Peer( + ORGS[org][key].requests, + { + pem: Buffer.from(data).toString(), + 'clientCert': tlsInfo.certificate, + 'clientKey': tlsInfo.key, + 'ssl-target-name-override': ORGS[org][key]['server-hostname'] + }); + channel.addPeer(peer); + } } } - } - // use default primary peer - // send query - logger.debug('will initialize the channel'); - return channel.initialize(); - }, - function(err) { - t.fail('Failed to enroll user: ' + err.stack ? err.stack : err); - t.end(); - } - ).then( - function() { - t.pass('channel was successfully initialized'); - let orgs = channel.getOrganizations(); - logger.debug(' Got the following orgs back %j', orgs); - t.equals(orgs.length, 2, 'Checking the that we got back the right number of orgs'); - if(orgs[0].id.indexOf('Or') == 0) { - t.pass('Found the org name '+ orgs[0].id); + // use default primary peer + // send query + logger.debug('will initialize the channel'); + return channel.initialize(); + }, + (err) => { + t.fail('Failed to enroll user: ' + err.stack ? err.stack : err); + t.end(); + } + ).then( + () => { + t.pass('channel was successfully initialized'); + const orgs = channel.getOrganizations(); + logger.debug(' Got the following orgs back %j', orgs); + t.equals(orgs.length, 2, 'Checking the that we got back the right number of orgs'); + if(orgs[0].id.indexOf('Or') == 0) { + t.pass('Found the org name '+ orgs[0].id); + } + else { + t.fail('Did not find the org name of \'org\' :: found ' + orgs[0].id); + } + t.end(); + }, + (err) => { + t.fail('Failed to send query due to error: ' + err.stack ? err.stack : err); + t.end(); } - else { - t.fail('Did not find the org name of \'org\' :: found ' + orgs[0].id); + ).catch( + (err) => { + t.fail('Failed to query with error:' + err.stack ? err.stack : err); + t.end(); } - t.end(); - }, - function(err) { - t.fail('Failed to send query due to error: ' + err.stack ? err.stack : err); - t.end(); - } - ).catch( - function(err) { - t.fail('Failed to query with error:' + err.stack ? err.stack : err); - t.end(); - } - ); - }); + ); + }); }); diff --git a/test/integration/grpc.js b/test/integration/grpc.js index 7d99cf1335..2cf925a5bc 100644 --- a/test/integration/grpc.js +++ b/test/integration/grpc.js @@ -6,19 +6,19 @@ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); +const utils = require('fabric-client/lib/utils.js'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var fs = require('fs'); -var crypto = require('crypto'); +const path = require('path'); +const fs = require('fs'); +const crypto = require('crypto'); -var e2eUtils = require('./e2e/e2eUtils.js'); -var testUtil = require('../unit/util.js'); -var Client = require('fabric-client'); +const e2eUtils = require('./e2e/e2eUtils.js'); +const testUtil = require('../unit/util.js'); +const Client = require('fabric-client'); const GRPC_SEND = 'grpc.max_send_message_length'; const GRPC_RECEIVE = 'grpc.max_receive_message_length'; @@ -165,12 +165,12 @@ async function send(client, channel, url, cc, opts, megs, grpc_send_max, grpc_re if(sdk_send_max !== null) utils.setConfigSetting('grpc-max-send-message-length', sdk_send_max); if(sdk_receive_max !== null) utils.setConfigSetting('grpc-max-receive-message-length', sdk_receive_max); - let peer = client.newPeer( + const peer = client.newPeer( url, opts ); - let request = { + const request = { targets: [peer], chaincodeId : cc, fcn: 'echo', @@ -183,9 +183,9 @@ async function send(client, channel, url, cc, opts, megs, grpc_send_max, grpc_re async function sendToConnectionProfile(client, channel, config, cc, megs) { client.loadFromConfig(config); - let peer = client.getPeersForOrg('Org1MSP')[0]; // will only be one + const peer = client.getPeersForOrg('Org1MSP')[0]; // will only be one - let request = { + const request = { targets: [peer], chaincodeId : cc, fcn: 'echo', @@ -197,9 +197,9 @@ async function sendToConnectionProfile(client, channel, config, cc, megs) { } function checkResponse(t, response, message, error_message) { - var err = (response[0] && response[0][0] && response[0][0] instanceof Error) ? response[0][0] : {}; - let pattern = new RegExp('\\b(' + error_message + ')', 'g'); - let error_words_length = error_message.split('|').length; + const err = (response[0] && response[0][0] && response[0][0] instanceof Error) ? response[0][0] : {}; + const pattern = new RegExp('\\b(' + error_message + ')', 'g'); + const error_words_length = error_message.split('|').length; if(err.message) { if(pattern.test(err.message) && err.message.match(pattern).length == error_words_length) { diff --git a/test/integration/install.js b/test/integration/install.js index d65783a161..c1c48f14d5 100644 --- a/test/integration/install.js +++ b/test/integration/install.js @@ -8,23 +8,23 @@ // in a happy-path scenario 'use strict'; -var rewire = require('rewire'); -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('install'); +const rewire = require('rewire'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('install'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var fs = require('fs'); -var e2eUtils = require('./e2e/e2eUtils.js'); +const path = require('path'); +const fs = require('fs'); +const e2eUtils = require('./e2e/e2eUtils.js'); -var Client = require('fabric-client'); -var Packager = require('fabric-client/lib/Packager.js'); -var testUtil = require('../unit/util.js'); +const Client = require('fabric-client'); +const Packager = require('fabric-client/lib/Packager.js'); +const testUtil = require('../unit/util.js'); -var ORGS; +let ORGS; test('\n\n** Test chaincode install using chaincodePath to create chaincodePackage **\n\n', (t) => { testUtil.resetDefaults(); @@ -32,7 +32,7 @@ test('\n\n** Test chaincode install using chaincodePath to create chaincodePacka Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); - var params = { + const params = { org: 'org1', testDesc: 'using chaincodePath', channelName: 'test-install', @@ -52,37 +52,37 @@ test('\n\n** Test chaincode install using chaincodePath to create chaincodePacka t.end(); } }, - (err) => { - t.fail('install reject: ' + err); - t.end(); - }).catch((err) => { - t.fail('install error. ' + err.stack ? err.stack : err); - t.end(); - }).then(() => { - params.channelName = params.channelName + '0'; - params.testDesc = params.testDesc + '0'; - installChaincode(params, t) - .then((info) => { - if (info && info instanceof Error && info.message.includes('install.' + params.chaincodeVersion + ' exists')) { - t.pass('passed check for exists on install again'); - t.end(); - } else { - t.fail('failed check for exists on install again'); - t.end(); - } - }, - (err) => { - t.fail('install reject: ' + err); - t.end(); - }).catch((err) => { - t.fail('install error. ' + err.stack ? err.stack : err); - t.end(); - }); - }); + (err) => { + t.fail('install reject: ' + err); + t.end(); + }).catch((err) => { + t.fail('install error. ' + err.stack ? err.stack : err); + t.end(); + }).then(() => { + params.channelName = params.channelName + '0'; + params.testDesc = params.testDesc + '0'; + installChaincode(params, t) + .then((info) => { + if (info && info instanceof Error && info.message.includes('install.' + params.chaincodeVersion + ' exists')) { + t.pass('passed check for exists on install again'); + t.end(); + } else { + t.fail('failed check for exists on install again'); + t.end(); + } + }, + (err) => { + t.fail('install reject: ' + err); + t.end(); + }).catch((err) => { + t.fail('install error. ' + err.stack ? err.stack : err); + t.end(); + }); + }); }); test('\n\n** Test chaincode install using chaincodePackage[byte] **\n\n', (t) => { - var params = { + const params = { org: 'org1', testDesc: 'using chaincodePackage', channelName: 'test-install-package', @@ -91,10 +91,10 @@ test('\n\n** Test chaincode install using chaincodePackage[byte] **\n\n', (t) => chaincodeVersion: testUtil.getUniqueVersion() }; - let _getChaincodeDeploymentSpec = rewire('fabric-client/lib/Client.js').__get__('_getChaincodeDeploymentSpec'); + const _getChaincodeDeploymentSpec = rewire('fabric-client/lib/Client.js').__get__('_getChaincodeDeploymentSpec'); // install from source - let p = _getChaincodeDeploymentSpec(params, false) + const p = _getChaincodeDeploymentSpec(params, false) .then((cdsBytes) => { params.chaincodePackage = cdsBytes; installChaincode(params, t) @@ -107,49 +107,49 @@ test('\n\n** Test chaincode install using chaincodePackage[byte] **\n\n', (t) => t.end(); } }, - (err) => { - t.fail(params.testDesc + ' - install reject: ' + err); - t.end(); - }).catch((err) => { - t.fail(params.testDesc + ' - install error. ' + err.stack ? err.stack : err); - t.end(); - }).then(() => { - params.channelName = params.channelName + '0'; - params.testDesc = params.testDesc + '0'; - installChaincode(params, t) - .then((info) => { - if (info && info instanceof Error && info.message.includes('install-package.' + params.chaincodeVersion + ' exists')) { - t.pass('passed check for exists same code again'); - t.end(); - } else { - t.fail('failed check for exists same code again'); - t.end(); - } - }, - (err) => { - t.fail(params.testDesc + ' - install same chaincode again - reject, error'); - logger.error(err.stack ? err.stack : err); - t.end(); - }).catch((err) => { - t.fail(params.testDesc + ' - install same chaincode again - error'); - logger.error(err.stack ? err.stack : err); - t.end(); - }); - }); + (err) => { + t.fail(params.testDesc + ' - install reject: ' + err); + t.end(); + }).catch((err) => { + t.fail(params.testDesc + ' - install error. ' + err.stack ? err.stack : err); + t.end(); + }).then(() => { + params.channelName = params.channelName + '0'; + params.testDesc = params.testDesc + '0'; + installChaincode(params, t) + .then((info) => { + if (info && info instanceof Error && info.message.includes('install-package.' + params.chaincodeVersion + ' exists')) { + t.pass('passed check for exists same code again'); + t.end(); + } else { + t.fail('failed check for exists same code again'); + t.end(); + } + }, + (err) => { + t.fail(params.testDesc + ' - install same chaincode again - reject, error'); + logger.error(err.stack ? err.stack : err); + t.end(); + }).catch((err) => { + t.fail(params.testDesc + ' - install same chaincode again - error'); + logger.error(err.stack ? err.stack : err); + t.end(); + }); + }); }); t.end(); }); function installChaincode(params, t) { try { - var org = params.org; - var client = new Client(); - var channel = client.newChannel(params.channelName); - - let orgName = ORGS[org].name; - var caRootsPath = ORGS.orderer.tls_cacerts; - let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); - let caroots = Buffer.from(data).toString(); + const org = params.org; + const client = new Client(); + const channel = client.newChannel(params.channelName); + + const orgName = ORGS[org].name; + const caRootsPath = ORGS.orderer.tls_cacerts; + const data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + const caroots = Buffer.from(data).toString(); let tlsInfo = null; return e2eUtils.tlsEnroll(org) @@ -178,12 +178,12 @@ function installChaincode(params, t) { ) ); - var targets = []; - for (let key in ORGS[org]) { + const targets = []; + for (const key in ORGS[org]) { if (ORGS[org].hasOwnProperty(key)) { if (key.indexOf('peer') === 0) { - let data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); - let peer = client.newPeer( + const data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); + const peer = client.newPeer( ORGS[org][key].requests, { pem: Buffer.from(data).toString(), @@ -198,7 +198,7 @@ function installChaincode(params, t) { } // send proposal to endorser - var request = { + const request = { targets: targets, chaincodePath: params.chaincodePath, chaincodeId: params.chaincodeId, @@ -208,38 +208,38 @@ function installChaincode(params, t) { return client.installChaincode(request); }, - (err) => { - t.fail(params.testDesc + ' - Failed to enroll user \'admin\'. ' + err); - throw new Error(params.testDesc + ' - Failed to enroll user \'admin\'. ' + err); - }).then((results) => { - var proposalResponses = results[0]; - - //var proposal = results[1]; - var all_good = true; - var error = null; - for (var i in proposalResponses) { - let one_good = false; - if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) { - one_good = true; - logger.info(params.testDesc + ' - install proposal was good'); - } else { - logger.error(params.testDesc + ' - install proposal was bad'); - error = proposalResponses[i]; - } - all_good = all_good & one_good; - } - if (all_good) { - return 'success'; + (err) => { + t.fail(params.testDesc + ' - Failed to enroll user \'admin\'. ' + err); + throw new Error(params.testDesc + ' - Failed to enroll user \'admin\'. ' + err); + }).then((results) => { + const proposalResponses = results[0]; + + //var proposal = results[1]; + let all_good = true; + let error = null; + for (const i in proposalResponses) { + let one_good = false; + if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) { + one_good = true; + logger.info(params.testDesc + ' - install proposal was good'); } else { - if (error) { - return error; - } - else return 'fail'; + logger.error(params.testDesc + ' - install proposal was bad'); + error = proposalResponses[i]; } - }, - (err) => { - return new Error(err.stack ? err.stack : err); - }); + all_good = all_good & one_good; + } + if (all_good) { + return 'success'; + } else { + if (error) { + return error; + } + else return 'fail'; + } + }, + (err) => { + return new Error(err.stack ? err.stack : err); + }); } catch (err) { return Promise.reject(new Error(err.stack ? err.stack : err)); } diff --git a/test/integration/instantiate.js b/test/integration/instantiate.js index dac213f82e..05c738c488 100644 --- a/test/integration/instantiate.js +++ b/test/integration/instantiate.js @@ -6,25 +6,25 @@ 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var fs = require('fs'); -var util = require('util'); +const path = require('path'); +const fs = require('fs'); +const util = require('util'); -var Client = require('fabric-client'); -var utils = require('fabric-client/lib/utils.js'); -var e2eUtils = require('./e2e/e2eUtils.js'); -var testUtil = require('../unit/util.js'); -var logger = utils.getLogger('instantiate-chaincode'); +const Client = require('fabric-client'); +const utils = require('fabric-client/lib/utils.js'); +const e2eUtils = require('./e2e/e2eUtils.js'); +const testUtil = require('../unit/util.js'); +const logger = utils.getLogger('instantiate-chaincode'); -var e2e = testUtil.END2END; -var version = 'v0'; +const e2e = testUtil.END2END; +const version = 'v0'; test('\n\n **** E R R O R T E S T I N G : instantiate call fails with non-existent Chaincode version', (t) => { - var request = { + const request = { chaincodeId: e2e.chaincodeId, chaincodeVersion: 'v333333333', fcn: 'init', @@ -32,12 +32,12 @@ test('\n\n **** E R R O R T E S T I N G : instantiate call fails with non-exist txId: '' }; - var error_snip = 'cannot get package for chaincode'; + const error_snip = 'cannot get package for chaincode'; instantiateChaincodeForError(request, error_snip, t); }); test('\n\n **** E R R O R T E S T I N G : instantiate call fails with non-existent Chaincode name', (t) => { - var request = { + const request = { chaincodeId: 'dummy', chaincodeVersion: version, fcn: 'init', @@ -45,36 +45,36 @@ test('\n\n **** E R R O R T E S T I N G : instantiate call fails with non-exist txId: '' }; - var error_snip = 'cannot get package for chaincode'; + const error_snip = 'cannot get package for chaincode'; instantiateChaincodeForError(request, error_snip, t); }); test('\n\n***** End-to-end flow: instantiate chaincode *****\n\n', (t) => { e2eUtils.instantiateChaincode('org1', testUtil.CHAINCODE_PATH, 'v0', 'golang', false, false, t) - .then((result) => { - if(result){ - t.pass('Successfully instantiated chaincode on the channel'); - - return e2eUtils.sleep(5000); - } - else { - t.fail('Failed to instantiate chaincode '); + .then((result) => { + if(result){ + t.pass('Successfully instantiated chaincode on the channel'); + + return e2eUtils.sleep(5000); + } + else { + t.fail('Failed to instantiate chaincode '); + t.end(); + } + }, (err) => { + t.fail('Failed to instantiate chaincode on the channel. ' + err.stack ? err.stack : err); + t.end(); + }).then(() => { + logger.debug('Successfully slept 5s to wait for chaincode instantiate to be completed and committed in all peers'); + t.end(); + }).catch((err) => { + t.fail('Test failed due to unexpected reasons. ' + err); t.end(); - } - }, (err) => { - t.fail('Failed to instantiate chaincode on the channel. ' + err.stack ? err.stack : err); - t.end(); - }).then(() => { - logger.debug('Successfully slept 5s to wait for chaincode instantiate to be completed and committed in all peers'); - t.end(); - }).catch((err) => { - t.fail('Test failed due to unexpected reasons. ' + err); - t.end(); - }); + }); }); test('\n\n **** E R R O R T E S T I N G : instantiate call fails by instantiating the same Chaincode twice', (t) => { - var request = { + const request = { chaincodeId : e2e.chaincodeId, chaincodeVersion : version, fcn: 'init', @@ -82,90 +82,90 @@ test('\n\n **** E R R O R T E S T I N G : instantiate call fails by instantiati txId: '' }; - var error_snip = 'already exists'; + const error_snip = 'already exists'; instantiateChaincodeForError(request, error_snip, t); }); function instantiateChaincodeForError(request, error_snip, t) { Client.addConfigFile(path.join(__dirname, './e2e/config.json')); - var ORGS = Client.getConfigSetting('test-network'); + const ORGS = Client.getConfigSetting('test-network'); - var caRootsPath = ORGS.orderer.tls_cacerts; - let data = fs.readFileSync(path.join(__dirname, '/test', caRootsPath)); - let caroots = Buffer.from(data).toString(); + const caRootsPath = ORGS.orderer.tls_cacerts; + const data = fs.readFileSync(path.join(__dirname, '/test', caRootsPath)); + const caroots = Buffer.from(data).toString(); - var userOrg = 'org1'; - var client = new Client(); - var channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); + const userOrg = 'org1'; + const client = new Client(); + const channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); logger.debug(' channel_name %s', channel_name); - var channel = client.newChannel(channel_name); - var orgName = ORGS[userOrg].name; - var tlsInfo = null; + const channel = client.newChannel(channel_name); + const orgName = ORGS[userOrg].name; + let tlsInfo = null; e2eUtils.tlsEnroll(userOrg) - .then((enrollment) => { - t.pass('Successfully retrieved TLS certificate'); - tlsInfo = enrollment; - client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); - return Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(orgName)}); - }).then((store) => { - client.setStateStore(store); - return testUtil.getSubmitter(client, t, true /* use peer org admin */, userOrg); - }).then(() => { - t.pass('Successfully enrolled user \'admin\''); - - channel.addOrderer( - client.newOrderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'clientCert': tlsInfo.certificate, - 'clientKey': tlsInfo.key, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) - ); - - var targets = []; - for (let org in ORGS) { - if (ORGS[org].hasOwnProperty('peer1')) { - let key = 'peer1'; - let data = fs.readFileSync(path.join(__dirname, '/test', ORGS[org][key]['tls_cacerts'])); - logger.debug(' create new peer %s', ORGS[org][key].requests); - let peer = client.newPeer( - ORGS[org][key].requests, + .then((enrollment) => { + t.pass('Successfully retrieved TLS certificate'); + tlsInfo = enrollment; + client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); + return Client.newDefaultKeyValueStore({path: testUtil.storePathForOrg(orgName)}); + }).then((store) => { + client.setStateStore(store); + return testUtil.getSubmitter(client, t, true /* use peer org admin */, userOrg); + }).then(() => { + t.pass('Successfully enrolled user \'admin\''); + + channel.addOrderer( + client.newOrderer( + ORGS.orderer.url, { - pem: Buffer.from(data).toString(), + 'pem': caroots, 'clientCert': tlsInfo.certificate, 'clientKey': tlsInfo.key, - 'ssl-target-name-override': ORGS[org][key]['server-hostname'] + 'ssl-target-name-override': ORGS.orderer['server-hostname'] } - ); - targets.push(peer); - channel.addPeer(peer); + ) + ); + + const targets = []; + for (const org in ORGS) { + if (ORGS[org].hasOwnProperty('peer1')) { + const key = 'peer1'; + const data = fs.readFileSync(path.join(__dirname, '/test', ORGS[org][key]['tls_cacerts'])); + logger.debug(' create new peer %s', ORGS[org][key].requests); + const peer = client.newPeer( + ORGS[org][key].requests, + { + pem: Buffer.from(data).toString(), + 'clientCert': tlsInfo.certificate, + 'clientKey': tlsInfo.key, + 'ssl-target-name-override': ORGS[org][key]['server-hostname'] + } + ); + targets.push(peer); + channel.addPeer(peer); + } } - } - - return channel.initialize(); - }, (err) => { - t.fail('Failed to enroll user \'admin\'. ' + err); - throw new Error('Failed to enroll user \'admin\'. ' + err); - }).then(() => { - t.pass('Successfully initialized channel'); - request.txId = client.newTransactionID(); - return channel.sendInstantiateProposal(request); - }, (err) => { - t.fail(util.format('Failed to initialize the channel. %s', err.stack ? err.stack : err)); - throw new Error('Failed to initialize the channel'); - }).then((results) => { - testUtil.checkResults(results, error_snip, t); - t.end(); - }, (err) => { - t.fail('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); - throw new Error('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); - }).catch((err) => { - t.fail('Test failed due to unexpected reasons. ' + err); - t.end(); - }); + + return channel.initialize(); + }, (err) => { + t.fail('Failed to enroll user \'admin\'. ' + err); + throw new Error('Failed to enroll user \'admin\'. ' + err); + }).then(() => { + t.pass('Successfully initialized channel'); + request.txId = client.newTransactionID(); + return channel.sendInstantiateProposal(request); + }, (err) => { + t.fail(util.format('Failed to initialize the channel. %s', err.stack ? err.stack : err)); + throw new Error('Failed to initialize the channel'); + }).then((results) => { + testUtil.checkResults(results, error_snip, t); + t.end(); + }, (err) => { + t.fail('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); + throw new Error('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); + }).catch((err) => { + t.fail('Test failed due to unexpected reasons. ' + err); + t.end(); + }); } diff --git a/test/integration/invoke.js b/test/integration/invoke.js index 1d681569ec..ccf2248020 100644 --- a/test/integration/invoke.js +++ b/test/integration/invoke.js @@ -35,43 +35,43 @@ init(); test('\n\n***** E R R O R T E S T I N G: invoke transaction with one endorsement *****\n\n', (t) => { invokeChaincode('org2', 'v0', t, 'ENDORSEMENT_POLICY_FAILURE', [peers[0]]) - .then((result) => { - if(result){ - t.pass('Successfully tested failure to invoke transaction chaincode due to insufficient endorsement'); + .then((result) => { + if(result){ + t.pass('Successfully tested failure to invoke transaction chaincode due to insufficient endorsement'); - return invokeChaincode('org2', 'v0', t, 'ENDORSEMENT_POLICY_FAILURE', [peers[1]]); - } - else { - t.fail('Failed to invoke transaction chaincode'); - t.end(); - } - }, (err) => { - t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); - t.end(); - }).then((result) => { - if(result){ - t.pass('Successfully tested failure to invoke transaction chaincode due to insufficient endorsement'); + return invokeChaincode('org2', 'v0', t, 'ENDORSEMENT_POLICY_FAILURE', [peers[1]]); + } + else { + t.fail('Failed to invoke transaction chaincode'); + t.end(); + } + }, (err) => { + t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); t.end(); - } - else { - t.fail('Failed to invoke transaction chaincode'); + }).then((result) => { + if(result){ + t.pass('Successfully tested failure to invoke transaction chaincode due to insufficient endorsement'); + t.end(); + } + else { + t.fail('Failed to invoke transaction chaincode'); + t.end(); + } + }, (err) => { + t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); t.end(); - } - }, (err) => { - t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); - t.end(); - }); + }); }); test('\n\n***** invoke transaction with inverted order of endorsements *****\n\n', (t) => { invokeChaincode('org2', 'v0', t, false, [peers[1], peers[0]]) - .then(() => { - t.pass('Successfully invoke transaction chaincode on channel'); - t.end(); - }, (err) => { - t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); - t.end(); - }); + .then(() => { + t.pass('Successfully invoke transaction chaincode on channel'); + t.end(); + }, (err) => { + t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); + t.end(); + }); }); function init() { @@ -80,7 +80,7 @@ function init() { ORGS = Client.getConfigSetting('test-network'); } - for (let key in ORGS) { + for (const key in ORGS) { if (ORGS.hasOwnProperty(key) && typeof ORGS[key].peer1 !== 'undefined') { const data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[key].peer1['tls_cacerts'])); const org = ORGS[key].peer1; @@ -100,7 +100,7 @@ function invokeChaincode(userOrg, version, t, shouldFail, peers){ // override t.end function so it'll always disconnect the event hub t.end = ((context, ehs, f) => { return function() { - for(let key in ehs) { + for(const key in ehs) { const eventhub = ehs[key]; if (eventhub && eventhub.isconnected()) { logger.debug('Disconnecting the event hub'); @@ -125,154 +125,154 @@ function invokeChaincode(userOrg, version, t, shouldFail, peers){ let tlsInfo = null; return e2eUtils.tlsEnroll(userOrg) - .then((enrollment) => { - t.pass('Successfully retrieved TLS certificate'); - tlsInfo = enrollment; - client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); - return testUtil.getSubmitter(client, t, userOrg); - }).then(() => { - t.pass('Successfully enrolled user \'admin\''); - - channel.addOrderer( - client.newOrderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) - ); - - for (let key in peers) { - const peer = client.newPeer( - peers[key].requests, - { - pem: peers[key].pem, - 'ssl-target-name-override': peers[key]['server-hostname'], - }); - channel.addPeer(peer); - eventhubs.push(channel.newChannelEventHub(peer)); - } + .then((enrollment) => { + t.pass('Successfully retrieved TLS certificate'); + tlsInfo = enrollment; + client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); + return testUtil.getSubmitter(client, t, userOrg); + }).then(() => { + t.pass('Successfully enrolled user \'admin\''); + + channel.addOrderer( + client.newOrderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); + + for (const key in peers) { + const peer = client.newPeer( + peers[key].requests, + { + pem: peers[key].pem, + 'ssl-target-name-override': peers[key]['server-hostname'], + }); + channel.addPeer(peer); + eventhubs.push(channel.newChannelEventHub(peer)); + } - return channel.initialize(); + return channel.initialize(); - }).then(() => { - tx_id = client.newTransactionID(); + }).then(() => { + tx_id = client.newTransactionID(); - // send proposal to endorser - const request = { - chaincodeId : e2e.chaincodeId, - fcn: 'move', - args: ['a', 'b', '100'], - txId: tx_id, - }; - return channel.sendTransactionProposal(request); - - }, (err) => { - t.fail('Failed to enroll user \'admin\'. ' + err); - throw new Error('Failed to enroll user \'admin\'. ' + err); - - }).then((results) => { - const proposalResponses = results[0]; - const proposal = results[1]; - let all_good = true; - - for(let i in proposalResponses) { - let one_good = false; - const proposal_response = proposalResponses[i]; - if( proposal_response.response && proposal_response.response.status === 200) { - t.pass('transaction proposal has response status of good'); - one_good = channel.verifyProposalResponse(proposal_response); - if(one_good) { - t.pass(' transaction proposal signature and endorser are valid'); + // send proposal to endorser + const request = { + chaincodeId : e2e.chaincodeId, + fcn: 'move', + args: ['a', 'b', '100'], + txId: tx_id, + }; + return channel.sendTransactionProposal(request); + + }, (err) => { + t.fail('Failed to enroll user \'admin\'. ' + err); + throw new Error('Failed to enroll user \'admin\'. ' + err); + + }).then((results) => { + const proposalResponses = results[0]; + const proposal = results[1]; + let all_good = true; + + for(const i in proposalResponses) { + let one_good = false; + const proposal_response = proposalResponses[i]; + if( proposal_response.response && proposal_response.response.status === 200) { + t.pass('transaction proposal has response status of good'); + one_good = channel.verifyProposalResponse(proposal_response); + if(one_good) { + t.pass(' transaction proposal signature and endorser are valid'); + } + } else { + t.fail('transaction proposal was bad'); } - } else { - t.fail('transaction proposal was bad'); + all_good = all_good & one_good; } - all_good = all_good & one_good; - } - if (all_good) { + if (all_good) { // check all the read/write sets to see if the same, verify that each peer // got the same results on the proposal - all_good = channel.compareProposalResponseResults(proposalResponses); - t.pass('compareProposalResponseResults exection did not throw an error'); - if(all_good){ - t.pass(' All proposals have a matching read/writes sets'); - } - else { - t.fail(' All proposals do not have matching read/write sets'); + all_good = channel.compareProposalResponseResults(proposalResponses); + t.pass('compareProposalResponseResults exection did not throw an error'); + if(all_good){ + t.pass(' All proposals have a matching read/writes sets'); + } + else { + t.fail(' All proposals do not have matching read/write sets'); + } } - } - if (all_good) { + if (all_good) { // check to see if all the results match - t.pass('Successfully sent Proposal and received ProposalResponse'); - logger.debug(util.format('Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', proposalResponses[0].response.status, proposalResponses[0].response.message, proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature)); - - const request = { - proposalResponses: proposalResponses, - proposal: proposal - }; - - // set the transaction listener and set a timeout of 30sec - // if the transaction did not get committed within the timeout period, - // fail the test - const deployId = tx_id.getTransactionID(); - - const eventPromises = []; - eventhubs.forEach((eh) => { - const txPromise = new Promise((resolve, reject) => { - const handle = setTimeout(reject, 120000); - - eh.registerTxEvent(deployId.toString(), - (tx, code) => { - clearTimeout(handle); - eh.unregisterTxEvent(deployId); - - if (code !== 'VALID') { - if (shouldFail !== false && code === shouldFail) { - t.pass('The balance transaction failed with ' + shouldFail + ' as expected'); - resolve(); + t.pass('Successfully sent Proposal and received ProposalResponse'); + logger.debug(util.format('Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', proposalResponses[0].response.status, proposalResponses[0].response.message, proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature)); + + const request = { + proposalResponses: proposalResponses, + proposal: proposal + }; + + // set the transaction listener and set a timeout of 30sec + // if the transaction did not get committed within the timeout period, + // fail the test + const deployId = tx_id.getTransactionID(); + + const eventPromises = []; + eventhubs.forEach((eh) => { + const txPromise = new Promise((resolve, reject) => { + const handle = setTimeout(reject, 120000); + + eh.registerTxEvent(deployId.toString(), + (tx, code) => { + clearTimeout(handle); + eh.unregisterTxEvent(deployId); + + if (code !== 'VALID') { + if (shouldFail !== false && code === shouldFail) { + t.pass('The balance transaction failed with ' + shouldFail + ' as expected'); + resolve(); + } else { + t.fail('The balance transaction failed with ' + code); + reject(); + } } else { - t.fail('The balance transaction failed with ' + code); - reject(); - } - } else { - if (shouldFail === false) { - t.pass('The balance transfer transaction has been committed on peer '+ eh.getPeerAddr()); - resolve(); - } else { - t.fail('The balance transfer transaction should have failed with ' + shouldFail); - reject(); + if (shouldFail === false) { + t.pass('The balance transfer transaction has been committed on peer '+ eh.getPeerAddr()); + resolve(); + } else { + t.fail('The balance transfer transaction should have failed with ' + shouldFail); + reject(); + } } + }, + () => { + clearTimeout(handle); + t.fail('Failed -- received notification of the event call back being cancelled for '+ deployId); + resolve(); } - }, - () => { - clearTimeout(handle); - t.fail('Failed -- received notification of the event call back being cancelled for '+ deployId); - resolve(); - } - ); + ); + }); + eh.connect(); + + eventPromises.push(txPromise); }); - eh.connect(); - - eventPromises.push(txPromise); - }); - - const sendPromise = channel.sendTransaction(request); - return Promise.all([sendPromise].concat(eventPromises)) - .then((results) => { - logger.debug('event promise all complete and testing complete'); - return results[0]; // the first returned value is from the 'sendPromise' which is from the 'sendTransaction()' call - }).catch((err) => { - t.fail('Failed transaction ::'+ err); - throw new Error('Failed transaction ::'+ err); - }); - } else { - t.fail('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'); - throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'); - } - }, (err) => { - t.fail('Failed to send proposal due to error: ' + err.stack ? err.stack : err); - throw new Error('Failed to send proposal due to error: ' + err.stack ? err.stack : err); - }); + + const sendPromise = channel.sendTransaction(request); + return Promise.all([sendPromise].concat(eventPromises)) + .then((results) => { + logger.debug('event promise all complete and testing complete'); + return results[0]; // the first returned value is from the 'sendPromise' which is from the 'sendTransaction()' call + }).catch((err) => { + t.fail('Failed transaction ::'+ err); + throw new Error('Failed transaction ::'+ err); + }); + } else { + t.fail('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'); + throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'); + } + }, (err) => { + t.fail('Failed to send proposal due to error: ' + err.stack ? err.stack : err); + throw new Error('Failed to send proposal due to error: ' + err.stack ? err.stack : err); + }); } diff --git a/test/integration/javachaincode/query.js b/test/integration/javachaincode/query.js index c789103469..1915432706 100644 --- a/test/integration/javachaincode/query.js +++ b/test/integration/javachaincode/query.js @@ -8,11 +8,11 @@ // in a happy-path scenario 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtils = require('../../unit/util'); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtils = require('../../unit/util'); test('\n\n***** Java-Chaincode End-to-end flow: query chaincode *****\n\n', async (t) => { const chaincode_id = 'example_java'; @@ -23,7 +23,7 @@ test('\n\n***** Java-Chaincode End-to-end flow: query chaincode *****\n\n', asyn let expectedResult = '300'; const targets = []; // empty array, meaning client will get the peers from the channel try { - let result = await e2eUtils.queryChaincode('org2', version, targets, fcn, args, expectedResult, chaincode_id, t); + const result = await e2eUtils.queryChaincode('org2', version, targets, fcn, args, expectedResult, chaincode_id, t); if(result){ t.pass('Successfully query java chaincode on the channel'); } @@ -36,7 +36,7 @@ test('\n\n***** Java-Chaincode End-to-end flow: query chaincode *****\n\n', asyn try { expectedResult = new Error('throwError: an error occurred'); - let result = await e2eUtils.queryChaincode('org2', version, targets, 'throwError', args, expectedResult, chaincode_id, t); + const result = await e2eUtils.queryChaincode('org2', version, targets, 'throwError', args, expectedResult, chaincode_id, t); if(result){ t.pass('Sucessfully handled error from a query on java chaincode'); } diff --git a/test/integration/memory.js b/test/integration/memory.js index 3c8fbe123c..c3f8c45141 100644 --- a/test/integration/memory.js +++ b/test/integration/memory.js @@ -5,17 +5,17 @@ */ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('Memory Usage'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('Memory Usage'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var Client = require('fabric-client'); -var util = require('util'); -var fs = require('fs'); -var path = require('path'); +const Client = require('fabric-client'); +const util = require('util'); +const fs = require('fs'); +const path = require('path'); //var heapdump = require('heapdump'); @@ -39,7 +39,7 @@ var path = require('path'); node --expose-gc test/integration/memory.js count=1000 node --expose-gc test/integration/memory.js count=1000 skipcreate=true */ -test('\n\n***** use the network configuration file *****\n\n', function(t) { +test('\n\n***** use the network configuration file *****\n\n', (t) => { looper(t); t.end(); }); @@ -47,11 +47,11 @@ test('\n\n***** use the network configuration file *****\n\n', function(t) { async function looper(t) { //global.gc(); //heapdump.writeSnapshot(); - var skip = getArg('skipcreate', false); + let skip = getArg('skipcreate', false); if(skip === 'true') skip = true; if(!skip) await createChannel(t); - var count = getArg('count', 1); + const count = getArg('count', 1); for(let i = 0;i 2) { - for(let i in process.argv) { - let arg = process.argv[i]; + for(const i in process.argv) { + const arg = process.argv[i]; if(arg && arg.indexOf(arg_name+'=') === 0) { value = arg.split('=')[1]; } @@ -95,19 +95,19 @@ async function createChannel(t) { // this network config does not have the client information, we will // load that later so that we can switch this client to be in a different // organization - var client = Client.loadFromConfig('test/fixtures/network.yaml'); + const client = Client.loadFromConfig('test/fixtures/network.yaml'); t.pass('Successfully loaded a network configuration'); - var channel_name = 'mychannel2'; - var config = null; - var signatures = []; - var genesis_block = null; - var channel = null; - var instansiate_tx_id = null; - var results = null; - var response = null; - var request = null; - var tx_id = null; + const channel_name = 'mychannel2'; + let config = null; + const signatures = []; + let genesis_block = null; + let channel = null; + let instansiate_tx_id = null; + let results = null; + let response = null; + let request = null; + let tx_id = null; try { // lets load the client information for this organization // the file only has the client section @@ -119,7 +119,7 @@ async function createChannel(t) { t.pass('Successfully created the key value store and crypto store based on the config and network config'); // get the config envelope created by the configtx tool - let envelope_bytes = fs.readFileSync(path.join(__dirname, '../fixtures/channel/mychannel2.tx')); + const envelope_bytes = fs.readFileSync(path.join(__dirname, '../fixtures/channel/mychannel2.tx')); // have the sdk get the config update object from the envelope // the config update object is what is required to be signed by all // participating organizations @@ -127,11 +127,11 @@ async function createChannel(t) { t.pass('Successfully extracted the config update from the configtx envelope'); // sign the config by admin from org1 - var signature = client.signChannelConfig(config); + let signature = client.signChannelConfig(config); // convert signature to a storable string // fabric-client SDK will convert any strings it finds back // to GRPC protobuf objects during the channel create - var string_signature = signature.toBuffer().toString('hex'); + const string_signature = signature.toBuffer().toString('hex'); t.pass('Successfully signed config update by org1'); // collect signature from org1 admin signatures.push(string_signature); @@ -318,8 +318,8 @@ async function createChannel(t) { }; results = await channel.sendInstantiateProposal(request); // still have org2 admin signer - var proposalResponses = results[0]; - var proposal = results[1]; + const proposalResponses = results[0]; + const proposal = results[1]; if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) { t.pass('Successfully sent Proposal and received ProposalResponse'); request = { @@ -362,17 +362,17 @@ async function actions(t) { // this network config does not have the client information, we will // load that later so that we can switch this client to be in a different // organization - var client = Client.loadFromConfig('test/fixtures/network.yaml'); + const client = Client.loadFromConfig('test/fixtures/network.yaml'); t.pass('Successfully loaded a network configuration'); - var channel_name = 'mychannel2'; - var channel = null; - var query_tx_id = null; - var results = null; - var response = null; - var request = null; - var tx_id = null; - var found = null; + const channel_name = 'mychannel2'; + let channel = null; + let query_tx_id = null; + let results = null; + let response = null; + let request = null; + let tx_id = null; + let found = null; try { // lets load the client information for this organization // the file only has the client section @@ -399,12 +399,12 @@ async function actions(t) { }; results = await channel.sendTransactionProposal(request); //logged in as org2 user - var proposalResponses = results[0]; - var proposal = results[1]; - var all_good = true; - for(var i in proposalResponses) { + const proposalResponses = results[0]; + const proposal = results[1]; + let all_good = true; + for(const i in proposalResponses) { let one_good = false; - let proposal_response = proposalResponses[i]; + const proposal_response = proposalResponses[i]; if( proposal_response.response && proposal_response.response.status === 200) { t.pass('transaction proposal has response status of good'); one_good = true; @@ -424,7 +424,7 @@ async function actions(t) { admin : false }; - var eventhub = channel.getChannelEventHub('peer0.org1.example.com'); + const eventhub = channel.getChannelEventHub('peer0.org1.example.com'); response = await invoke(t, request, tx_id, client, channel, eventhub); //logged in as org2 user if (!(response[0] instanceof Error) && response[0].status === 'SUCCESS') { @@ -440,7 +440,7 @@ async function actions(t) { args: ['b'] }; - let response_payloads = await channel.queryByChaincode(request); //logged in as user on org1 + const response_payloads = await channel.queryByChaincode(request); //logged in as user on org1 if (response_payloads) { for(let i = 0; i < response_payloads.length; i++) { t.pass('Successfully got query results :: '+ response_payloads[i].toString('utf8')); @@ -453,7 +453,7 @@ async function actions(t) { results = await client.queryChannels('peer0.org1.example.com'); logger.debug(' queryChannels ::%j',results); found = false; - for(let i in results.channels) { + for(const i in results.channels) { logger.debug(' queryChannels has found %s', results.channels[i].channel_id); if(results.channels[i].channel_id === channel_name) { found = true; @@ -468,7 +468,7 @@ async function actions(t) { results = await client.queryInstalledChaincodes('peer0.org1.example.com', true); // use admin logger.debug(' queryInstalledChaincodes ::%j',results); found = false; - for(let i in results.chaincodes) { + for(const i in results.chaincodes) { logger.debug(' queryInstalledChaincodes has found %s', results.chaincodes[i].name); if(results.chaincodes[i].name === 'example') { found = true; @@ -546,12 +546,12 @@ async function actions(t) { function invoke(t, request, tx_id, client, channel, eventhub) { - var transactionID = tx_id.getTransactionID(); - var promises = []; + const transactionID = tx_id.getTransactionID(); + const promises = []; promises.push(channel.sendTransaction(request)); - let txPromise = new Promise((resolve, reject) => { - let handle = setTimeout(() => { + const txPromise = new Promise((resolve, reject) => { + const handle = setTimeout(() => { eventhub.disconnect(); t.fail('REQUEST_TIMEOUT -- eventhub did not respond'); reject(new Error('REQUEST_TIMEOUT:' + eventhub.getPeerAddr())); @@ -573,7 +573,7 @@ function invoke(t, request, tx_id, client, channel, eventhub) { t.fail('Event registration for this transaction was invalid ::' + error); reject(error); }, - {disconnect: true} + {disconnect: true} ); eventhub.connect(); @@ -588,12 +588,12 @@ function sleep(ms) { } function logMemory(clean) { - var memory_usage = process.memoryUsage(); + const memory_usage = process.memoryUsage(); logger.info(' Memory usage :: %j',memory_usage); //info: memory_usage : {"rss":214753280,"heapTotal":55156736,"heapUsed":36789336,"external":5236572} - let now = new Date(); - let line = now.toString() + ',' + memory_usage.rss + ',' + memory_usage.heapTotal + ',' + memory_usage.heapUsed + ',' + memory_usage.external + '\n'; - let file_path = path.join(__dirname, '../memory-usage.csv'); + const now = new Date(); + const line = now.toString() + ',' + memory_usage.rss + ',' + memory_usage.heapTotal + ',' + memory_usage.heapUsed + ',' + memory_usage.external + '\n'; + const file_path = path.join(__dirname, '../memory-usage.csv'); if(clean) { fs.writeFileSync(file_path, 'time,rss,heapTotal,heapUsed,external\n'); } diff --git a/test/integration/network-e2e/install-chaincode.js b/test/integration/network-e2e/install-chaincode.js index a8ef2e6923..931f674d70 100644 --- a/test/integration/network-e2e/install-chaincode.js +++ b/test/integration/network-e2e/install-chaincode.js @@ -8,16 +8,16 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E install-chaincode'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E install-chaincode'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtil = require('../../unit/util.js'); -var version = 'v0'; +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtil = require('../../unit/util.js'); +const version = 'v0'; test('\n\n***** Network End-to-end flow: chaincode install *****\n\n', (t) => { e2eUtils.installChaincodeWithId('org1', testUtil.NETWORK_END2END.chaincodeId, testUtil.NODE_CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'node', t, true) diff --git a/test/integration/network-e2e/instantiate-chaincode.js b/test/integration/network-e2e/instantiate-chaincode.js index a28dd15ff4..bdf0234dc5 100644 --- a/test/integration/network-e2e/instantiate-chaincode.js +++ b/test/integration/network-e2e/instantiate-chaincode.js @@ -8,16 +8,16 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E instantiate-chaincode'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E instantiate-chaincode'); logger.level = 'debug'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtil = require('../../unit/util.js'); +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtil = require('../../unit/util.js'); diff --git a/test/integration/network-e2e/query.js b/test/integration/network-e2e/query.js index f5e286ae55..d3ead095c8 100644 --- a/test/integration/network-e2e/query.js +++ b/test/integration/network-e2e/query.js @@ -45,7 +45,7 @@ test('\n\n***** Network End-to-end flow: execute transaction to get information await fileSystemWallet.import('tlsId', X509WalletMixin.createIdentity('org1', tlsInfo.certificate, tlsInfo.key)); const ccp = fs.readFileSync(fixtures + '/network.json'); - let ccpObject = JSON.parse(ccp.toString()); + const ccpObject = JSON.parse(ccp.toString()); await gateway.connect(ccpObject, { wallet: fileSystemWallet, @@ -65,7 +65,7 @@ test('\n\n***** Network End-to-end flow: execute transaction to get information // try a standard query - let responseBuffer = await contract.executeTransaction('query', 'a'); + const responseBuffer = await contract.executeTransaction('query', 'a'); let response = responseBuffer.toString(); if(response * 1 === parseInt(response)){ diff --git a/test/integration/nodechaincode/install-chaincode.js b/test/integration/nodechaincode/install-chaincode.js index 264b3243d8..7822b86bc9 100644 --- a/test/integration/nodechaincode/install-chaincode.js +++ b/test/integration/nodechaincode/install-chaincode.js @@ -8,16 +8,16 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E install-chaincode'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E install-chaincode'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtil = require('../../unit/util.js'); -var version = 'v0'; +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtil = require('../../unit/util.js'); +const version = 'v0'; test('\n\n***** Node-Chaincode End-to-end flow: chaincode install *****\n\n', (t) => { e2eUtils.installChaincode('org1', testUtil.NODE_CHAINCODE_PATH, testUtil.METADATA_PATH, version, 'node', t, true) diff --git a/test/integration/nodechaincode/instantiate-chaincode.js b/test/integration/nodechaincode/instantiate-chaincode.js index 51c8d20935..ac00c28e93 100644 --- a/test/integration/nodechaincode/instantiate-chaincode.js +++ b/test/integration/nodechaincode/instantiate-chaincode.js @@ -8,16 +8,16 @@ // in a happy-path scenario 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E instantiate-chaincode'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E instantiate-chaincode'); logger.level = 'debug'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtil = require('../../unit/util.js'); +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtil = require('../../unit/util.js'); diff --git a/test/integration/nodechaincode/invoke.js b/test/integration/nodechaincode/invoke.js index e3e4b25043..7e477d61ee 100644 --- a/test/integration/nodechaincode/invoke.js +++ b/test/integration/nodechaincode/invoke.js @@ -8,19 +8,19 @@ // in a happy-path scenario 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtils = require('../../unit/util'); -var chaincodeId = testUtils.NODE_END2END.chaincodeId; +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtils = require('../../unit/util'); +const chaincodeId = testUtils.NODE_END2END.chaincodeId; test('\n\n***** Node-Chaincode End-to-end flow: invoke transaction to move money *****\n\n', async (t) => { const fcn = 'move'; const args = ['a', 'b','100']; let expectedResult = 'move succeed'; try { - let result = await e2eUtils.invokeChaincode('org2', 'v0', chaincodeId, t, false/*useStore*/, fcn, args, expectedResult); + const result = await e2eUtils.invokeChaincode('org2', 'v0', chaincodeId, t, false/*useStore*/, fcn, args, expectedResult); if(result){ t.pass('Successfully invoke transaction chaincode on channel'); await testUtils.sleep(5000); @@ -34,7 +34,7 @@ test('\n\n***** Node-Chaincode End-to-end flow: invoke transaction to move money try { expectedResult = new Error('throwError: an error occurred'); - let result = await e2eUtils.invokeChaincode('org2', 'v0', chaincodeId, t, false/*useStore*/, 'throwError', args, expectedResult); + const result = await e2eUtils.invokeChaincode('org2', 'v0', chaincodeId, t, false/*useStore*/, 'throwError', args, expectedResult); if(result){ t.pass('Successfully handled invocation errors'); } diff --git a/test/integration/nodechaincode/query.js b/test/integration/nodechaincode/query.js index d237388569..81fa252e32 100644 --- a/test/integration/nodechaincode/query.js +++ b/test/integration/nodechaincode/query.js @@ -8,12 +8,12 @@ // in a happy-path scenario 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtils = require('../../unit/util'); -var chaincodeId = testUtils.NODE_END2END.chaincodeId; +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtils = require('../../unit/util'); +const chaincodeId = testUtils.NODE_END2END.chaincodeId; test('\n\n***** Node-Chaincode End-to-end flow: query chaincode *****\n\n', async (t) => { const fcn = 'query'; @@ -21,7 +21,7 @@ test('\n\n***** Node-Chaincode End-to-end flow: query chaincode *****\n\n', asyn let expectedResult = '300'; const targets = []; // empty array, meaning client will get the peers from the channel try { - let result = await e2eUtils.queryChaincode('org2', 'v0', targets, fcn, args, expectedResult, chaincodeId, t); + const result = await e2eUtils.queryChaincode('org2', 'v0', targets, fcn, args, expectedResult, chaincodeId, t); if(result){ t.pass('Successfully query chaincode on the channel'); } @@ -34,7 +34,7 @@ test('\n\n***** Node-Chaincode End-to-end flow: query chaincode *****\n\n', asyn try { expectedResult = new Error('throwError: an error occurred'); - let result = await e2eUtils.queryChaincode('org2', 'v0', targets, 'throwError', args, expectedResult, chaincodeId, t); + const result = await e2eUtils.queryChaincode('org2', 'v0', targets, 'throwError', args, expectedResult, chaincodeId, t); if(result){ t.pass('Sucessfully handled error from a query'); } diff --git a/test/integration/nodechaincode/upgrade.js b/test/integration/nodechaincode/upgrade.js index d3a65a9b57..e99a1ffc8e 100644 --- a/test/integration/nodechaincode/upgrade.js +++ b/test/integration/nodechaincode/upgrade.js @@ -8,13 +8,13 @@ // in a happy-path scenario 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var e2eUtils = require('../e2e/e2eUtils.js'); -var testUtil = require('../../unit/util.js'); -var chaincodeId = testUtil.NODE_END2END.chaincodeId; -var version = 'v1'; +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const e2eUtils = require('../e2e/e2eUtils.js'); +const testUtil = require('../../unit/util.js'); +const chaincodeId = testUtil.NODE_END2END.chaincodeId; +const version = 'v1'; test('\n\n***** Node-Chaincode U P G R A D E flow: chaincode install *****\n\n', (t) => { e2eUtils.installChaincode('org1', testUtil.NODE_CHAINCODE_UPGRADE_PATH, null, version, 'node', t, true) diff --git a/test/integration/only-admin.js b/test/integration/only-admin.js index a5aa34d9cb..ea6dffead2 100644 --- a/test/integration/only-admin.js +++ b/test/integration/only-admin.js @@ -27,7 +27,7 @@ const testUtil = require('../unit/util.js'); // Testing will also demostrate how to read and set the admin identity manually // Only one call will be made with this, however if the identity has access, all // the calls made by connection profile demonstration may also be made. -test('\n\n***** use only admin identity *****\n\n', async function(t) { +test('\n\n***** use only admin identity *****\n\n', async (t) => { const channel_name = 'adminconfig'; const client_org1 = await testUtil.getClientForOrg(t, 'org1'); diff --git a/test/integration/orderer-channel-tests.js b/test/integration/orderer-channel-tests.js index 80e1dc4e9c..772479cbc7 100644 --- a/test/integration/orderer-channel-tests.js +++ b/test/integration/orderer-channel-tests.js @@ -5,26 +5,26 @@ */ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); +const utils = require('fabric-client/lib/utils.js'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var e2eUtils = require('./e2e/e2eUtils.js'); -var fs = require('fs'); -var path = require('path'); +const e2eUtils = require('./e2e/e2eUtils.js'); +const fs = require('fs'); +const path = require('path'); -var testUtil = require('../unit/util.js'); +const testUtil = require('../unit/util.js'); -var Client = require('fabric-client'); -var Orderer = require('fabric-client/lib/Orderer.js'); +const Client = require('fabric-client'); +const Orderer = require('fabric-client/lib/Orderer.js'); -var ORGS; +let ORGS; -var client = new Client(); -var org = 'org1'; +const client = new Client(); +const org = 'org1'; // // Orderer via member missing orderer @@ -33,18 +33,18 @@ var org = 'org1'; // before the orderer URL was set. Verify that an error is reported when tying // to send the request. // -test('\n\n** TEST ** orderer via member missing orderer', function(t) { +test('\n\n** TEST ** orderer via member missing orderer', (t) => { testUtil.resetDefaults(); utils.setConfigSetting('key-value-store', 'fabric-ca-client/lib/impl/FileKeyValueStore.js');//force for 'gulp test' Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); - let orgName = ORGS[org].name; + const orgName = ORGS[org].name; // // Create and configure the test channel // - let channel = client.newChannel('testchannel-orderer-member2'); - let cryptoSuite = Client.newCryptoSuite(); + const channel = client.newChannel('testchannel-orderer-member2'); + const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); @@ -54,18 +54,18 @@ test('\n\n** TEST ** orderer via member missing orderer', function(t) { client.setStateStore(store); return testUtil.getSubmitter(client, t, org); }).then( - function() { + () => { t.pass('Successfully enrolled user \'admin\''); // send to orderer return channel.sendTransaction('data'); }, - function(err) { + (err) => { t.fail('Failed to enroll user \'admin\'. ' + err); t.end(); } ).then( - function(status) { + (status) => { if (status === 0) { t.fail('Successfully submitted request, which is bad because the channel is missing orderers.'); } else { @@ -74,12 +74,12 @@ test('\n\n** TEST ** orderer via member missing orderer', function(t) { t.end(); }, - function(err) { + (err) => { t.comment('Error: ' + err); t.pass('Successfully tested invalid submission due to missing orderers. Error code: ' + err); t.end(); } - ).catch(function(err) { + ).catch((err) => { t.fail('Failed request. ' + err); t.end(); }); @@ -92,76 +92,76 @@ test('\n\n** TEST ** orderer via member missing orderer', function(t) { // with the data set to null. Verify that an error is reported when tying // to send null data. // -test('\n\n** TEST ** orderer via member null data', function(t) { +test('\n\n** TEST ** orderer via member null data', (t) => { // // Create and configure the test channel // - var channel = client.newChannel('testchannel-orderer-member3'); - var caRootsPath = ORGS.orderer.tls_cacerts; - let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); - let caroots = Buffer.from(data).toString(); + const channel = client.newChannel('testchannel-orderer-member3'); + const caRootsPath = ORGS.orderer.tls_cacerts; + const data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + const caroots = Buffer.from(data).toString(); let tlsInfo = null; e2eUtils.tlsEnroll(org) - .then((enrollment) => { - t.pass('Successfully retrieved TLS certificate'); - tlsInfo = enrollment; - client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); - return testUtil.getSubmitter(client, t, org); - }).then( - function() { - t.pass('Successfully enrolled user \'admin\''); - - channel.addOrderer( - new Orderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) - ); - - // send to orderer - return channel.sendTransaction(null); - }, - function(err) { - t.fail('Failed to enroll user \'admin\'. ' + err); - t.end(); - } - ).then( - function(status) { - if (status === 0) { - t.fail('Successfully submitted request, which is bad because the submission was missing data'); + .then((enrollment) => { + t.pass('Successfully retrieved TLS certificate'); + tlsInfo = enrollment; + client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); + return testUtil.getSubmitter(client, t, org); + }).then( + () => { + t.pass('Successfully enrolled user \'admin\''); + + channel.addOrderer( + new Orderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); + + // send to orderer + return channel.sendTransaction(null); + }, + (err) => { + t.fail('Failed to enroll user \'admin\'. ' + err); t.end(); - } else { - t.pass('Successfully tested invalid submission due to null data. Error code: ' + status); - - return channel.sendTransaction('some non-null but still bad data'); } - }, - function(err) { - t.pass('Failed to submit. Error code: ' + err); - t.end(); - } - ).then( - function(status) { - if (status === 0) { - t.fail('Successfully submitted request, which is bad because the submission was using bad data'); + ).then( + (status) => { + if (status === 0) { + t.fail('Successfully submitted request, which is bad because the submission was missing data'); + t.end(); + } else { + t.pass('Successfully tested invalid submission due to null data. Error code: ' + status); + + return channel.sendTransaction('some non-null but still bad data'); + } + }, + (err) => { + t.pass('Failed to submit. Error code: ' + err); t.end(); - } else { - t.pass('Successfully tested invalid submission due to bad data. Error code: ' + status); + } + ).then( + (status) => { + if (status === 0) { + t.fail('Successfully submitted request, which is bad because the submission was using bad data'); + t.end(); + } else { + t.pass('Successfully tested invalid submission due to bad data. Error code: ' + status); + t.end(); + } + }, + (err) => { + t.pass('Failed to submit. Error code: ' + err); t.end(); } - }, - function(err) { - t.pass('Failed to submit. Error code: ' + err); + ).catch((err) => { + t.pass('Failed request. ' + err); t.end(); - } - ).catch(function(err) { - t.pass('Failed request. ' + err); - t.end(); - }); + }); }); // @@ -171,68 +171,68 @@ test('\n\n** TEST ** orderer via member null data', function(t) { // with the orderer address set to a bad URL. Verify that an error is reported // when tying to send the request. // -test('\n\n** TEST ** orderer via member bad request', function(t) { +test('\n\n** TEST ** orderer via member bad request', (t) => { // // Create and configure the test channel // - var channel = client.newChannel('testchannel-orderer-member4'); + const channel = client.newChannel('testchannel-orderer-member4'); // Set bad orderer address here - var caRootsPath = ORGS.orderer.tls_cacerts; - let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); - let caroots = Buffer.from(data).toString(); + const caRootsPath = ORGS.orderer.tls_cacerts; + const data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + const caroots = Buffer.from(data).toString(); let tlsInfo = null; e2eUtils.tlsEnroll(org) - .then((enrollment) => { - t.pass('Successfully retrieved TLS certificate'); - tlsInfo = enrollment; - client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); - return testUtil.getSubmitter(client, t, org); - }).then( - function() { - t.pass('Successfully enrolled user \'admin\''); - - channel.addOrderer( - new Orderer( - 'grpcs://localhost:5199', - { - 'pem': caroots, - 'clientCert': tlsInfo.certificate, - 'clientKey': tlsInfo.key, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) - ); - - // send to orderer - var request = { - proposalResponses: 'blah', - proposal: 'blah' - }; - return channel.sendTransaction(request); - }, - function(err) { - t.fail('Failed to enroll user \'admin\'. ' + err); - t.end(); - } - ).then( - function(status) { - if (status === 0) { - t.fail('Successfully submitted request, which is bad because request is invalid'); - } else { - t.pass('Successfully tested invalid submission due to the invalid request. Error code: ' + status); + .then((enrollment) => { + t.pass('Successfully retrieved TLS certificate'); + tlsInfo = enrollment; + client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); + return testUtil.getSubmitter(client, t, org); + }).then( + () => { + t.pass('Successfully enrolled user \'admin\''); + + channel.addOrderer( + new Orderer( + 'grpcs://localhost:5199', + { + 'pem': caroots, + 'clientCert': tlsInfo.certificate, + 'clientKey': tlsInfo.key, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); + + // send to orderer + const request = { + proposalResponses: 'blah', + proposal: 'blah' + }; + return channel.sendTransaction(request); + }, + (err) => { + t.fail('Failed to enroll user \'admin\'. ' + err); + t.end(); } + ).then( + (status) => { + if (status === 0) { + t.fail('Successfully submitted request, which is bad because request is invalid'); + } else { + t.pass('Successfully tested invalid submission due to the invalid request. Error code: ' + status); + } + t.end(); + }, + (err) => { + t.comment('Failed to submit. Error: '); + t.pass('Error :' + err.stack ? err.stack : err); + t.end(); + } + ).catch((err) => { + t.comment('Failed to submit orderer request. Error: '); + t.pass('Error: ' + err); t.end(); - }, - function(err) { - t.comment('Failed to submit. Error: '); - t.pass('Error :' + err.stack ? err.stack : err); - t.end(); - } - ).catch(function(err) { - t.comment('Failed to submit orderer request. Error: '); - t.pass('Error: ' + err); - t.end(); - }); + }); }); diff --git a/test/integration/query.js b/test/integration/query.js index 143d55acba..dc0a43f509 100644 --- a/test/integration/query.js +++ b/test/integration/query.js @@ -13,51 +13,51 @@ 'use strict'; -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('query'); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('query'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var util = require('util'); -var e2eUtils = require('./e2e/e2eUtils.js'); -var fs = require('fs'); +const path = require('path'); +const util = require('util'); +const e2eUtils = require('./e2e/e2eUtils.js'); +const fs = require('fs'); -var testUtil = require('../unit/util.js'); -var Client = require('fabric-client'); -var Peer = require('fabric-client/lib/Peer.js'); -var Orderer = require('fabric-client/lib/Orderer.js'); -var BlockDecoder = require('fabric-client/lib/BlockDecoder.js'); +const testUtil = require('../unit/util.js'); +const Client = require('fabric-client'); +const Peer = require('fabric-client/lib/Peer.js'); +const Orderer = require('fabric-client/lib/Orderer.js'); +const BlockDecoder = require('fabric-client/lib/BlockDecoder.js'); -var client = new Client(); -var channel_id = testUtil.END2END.channel; -var channel = client.newChannel(channel_id); +const client = new Client(); +const channel_id = testUtil.END2END.channel; +const channel = client.newChannel(channel_id); -var org = 'org1'; -var orgName; +const org = 'org1'; +let orgName; -var e2e = testUtil.END2END; -var ORGS, peer0; +const e2e = testUtil.END2END; +let ORGS, peer0; let tx_id = null; -var data; +let data; test(' ---->>>>> Query channel working <<<<<-----', (t) => { Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); orgName = ORGS[org].name; - var caRootsPath = ORGS.orderer.tls_cacerts; + const caRootsPath = ORGS.orderer.tls_cacerts; data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); - let caroots = Buffer.from(data).toString(); + const caroots = Buffer.from(data).toString(); let tlsInfo = null; let bcInfo = null; let tx_block = null; utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); - var cryptoSuite = Client.newCryptoSuite(); + const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({ path: testUtil.storePathForOrg(orgName) })); client.setCryptoSuite(cryptoSuite); @@ -94,7 +94,7 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { 'ssl-target-name-override': ORGS[org].peer1['server-hostname'] }); data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS['org2'].peer1['tls_cacerts'])); - var peer1 = new Peer( + const peer1 = new Peer( ORGS['org2'].peer1.requests, { pem: Buffer.from(data).toString(), @@ -145,19 +145,19 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { 'test for header channel mspid in identity'); t.equals('Org1MSP', processed_transaction.transactionEnvelope.payload.data.actions['0'] .payload.action.endorsements['0'].endorser.Mspid, - 'test for endorser mspid in identity'); + 'test for endorser mspid in identity'); t.equals('Org2MSP', processed_transaction.transactionEnvelope.payload.data.actions['0'].header.creator.Mspid, 'test for creator mspid in identity'); t.equals(200, processed_transaction.transactionEnvelope.payload.data.actions['0'].payload.action .proposal_response_payload.extension.response.status, - 'test for transation status'); + 'test for transation status'); t.equals(0, processed_transaction.transactionEnvelope.payload.data.actions['0'] .payload.action.proposal_response_payload.extension.results.data_model, - 'test for data model value'); + 'test for data model value'); t.equals('a', processed_transaction.transactionEnvelope.payload.data.actions['0'] .payload.action.proposal_response_payload.extension.results.ns_rwset['0'] .rwset.writes['0'].key, - 'test for write set key value'); + 'test for write set key value'); const block_num = Number(processed_transaction.transactionEnvelope.payload.data.actions['0'] .payload.action.proposal_response_payload.extension.results.ns_rwset['0'] .rwset.reads[1].version.block_num.toString()); @@ -177,7 +177,7 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { logger.debug(' Channel queryInfo() returned block previousBlockHash=' + blockchainInfo.previousBlockHash); logger.debug(' Channel queryInfo() returned block currentBlockHash=' + blockchainInfo.currentBlockHash); bcInfo = blockchainInfo; - var block_hash = blockchainInfo.currentBlockHash; + const block_hash = blockchainInfo.currentBlockHash; // send query return channel.queryBlockByHash(block_hash, peer0); }).then((block) => { @@ -194,7 +194,7 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { if (!(binaryBlock instanceof Buffer)) { t.fail('queryBlock(skipDecode = true) did not return a binary block'); } else { - let block = BlockDecoder.decode(binaryBlock); + const block = BlockDecoder.decode(binaryBlock); if (block && block.header && block.header.number) { t.pass('queryBlock(skipDecode = true) returned a decodable binary block'); t.equals(block.header.number, '1', 'block number is correct'); @@ -203,14 +203,14 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { } } - var block_hash = bcInfo.currentBlockHash; + const block_hash = bcInfo.currentBlockHash; // query by hash skipping decoder return channel.queryBlockByHash(block_hash, peer0, null, true); }).then((binaryBlock) => { if (!(binaryBlock instanceof Buffer)) { t.fail('queryBlockByHash(skipDecode = true) did not return a binary block'); } else { - let block = BlockDecoder.decode(binaryBlock); + const block = BlockDecoder.decode(binaryBlock); if (block && block.header && block.header.number) { t.pass('queryBlockByHash(skipDecode = true) returned a decodable binary block'); t.equals(block.header.number, (bcInfo.height - 1).toString(), 'block number is correct'); @@ -225,7 +225,7 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { if (!(binaryBlock instanceof Buffer)) { t.fail('queryBlockByTxID(skipDecode = true) did not return a binary block'); } else { - let block = BlockDecoder.decode(binaryBlock); + const block = BlockDecoder.decode(binaryBlock); if (block && block.header && block.header.number) { t.pass('queryBlockByTxID(skipDecode = true) returned a decodable binary block'); t.equals(block.header.number, tx_block,'block number is correct'); @@ -240,7 +240,7 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { if (!(binaryTx instanceof Buffer)) { t.fail('queryTransaction(skipDecode = true) did not return a binary transaction'); } else { - let tx = BlockDecoder.decodeTransaction(binaryTx); + const tx = BlockDecoder.decodeTransaction(binaryTx); if (tx && tx.transactionEnvelope && tx.transactionEnvelope.payload && tx.transactionEnvelope.payload.header && tx.transactionEnvelope.payload.header.channel_header) { t.pass(util.format('queryTransaction(skipDecode = true) returned binary transaction which is decodable')); diff --git a/test/unit/config.js b/test/unit/config.js index 3ecd521a8b..c4a2a2f431 100644 --- a/test/unit/config.js +++ b/test/unit/config.js @@ -6,18 +6,18 @@ 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var Client = require('fabric-client'); +const Client = require('fabric-client'); // THIS TEST FILE MUST BE RUN FIRST so that node.js will not load the two clients in this order -test('\n\n ** config testing **\n\n', function (t) { +test('\n\n ** config testing **\n\n', (t) => { // this setting is in both configs, so we want to to find the fabric-client's version not the fabric-ca-client - let timeout = Client.getConfigSetting('request-timeout'); + const timeout = Client.getConfigSetting('request-timeout'); t.equal(timeout, 45000, 'the timeout is correct, which means the configs were loaded in the correct order'); t.pass('Got to the end'); t.end(); diff --git a/test/unit/constants.js b/test/unit/constants.js index 881f1a228f..3238a2f479 100644 --- a/test/unit/constants.js +++ b/test/unit/constants.js @@ -3,10 +3,10 @@ SPDX-License-Identifier: Apache-2.0 */ -var os = require('os'); -var path = require('path'); +const os = require('os'); +const path = require('path'); -var tempdir = path.join(os.tmpdir(), 'hfc'); +const tempdir = path.join(os.tmpdir(), 'hfc'); module.exports = { tempdir: tempdir diff --git a/test/unit/couchdb-key-value-store.js b/test/unit/couchdb-key-value-store.js index 82a8d4039c..6d6c77fc65 100644 --- a/test/unit/couchdb-key-value-store.js +++ b/test/unit/couchdb-key-value-store.js @@ -6,12 +6,12 @@ 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); -var CouchdbMock = require('mock-couch'); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); +const CouchdbMock = require('mock-couch'); -var CDBKVS = require('fabric-client/lib/impl/CouchDBKeyValueStore.js'); +const CDBKVS = require('fabric-client/lib/impl/CouchDBKeyValueStore.js'); test('\n\n** CouchDBKeyValueStore tests', (t) => { t.throws( @@ -30,52 +30,52 @@ test('\n\n** CouchDBKeyValueStore tests', (t) => { 'Error checking in the constructor: opts object missing required "url"' ); - var store; + let store; new CDBKVS({url: 'http://localhost:9999'}) - .then(() => { - t.fail('Should not have been able to successfully construct a store from an invalid URL'); - throw new Error('Failed'); - },(err) => { - if (err.message && err.message.indexOf('ECONNREFUSED') > 0) { - t.pass('Successfully rejected the construction request due to invalid URL'); - } else { - t.fail('Store construction failed for unknown reason: ' + err.stack ? err.stack : err); + .then(() => { + t.fail('Should not have been able to successfully construct a store from an invalid URL'); throw new Error('Failed'); - } + },(err) => { + if (err.message && err.message.indexOf('ECONNREFUSED') > 0) { + t.pass('Successfully rejected the construction request due to invalid URL'); + } else { + t.fail('Store construction failed for unknown reason: ' + err.stack ? err.stack : err); + throw new Error('Failed'); + } - var couchdb = CouchdbMock.createServer(); - couchdb.listen(5985); + const couchdb = CouchdbMock.createServer(); + couchdb.listen(5985); - // override t.end function so it'll always disconnect the event hub - t.end = ((context, mockdb, f) => { - return function() { - if (mockdb) { - t.comment('Disconnecting the mock couchdb server'); - mockdb.close(); - } + // override t.end function so it'll always disconnect the event hub + t.end = ((context, mockdb, f) => { + return function() { + if (mockdb) { + t.comment('Disconnecting the mock couchdb server'); + mockdb.close(); + } - f.apply(context, arguments); - }; - })(t, couchdb, t.end); + f.apply(context, arguments); + }; + })(t, couchdb, t.end); - return new CDBKVS({url: 'http://localhost:5985'}); - }).then((st) => { - store = st; - t.pass('Successfully connected the key value store to couchdb at localhost:5985'); + return new CDBKVS({url: 'http://localhost:5985'}); + }).then((st) => { + store = st; + t.pass('Successfully connected the key value store to couchdb at localhost:5985'); - t.notEqual(store._database, undefined, 'Check "_database" value of the constructed store object'); + t.notEqual(store._database, undefined, 'Check "_database" value of the constructed store object'); - return store.setValue('someKey', 'someValue'); - }).then((value) => { - t.equal(value, 'someValue', 'Check result of setValue()'); + return store.setValue('someKey', 'someValue'); + }).then((value) => { + t.equal(value, 'someValue', 'Check result of setValue()'); - return store.getValue('someKey'); - }).then((value) => { - t.equal(value, 'someValue', 'Check result of getValue()'); - t.end(); - }).catch((err) => { - t.fail(err.stack ? err.stack : err); - t.end(); - }); + return store.getValue('someKey'); + }).then((value) => { + t.equal(value, 'someValue', 'Check result of getValue()'); + t.end(); + }).catch((err) => { + t.fail(err.stack ? err.stack : err); + t.end(); + }); }); diff --git a/test/unit/crypto-key-store.js b/test/unit/crypto-key-store.js index 9be496133e..7339f8d08c 100644 --- a/test/unit/crypto-key-store.js +++ b/test/unit/crypto-key-store.js @@ -9,31 +9,31 @@ if (global && global.hfc) global.hfc.config = undefined; require('nconf').reset(); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); - -var util = require('util'); -var testutil = require('./util.js'); -var utils = require('fabric-client/lib/utils.js'); -var fs = require('fs-extra'); -var path = require('path'); -var os = require('os'); -var jsrsa = require('jsrsasign'); -var KEYUTIL = jsrsa.KEYUTIL; -var CouchdbMock = require('mock-couch'); -var nano = require('nano'); - -var ecdsaKey = require('fabric-client/lib/impl/ecdsa/key.js'); -var CKS = require('fabric-client/lib/impl/CryptoKeyStore.js'); -var CouchDBKeyValueStore = require('fabric-client/lib/impl/CouchDBKeyValueStore.js'); - -var TEST_KEY_PRIVATE_PEM = '-----BEGIN PRIVATE KEY-----' + +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); + +const util = require('util'); +const testutil = require('./util.js'); +const utils = require('fabric-client/lib/utils.js'); +const fs = require('fs-extra'); +const path = require('path'); +const os = require('os'); +const jsrsa = require('jsrsasign'); +const KEYUTIL = jsrsa.KEYUTIL; +const CouchdbMock = require('mock-couch'); +const nano = require('nano'); + +const ecdsaKey = require('fabric-client/lib/impl/ecdsa/key.js'); +const CKS = require('fabric-client/lib/impl/CryptoKeyStore.js'); +const CouchDBKeyValueStore = require('fabric-client/lib/impl/CouchDBKeyValueStore.js'); + +const TEST_KEY_PRIVATE_PEM = '-----BEGIN PRIVATE KEY-----' + 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgZYMvf3w5VkzzsTQY' + 'I8Z8IXuGFZmmfjIX2YSScqCvAkihRANCAAS6BhFgW/q0PzrkwT5RlWTt41VgXLgu' + 'Pv6QKvGsW7SqK6TkcCfxsWoSjy6/r1SzzTMni3J8iQRoJ3roPmoxPLK4' + '-----END PRIVATE KEY-----'; -var TEST_KEY_PRIVATE_CERT_PEM = '-----BEGIN CERTIFICATE-----' + +const TEST_KEY_PRIVATE_CERT_PEM = '-----BEGIN CERTIFICATE-----' + 'MIICEDCCAbagAwIBAgIUXoY6X7jIpHAAgL267xHEpVr6NSgwCgYIKoZIzj0EAwIw' + 'fzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh' + 'biBGcmFuY2lzY28xHzAdBgNVBAoTFkludGVybmV0IFdpZGdldHMsIEluYy4xDDAK' + @@ -48,18 +48,18 @@ var TEST_KEY_PRIVATE_CERT_PEM = '-----BEGIN CERTIFICATE-----' + 'BAHpeA==' + '-----END CERTIFICATE-----'; -var dbname = 'test_keystore'; -var dbclient = nano('http://localhost:5985'); +const dbname = 'test_keystore'; +const dbclient = nano('http://localhost:5985'); -var f1 = KEYUTIL.getKey(TEST_KEY_PRIVATE_PEM); -var testPrivKey = new ecdsaKey(f1); -var f2 = KEYUTIL.getKey(TEST_KEY_PRIVATE_CERT_PEM); -var testPubKey = new ecdsaKey(f2); +const f1 = KEYUTIL.getKey(TEST_KEY_PRIVATE_PEM); +const testPrivKey = new ecdsaKey(f1); +const f2 = KEYUTIL.getKey(TEST_KEY_PRIVATE_CERT_PEM); +const testPubKey = new ecdsaKey(f2); -test('\n\n** CryptoKeyStore tests **\n\n', function(t) { +test('\n\n** CryptoKeyStore tests **\n\n', (t) => { testutil.resetDefaults(); - var keystorePath = path.join(testutil.getTempDir(), 'crypto-key-store'); + const keystorePath = path.join(testutil.getTempDir(), 'crypto-key-store'); t.throws( () => { @@ -77,50 +77,50 @@ test('\n\n** CryptoKeyStore tests **\n\n', function(t) { 'Test invalid constructor calls: missing "path" property in the "options" parameter' ); - var store; + let store; CKS({path: keystorePath}) - .then((st) => { - store = st; - return store.putKey(testPrivKey); - }).then(() => { - t.pass('Successfully saved private key in store'); - - t.equal(fs.existsSync(path.join(keystorePath, testPrivKey.getSKI() + '-priv')), true, - 'Check that the private key has been saved with the proper -priv index'); - - return store.getKey(testPrivKey.getSKI()); - }).then((recoveredKey) => { - t.notEqual(recoveredKey, null, 'Successfully read private key from store using SKI'); - t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); - - return store.putKey(testPubKey); - }).then(() => { - t.equal(fs.existsSync(path.join(keystorePath, testPrivKey.getSKI() + '-pub')), true, - 'Check that the public key has been saved with the proper -pub index'); - - return store.getKey(testPubKey.getSKI()); - }).then((recoveredKey) => { - t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); - t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); - - // delete the private key entry and test if getKey() would return the public key - fs.unlinkSync(path.join(keystorePath, testPrivKey.getSKI() + '-priv')); - return store.getKey(testPubKey.getSKI()); - }).then((recoveredKey) => { - t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); - t.equal(recoveredKey.isPrivate(), false, 'Test if the recovered key is a public key'); - t.end(); - }).catch((err) => { - t.fail(err.stack ? err.stack : err); - t.end(); - }); + .then((st) => { + store = st; + return store.putKey(testPrivKey); + }).then(() => { + t.pass('Successfully saved private key in store'); + + t.equal(fs.existsSync(path.join(keystorePath, testPrivKey.getSKI() + '-priv')), true, + 'Check that the private key has been saved with the proper -priv index'); + + return store.getKey(testPrivKey.getSKI()); + }).then((recoveredKey) => { + t.notEqual(recoveredKey, null, 'Successfully read private key from store using SKI'); + t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); + + return store.putKey(testPubKey); + }).then(() => { + t.equal(fs.existsSync(path.join(keystorePath, testPrivKey.getSKI() + '-pub')), true, + 'Check that the public key has been saved with the proper -pub index'); + + return store.getKey(testPubKey.getSKI()); + }).then((recoveredKey) => { + t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); + t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); + + // delete the private key entry and test if getKey() would return the public key + fs.unlinkSync(path.join(keystorePath, testPrivKey.getSKI() + '-priv')); + return store.getKey(testPubKey.getSKI()); + }).then((recoveredKey) => { + t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); + t.equal(recoveredKey.isPrivate(), false, 'Test if the recovered key is a public key'); + t.end(); + }).catch((err) => { + t.fail(err.stack ? err.stack : err); + t.end(); + }); }); -test('\n\n** CryptoKeyStore tests - couchdb based store tests - use configSetting **\n\n', function(t) { +test('\n\n** CryptoKeyStore tests - couchdb based store tests - use configSetting **\n\n', (t) => { utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/CouchDBKeyValueStore.js'); - var couchdb = CouchdbMock.createServer(); + const couchdb = CouchdbMock.createServer(); couchdb.listen(5985); // override t.end function so it'll always disconnect the event hub @@ -136,18 +136,18 @@ test('\n\n** CryptoKeyStore tests - couchdb based store tests - use configSettin })(t, couchdb, t.end); CKS({name: dbname, url: 'http://localhost:5985'}) - .then((store) => { - return testKeyStore(store, t); - }).catch((err) => { - t.fail(err.stack ? err.stack : err); - t.end(); - }).then(() => { - t.end(); - }); + .then((store) => { + return testKeyStore(store, t); + }).catch((err) => { + t.fail(err.stack ? err.stack : err); + t.end(); + }).then(() => { + t.end(); + }); }); -test('\n\n** CryptoKeyStore tests - couchdb based store tests - use constructor argument **\n\n', function(t) { - var couchdb = CouchdbMock.createServer(); +test('\n\n** CryptoKeyStore tests - couchdb based store tests - use constructor argument **\n\n', (t) => { + const couchdb = CouchdbMock.createServer(); couchdb.listen(5985); // override t.end function so it'll always disconnect the event hub @@ -163,82 +163,82 @@ test('\n\n** CryptoKeyStore tests - couchdb based store tests - use constructor })(t, couchdb, t.end); CKS(CouchDBKeyValueStore, {name: dbname, url: 'http://localhost:5985'}) - .then((store) => { - return testKeyStore(store, t); - }).catch((err) => { - t.fail(err.stack ? err.stack : err); - t.end(); - }).then(() => { - t.end(); - }); + .then((store) => { + return testKeyStore(store, t); + }).catch((err) => { + t.fail(err.stack ? err.stack : err); + t.end(); + }).then(() => { + t.end(); + }); }); function testKeyStore(store, t) { - var docRev; + let docRev; return store.putKey(testPrivKey) - .then(() => { - t.pass('Successfully saved private key in store based on couchdb'); - - return new Promise((resolve) => { - dbclient.use(dbname).get(testPrivKey.getSKI() + '-priv', function(err, body) { - if (!err) { - t.pass('Successfully verified private key persisted in couchdb'); - docRev = body._rev; - return resolve(store.getKey(testPrivKey.getSKI())); - } else { - t.fail('Failed to persist private key in couchdb. ' + err.stack ? err.stack : err); - t.end(); - } + .then(() => { + t.pass('Successfully saved private key in store based on couchdb'); + + return new Promise((resolve) => { + dbclient.use(dbname).get(testPrivKey.getSKI() + '-priv', (err, body) => { + if (!err) { + t.pass('Successfully verified private key persisted in couchdb'); + docRev = body._rev; + return resolve(store.getKey(testPrivKey.getSKI())); + } else { + t.fail('Failed to persist private key in couchdb. ' + err.stack ? err.stack : err); + t.end(); + } + }); }); - }); - }).then((recoveredKey) => { - t.notEqual(recoveredKey, null, 'Successfully read private key from store using SKI'); - t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); - - return store.putKey(testPubKey); - }).then(() => { - return new Promise((resolve) => { - dbclient.use(dbname).get(testPrivKey.getSKI() + '-pub', function(err) { - if (!err) { - t.pass('Successfully verified public key persisted in couchdb'); - return resolve(store.getKey(testPubKey.getSKI())); - } else { - t.fail('Failed to persist public key in couchdb. ' + err.stack ? err.stack : err); - t.end(); - } + }).then((recoveredKey) => { + t.notEqual(recoveredKey, null, 'Successfully read private key from store using SKI'); + t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); + + return store.putKey(testPubKey); + }).then(() => { + return new Promise((resolve) => { + dbclient.use(dbname).get(testPrivKey.getSKI() + '-pub', (err) => { + if (!err) { + t.pass('Successfully verified public key persisted in couchdb'); + return resolve(store.getKey(testPubKey.getSKI())); + } else { + t.fail('Failed to persist public key in couchdb. ' + err.stack ? err.stack : err); + t.end(); + } + }); }); - }); - }).then((recoveredKey) => { - t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); - t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); - - // delete the private key entry and test if getKey() would return the public key - return new Promise((resolve) => { - dbclient.use(dbname).destroy(testPrivKey.getSKI() + '-priv', docRev, function(err) { - if (!err) { - return resolve(store.getKey(testPubKey.getSKI())); - } else { - t.fail('Failed to delete private key in couchdb. ' + err.stack ? err.stack : err); - t.end(); - } + }).then((recoveredKey) => { + t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); + t.equal(recoveredKey.isPrivate(), true, 'Test if the recovered key is a private key'); + + // delete the private key entry and test if getKey() would return the public key + return new Promise((resolve) => { + dbclient.use(dbname).destroy(testPrivKey.getSKI() + '-priv', docRev, (err) => { + if (!err) { + return resolve(store.getKey(testPubKey.getSKI())); + } else { + t.fail('Failed to delete private key in couchdb. ' + err.stack ? err.stack : err); + t.end(); + } + }); }); + }).then((recoveredKey) => { + t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); + t.equal(recoveredKey.isPrivate(), false, 'Test if the recovered key is a public key'); }); - }).then((recoveredKey) => { - t.notEqual(recoveredKey, null, 'Successfully read public key from store using SKI'); - t.equal(recoveredKey.isPrivate(), false, 'Test if the recovered key is a public key'); - }); } -test('\n\n** CryptoKeyStore tests - newCryptoKeyStore tests **\n\n', function(t) { +test('\n\n** CryptoKeyStore tests - newCryptoKeyStore tests **\n\n', (t) => { utils.setConfigSetting('key-value-store', 'fabric-ca-client/lib/impl/FileKeyValueStore.js');//force for 'gulp test' - let keyValStorePath = 'tmp/keyValStore1'; - let config = { path: keyValStorePath }; + const keyValStorePath = 'tmp/keyValStore1'; + const config = { path: keyValStorePath }; let cs = utils.newCryptoKeyStore(config); t.equal(cs._storeConfig.opts, config, util.format('Returned instance should have store config opts of %j', config)); t.equal(typeof cs._storeConfig.superClass, 'function', 'Returned instance should have store config superClass'); - let defaultKVSPath = path.join(os.homedir(), '.hfc-key-store'); + const defaultKVSPath = path.join(os.homedir(), '.hfc-key-store'); cs = utils.newCryptoKeyStore(); t.equal(cs._storeConfig.opts.path, defaultKVSPath, util.format('Returned instance should have store config opts.path of %s', defaultKVSPath)); t.equal(typeof cs._storeConfig.superClass, 'function', 'Returned instance should have store config superClass'); @@ -256,10 +256,10 @@ test('\n\n** CryptoKeyStore tests - newCryptoKeyStore tests **\n\n', function(t) t.end(); }); -test('\n\n** CryptoKeyStore tests - getKey error tests **\n\n', function (t) { +test('\n\n** CryptoKeyStore tests - getKey error tests **\n\n', (t) => { // override t.end function so it'll always clear the config settings testutil.resetDefaults(); - var cryptoSuite = utils.newCryptoSuite(); + const cryptoSuite = utils.newCryptoSuite(); cryptoSuite.getKey('blah').catch(err => { t.ok(err.toString().includes('getKey requires CryptoKeyStore to be set.'), 'Test missing cryptoKeyStore: cryptoSuite.getKey'); diff --git a/test/unit/file-key-value-store.js b/test/unit/file-key-value-store.js index dcc6322f3b..976b2a56d7 100644 --- a/test/unit/file-key-value-store.js +++ b/test/unit/file-key-value-store.js @@ -6,23 +6,23 @@ 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var path = require('path'); -var testUtil = require('./util.js'); -var fs = require('fs-extra'); -var utils = require('fabric-client/lib/utils.js'); +const path = require('path'); +const testUtil = require('./util.js'); +const fs = require('fs-extra'); +const utils = require('fabric-client/lib/utils.js'); -var FileKeyValueStore = require('fabric-client/lib/impl/FileKeyValueStore.js'); +const FileKeyValueStore = require('fabric-client/lib/impl/FileKeyValueStore.js'); -var keyValStorePath = path.join(testUtil.getTempDir(), 'kvsTemp'); -var testKey = 'keyValFileStoreName'; -var testValue = 'secretKeyValue'; -var store1 = ''; +const keyValStorePath = path.join(testUtil.getTempDir(), 'kvsTemp'); +const testKey = 'keyValFileStoreName'; +const testValue = 'secretKeyValue'; +let store1 = ''; -test('\n\n ** FileKeyValueStore - read and write test **\n\n', function (t) { +test('\n\n ** FileKeyValueStore - read and write test **\n\n', (t) => { testUtil.resetDefaults(); // clean up @@ -32,96 +32,96 @@ test('\n\n ** FileKeyValueStore - read and write test **\n\n', function (t) { utils.newKeyValueStore({ path: keyValStorePath }) - .then( - function (store) { - if (testUtil.existsSync(keyValStorePath)) { - t.pass('FileKeyValueStore read and write test: Successfully created new directory for testValueStore'); - } else { - t.fail('FileKeyValueStore read and write test: failed to create new directory for testValueStore'); - t.end(); + .then( + (store) => { + if (testUtil.existsSync(keyValStorePath)) { + t.pass('FileKeyValueStore read and write test: Successfully created new directory for testValueStore'); + } else { + t.fail('FileKeyValueStore read and write test: failed to create new directory for testValueStore'); + t.end(); + } + store1 = store; + return store.setValue(testKey, testValue); } - store1 = store; - return store.setValue(testKey, testValue); - } - ).then( - function (result) { - if (result == testValue) { - t.pass('FileKeyValueStore read and write test: Successfully set value'); - } else { - t.fail('FileKeyValueStore read and write test: set value '+result+ 'does not match testValue '+testValue); + ).then( + (result) => { + if (result == testValue) { + t.pass('FileKeyValueStore read and write test: Successfully set value'); + } else { + t.fail('FileKeyValueStore read and write test: set value '+result+ 'does not match testValue '+testValue); + t.end(); + } + if (testUtil.existsSync(path.join(keyValStorePath, testKey))) { + t.pass('FileKeyValueStore read and write test: Verified the file for key ' + testKey + ' does exist'); + + return store1.getValue(testKey); + } else { + t.fail('FileKeyValueStore read and write test: Failed to create file for key ' + testKey); + t.end(); + } + }, + (reason) => { + t.fail('FileKeyValueStore read and write test: Failed to set value, reason: ' + reason); t.end(); } - if (testUtil.existsSync(path.join(keyValStorePath, testKey))) { - t.pass('FileKeyValueStore read and write test: Verified the file for key ' + testKey + ' does exist'); + ).then( + // Log the fulfillment value + (val) => { + if (val != testValue) + t.fail('FileKeyValueStore read and write test: get value ' + val + ' does not equal testValue of ' + testValue); + else + t.pass('FileKeyValueStore read and write test: Successfully retrieved value'); + // now test getValue() when the underlying directory get deleted + fs.removeSync(keyValStorePath); return store1.getValue(testKey); - } else { - t.fail('FileKeyValueStore read and write test: Failed to create file for key ' + testKey); + }, + // Log the rejection reason + (reason) => { + t.fail('FileKeyValueStore read and write test: Failed getValue, reason: ' + reason); t.end(); } - }, - function (reason) { - t.fail('FileKeyValueStore read and write test: Failed to set value, reason: ' + reason); - t.end(); - } - ).then( + ).then( // Log the fulfillment value - function (val) { - if (val != testValue) - t.fail('FileKeyValueStore read and write test: get value ' + val + ' does not equal testValue of ' + testValue); - else - t.pass('FileKeyValueStore read and write test: Successfully retrieved value'); + (val) => { + if (val === null) { + t.pass('FileKeyValueStore error check tests: Delete store & getValue test. getValue() returns null as expected'); + } else { + t.fail('FileKeyValueStore error check tests: Delete store & getValue test. getValue() should not have returned value: ' + val); + } - // now test getValue() when the underlying directory get deleted - fs.removeSync(keyValStorePath); - return store1.getValue(testKey); - }, - // Log the rejection reason - function (reason) { - t.fail('FileKeyValueStore read and write test: Failed getValue, reason: ' + reason); - t.end(); - } - ).then( - // Log the fulfillment value - function (val) { - if (val === null) { - t.pass('FileKeyValueStore error check tests: Delete store & getValue test. getValue() returns null as expected'); - } else { - t.fail('FileKeyValueStore error check tests: Delete store & getValue test. getValue() should not have returned value: ' + val); + return new FileKeyValueStore({ path: keyValStorePath }); + }, + (reason) => { + t.fail('FileKeyValueStore error check tests: Delete store & getValue test. getValue caught unexpected error: ' + reason); } - - return new FileKeyValueStore({ path: keyValStorePath }); - }, - function (reason) { - t.fail('FileKeyValueStore error check tests: Delete store & getValue test. getValue caught unexpected error: ' + reason); - } - ) - .then( - function (store) { + ) + .then( + (store) => { // now test setValue() when the underlying directory get deleted - fs.removeSync(keyValStorePath); - return store.setValue(testKey, testValue); - }) - .then( - function () { - t.fail('FileKeyValueStore error check tests: Delete store & setValue test. setValue() should have failed.'); - t.end(); - }, - function (reason) { - t.pass('FileKeyValueStore error check tests: Delete store & setValue test. setValue() failed as expected: ' + reason); - t.end(); - }) - .catch( - function (err) { - t.fail('Failed with unexpected error: ' + err.stack ? err.stack : err); - t.end(); - }); + fs.removeSync(keyValStorePath); + return store.setValue(testKey, testValue); + }) + .then( + () => { + t.fail('FileKeyValueStore error check tests: Delete store & setValue test. setValue() should have failed.'); + t.end(); + }, + (reason) => { + t.pass('FileKeyValueStore error check tests: Delete store & setValue test. setValue() failed as expected: ' + reason); + t.end(); + }) + .catch( + (err) => { + t.fail('Failed with unexpected error: ' + err.stack ? err.stack : err); + t.end(); + }); }); -test('\n\n** FileKeyValueStore error check tests **\n\n', function (t) { +test('\n\n** FileKeyValueStore error check tests **\n\n', (t) => { t.throws( - function () { + () => { new FileKeyValueStore(); }, /^Error: Must provide the path/, @@ -130,7 +130,7 @@ test('\n\n** FileKeyValueStore error check tests **\n\n', function (t) { ); t.throws( - function () { + () => { new FileKeyValueStore({ dir: keyValStorePath }); }, /^Error: Must provide the path/, diff --git a/test/unit/identity.js b/test/unit/identity.js index 5807267b1e..c215b90a71 100644 --- a/test/unit/identity.js +++ b/test/unit/identity.js @@ -165,23 +165,23 @@ test('\n\n ** Identity class tests **\n\n', (t) => { 'Checking required input parameters' ); - let cryptoUtils = utils.newCryptoSuite(); + const cryptoUtils = utils.newCryptoSuite(); cryptoUtils.setCryptoKeyStore(utils.newCryptoKeyStore()); // test identity serialization and deserialization - let mspImpl = new MSP({ + const mspImpl = new MSP({ rootCerts: [], admins: [], id: 'testMSP', cryptoSuite: cryptoUtils }); - let pubKey = cryptoUtils.importKey(TEST_CERT_PEM, { algorithm: api.CryptoAlgorithms.X509Certificate }); - let identity = new Identity(TEST_CERT_PEM, pubKey, mspImpl.getId(), cryptoUtils); + const pubKey = cryptoUtils.importKey(TEST_CERT_PEM, { algorithm: api.CryptoAlgorithms.X509Certificate }); + const identity = new Identity(TEST_CERT_PEM, pubKey, mspImpl.getId(), cryptoUtils); - let serializedID = identity.serialize(); + const serializedID = identity.serialize(); // deserializeIdentity should work both ways ... with promise and without - let identity_g = mspImpl.deserializeIdentity(serializedID, false); + const identity_g = mspImpl.deserializeIdentity(serializedID, false); t.equals(identity_g.getMSPId(),'testMSP', 'deserializeIdentity call without promise'); mspImpl.deserializeIdentity(serializedID) @@ -191,14 +191,14 @@ test('\n\n ** Identity class tests **\n\n', (t) => { t.equal(dsID._publicKey._key.pubKeyHex, '0452a75e1ee105da7ab3d389fda69d8a04f5cf65b305b49cec7cdbdeb91a585cf87bef5a96aa9683d96bbabfe60d8cc6f5db9d0bc8c58d56bb28887ed81c6005ac', 'Identity class function tests: deserialized public key ecparam check'); // manually construct a key based on the saved privKeyHex and pubKeyHex - let f = KEYUTIL.getKey(TEST_KEY_PRIVATE_PEM); - let testKey = new ecdsaKey(f); - let pubKey = testKey.getPublicKey(); + const f = KEYUTIL.getKey(TEST_KEY_PRIVATE_PEM); + const testKey = new ecdsaKey(f); + const pubKey = testKey.getPublicKey(); - let signer = new Signer(cryptoUtils, testKey); + const signer = new Signer(cryptoUtils, testKey); t.equal(signer.getPublicKey().isPrivate(), false, 'Test Signer class getPublicKey() method'); - let signingID = new SigningIdentity(TEST_KEY_PRIVATE_CERT_PEM, pubKey, mspImpl.getId(), cryptoUtils, signer); + const signingID = new SigningIdentity(TEST_KEY_PRIVATE_CERT_PEM, pubKey, mspImpl.getId(), cryptoUtils, signer); t.throws( () => { @@ -208,7 +208,7 @@ test('\n\n ** Identity class tests **\n\n', (t) => { 'Test invalid hashFunction parameter for the sign() method' ); - let sig = signingID.sign(TEST_MSG); + const sig = signingID.sign(TEST_MSG); t.equal(cryptoUtils.verify(pubKey, sig, TEST_MSG), true, 'Test SigningIdentity sign() method'); t.equal(signingID.verify(TEST_MSG, sig), true, 'Test Identity verify() method'); t.end(); diff --git a/test/unit/logger.js b/test/unit/logger.js index c721aeea82..d7650b913f 100644 --- a/test/unit/logger.js +++ b/test/unit/logger.js @@ -6,30 +6,30 @@ 'use strict'; -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var hfc = require('fabric-client'); -var testutil = require('./util.js'); -var utils = require('fabric-client/lib/utils.js'); +const hfc = require('fabric-client'); +const testutil = require('./util.js'); +const utils = require('fabric-client/lib/utils.js'); -var bunyan = require('bunyan'); -var log4js = require('log4js'); -var intercept = require('intercept-stdout'); -var fs = require('fs-extra'); -var util = require('util'); -var path = require('path'); +const bunyan = require('bunyan'); +const log4js = require('log4js'); +const intercept = require('intercept-stdout'); +const fs = require('fs-extra'); +const util = require('util'); +const path = require('path'); // Logger tests ///////// function testLogger(t, ignoreLevels) { - var output = ''; + let output = ''; - let unhook = intercept(function (txt) { + const unhook = intercept((txt) => { output += txt; }); - let log = utils.getLogger('testlogger'); + const log = utils.getLogger('testlogger'); log.error('Test logger - error'); log.warn('Test logger - warn'); log.info('Test logger - info'); @@ -50,7 +50,7 @@ function testLogger(t, ignoreLevels) { } } -test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { +test('\n\n ** Logging utility tests - built-in logger **\n\n', (t) => { if (process.env.HFC_LOGGING) { delete process.env['HFC_LOGGING']; } @@ -62,7 +62,7 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { testutil.resetDefaults(); // test 2: custom logging levels for console logging - var output = ''; + let output = ''; // setup the environment *ignore this* process.env.HFC_LOGGING = "{'debug': 'console'}"; // eslint-disable-line quotes // internal call. clearing the cached config. @@ -70,11 +70,11 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { // internal call. clearing the cached logger. global.hfc.logger = undefined; try { - let unhook = intercept(function (txt) { + const unhook = intercept((txt) => { output += txt; }); - let logger = utils.getLogger('testlogger'); + const logger = utils.getLogger('testlogger'); unhook(); @@ -96,7 +96,7 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { // internal call. clearing the cached logger. global.hfc.logger = undefined; - let unhook = intercept(function (txt) { + let unhook = intercept((txt) => { output += txt; }); @@ -125,7 +125,7 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { // internal call. clearing the cached logger. global.hfc.logger = undefined; - unhook = intercept(function (txt) { + unhook = intercept((txt) => { output += txt; }); @@ -147,11 +147,11 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { } - let prepareEmptyFile = function (logPath) { + const prepareEmptyFile = function (logPath) { try { fs.ensureFileSync(logPath); - let stats = fs.statSync(logPath); + const stats = fs.statSync(logPath); if (stats.isFile()) { fs.truncateSync(logPath); @@ -162,22 +162,22 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { } }; - let debugPath = path.join(testutil.getTempDir(), 'hfc-log/debug.log'); - let errorPath = path.join(testutil.getTempDir(), 'hfc-log/error.log'); + const debugPath = path.join(testutil.getTempDir(), 'hfc-log/debug.log'); + const errorPath = path.join(testutil.getTempDir(), 'hfc-log/error.log'); prepareEmptyFile(debugPath); prepareEmptyFile(errorPath); hfc.setConfigSetting('hfc-logging', util.format('{"debug": "%s", "error": "%s"}', debugPath, errorPath)); // internal call. clearing the cached logger. global.hfc.logger = undefined; - var log1 = utils.getLogger('testlogger'); + const log1 = utils.getLogger('testlogger'); log1.error('Test logger - error'); log1.warn('Test logger - warn'); log1.info('Test logger - info'); log1.debug('Test logger - debug'); - setTimeout(function () { - var data = fs.readFileSync(debugPath); + setTimeout(() => { + let data = fs.readFileSync(debugPath); if (data.indexOf('Test logger - error') > 0 && data.indexOf('Test logger - warn') > 0 && @@ -206,16 +206,16 @@ test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { }, 1000); }); -test('\n\n ** Logging utility tests - test setting an external logger based on bunyan **\n\n', function (t) { - var logger = bunyan.createLogger({ name: 'bunyanLogger' }); +test('\n\n ** Logging utility tests - test setting an external logger based on bunyan **\n\n', (t) => { + const logger = bunyan.createLogger({ name: 'bunyanLogger' }); hfc.setLogger(logger); testLogger(t); t.end(); }); -test('\n\n ** Logging utility tests - test setting an external logger based on log4js **\n\n', function (t) { - var logger = log4js.getLogger(); +test('\n\n ** Logging utility tests - test setting an external logger based on log4js **\n\n', (t) => { + const logger = log4js.getLogger(); logger.level = 'info'; // Set level in order to output logs because by default it is OFF hfc.setLogger(logger); @@ -223,9 +223,9 @@ test('\n\n ** Logging utility tests - test setting an external logger based on l t.end(); }); -test('\n\n ** Logging utility tests - test setting an invalid external logger **\n\n', function (t) { +test('\n\n ** Logging utility tests - test setting an invalid external logger **\n\n', (t) => { // construct an invalid logger - var logger = { + const logger = { inf: function () { t.comment('info'); }, }; @@ -234,7 +234,7 @@ test('\n\n ** Logging utility tests - test setting an invalid external logger ** t.fail('Should not have allowed an invalid logger to be set'); t.end(); } catch (err) { - var er1 = err.toString(); + const er1 = err.toString(); if (er1.indexOf('debug()') > 0 && er1.indexOf('info()') > 0 && er1.indexOf('warn()') > 0 && diff --git a/test/unit/network-config.js b/test/unit/network-config.js index 99e306fbd2..4172a77f27 100644 --- a/test/unit/network-config.js +++ b/test/unit/network-config.js @@ -32,11 +32,11 @@ test('\n\n ** configuration testing **\n\n', (t) => { t.doesNotThrow( () => { - let client = new Client(); + const client = new Client(); client.setTlsClientCertAndKey('client cert', 'client key'); t.equals(client._tls_mutual.clientCert, 'client cert', 'Checking that client cert was set'); t.equals(client._tls_mutual.clientKey, 'client key', 'Checking that client key was set'); - let myOpts = {}; + const myOpts = {}; client.addTlsClientCertAndKey(myOpts); t.equals(myOpts.clientCert, 'client cert', 'Checking that client cert was added'); t.equals(myOpts.clientKey, 'client key', 'Checking that client key was added'); diff --git a/test/unit/packager.js b/test/unit/packager.js index 9d7f28e1b7..d959542265 100644 --- a/test/unit/packager.js +++ b/test/unit/packager.js @@ -117,15 +117,15 @@ test('\n\n** Golang Packager tests **\n\n', (t) => { if (err) t.fail('Failed to extract generated chaincode package. ' + err); - let checkPath = path.join(destDir, 'src', 'github.com', 'example_cc', 'example_cc.go'); + const checkPath = path.join(destDir, 'src', 'github.com', 'example_cc', 'example_cc.go'); t.equal(fs.existsSync(checkPath), true, 'The tar.gz file produced by Packager.package() has the "src/github.com/example_cc/example_cc.go" file'); t.end(); }); return Packager.package(testutil.CHAINCODE_PATH,'', false, testutil.METADATA_PATH); }).then((data) => { - let tmpFile = path.join(testutil.getTempDir(), 'test-deploy-copy.tar.gz'); - let destDir = path.join(testutil.getTempDir(), 'test-deploy-copy-tar-gz'); + const tmpFile = path.join(testutil.getTempDir(), 'test-deploy-copy.tar.gz'); + const destDir = path.join(testutil.getTempDir(), 'test-deploy-copy-tar-gz'); fs.writeFileSync(tmpFile, data); fs.removeSync(destDir); targz.decompress({ diff --git a/test/unit/read-configtx.js b/test/unit/read-configtx.js index 8110803221..c529232b8a 100644 --- a/test/unit/read-configtx.js +++ b/test/unit/read-configtx.js @@ -8,52 +8,52 @@ if (global && global.hfc) global.hfc.config = undefined; require('nconf').reset(); -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('E2E create-channel'); -var fs = require('fs'); -var path = require('path'); -var tape = require('tape'); -var _test = require('tape-promise').default; -var test = _test(tape); +const utils = require('fabric-client/lib/utils.js'); +const logger = utils.getLogger('E2E create-channel'); +const fs = require('fs'); +const path = require('path'); +const tape = require('tape'); +const _test = require('tape-promise').default; +const test = _test(tape); -var Channel = require('fabric-client/lib/Channel.js'); +const Channel = require('fabric-client/lib/Channel.js'); -var grpc = require('grpc'); -var _commonProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/common.proto').common; -var _configtxProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/configtx.proto').common; +const grpc = require('grpc'); +const _commonProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/common.proto').common; +const _configtxProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/configtx.proto').common; -var testUtil = require('../unit/util.js'); +const testUtil = require('../unit/util.js'); -test('\n\n***** READ in the genesis block *****\n\n', function(t) { +test('\n\n***** READ in the genesis block *****\n\n', (t) => { testUtil.resetDefaults(); // readin the envelope to send to the orderer - let normalPath = path.normalize(path.join(__dirname, '../fixtures/channel/twoorgs.genesis.block')); - var data = fs.readFileSync(normalPath); + const normalPath = path.normalize(path.join(__dirname, '../fixtures/channel/twoorgs.genesis.block')); + const data = fs.readFileSync(normalPath); - var channel = new Channel('test', 'fake'); + const channel = new Channel('test', 'fake'); - var block = _commonProto.Block.decode(data); - var envelope = _commonProto.Envelope.decode(block.data.data[0]); - var payload = _commonProto.Payload.decode(envelope.payload); - var channel_header = _commonProto.ChannelHeader.decode(payload.header.channel_header); + const block = _commonProto.Block.decode(data); + const envelope = _commonProto.Envelope.decode(block.data.data[0]); + const payload = _commonProto.Payload.decode(envelope.payload); + const channel_header = _commonProto.ChannelHeader.decode(payload.header.channel_header); if(channel_header.type != _commonProto.HeaderType.CONFIG) { logger.error('Block must be of type "CONFIG"'); } - var config_envelope = _configtxProto.ConfigEnvelope.decode(payload.data); + const config_envelope = _configtxProto.ConfigEnvelope.decode(payload.data); channel.loadConfigEnvelope(config_envelope); t.pass(' Loaded the geneisis block from the configtx tool'); t.end(); }); -test('\n\n***** READ in the configtx *****\n\n', function(t) { +test('\n\n***** READ in the configtx *****\n\n', (t) => { // readin the envelope to send to the orderer - let normalPath = path.normalize(path.join(__dirname, '../fixtures/channel/mychannel.tx')); - var data = fs.readFileSync(normalPath); + const normalPath = path.normalize(path.join(__dirname, '../fixtures/channel/mychannel.tx')); + const data = fs.readFileSync(normalPath); - var channel = new Channel('test', 'fake'); + const channel = new Channel('test', 'fake'); channel.loadConfigUpdateEnvelope(data); t.pass(' Loaded the channel config from the configtx tool');