From 4555441463d95d4f23e3aea28a34f2573f693a87 Mon Sep 17 00:00:00 2001 From: davidLiu Date: Wed, 27 Mar 2019 14:37:18 +0800 Subject: [PATCH] [FABN-909] remove unused fabric-ca-client files disclose some hardcode gitignore remove unsed fabric-ca-client but copied with gulp watch remove gulp watch remove gulp items moving to fabric-common - utils.js - User.js - BaseClient.js - msp.js items moving to fabric-protos - npm grpc: it should be a singleton add format.js, should it be moved to fabric-common migrate impl directory Change-Id: I1a5aaf070c91f09951578a75295595c3fd9ff417 Signed-off-by: davidLiu --- .eslintignore | 1 + .gitignore | 10 - build/tasks/ca.js | 35 -- build/tasks/doc.js | 19 +- build/tasks/test.js | 25 +- build/tasks/watch.js | 33 -- fabric-ca-client/config/default.json | 6 +- fabric-ca-client/lib/AffiliationService.js | 13 +- fabric-ca-client/lib/CertificateService.js | 4 +- fabric-ca-client/lib/FabricCAClient.js | 18 +- fabric-ca-client/lib/FabricCAServices.js | 49 +- fabric-ca-client/package.json | 7 +- fabric-ca-client/test/AffiliationService.js | 18 +- fabric-ca-client/test/CertificateService.js | 24 +- fabric-ca-client/test/FabricCAClient.js | 16 +- fabric-ca-client/test/FabricCAServices.js | 62 ++- fabric-ca-client/test/IdentityService.js | 7 +- fabric-ca-client/test/helper.js | 2 +- fabric-client/config/default.json | 18 +- fabric-client/lib/BlockDecoder.js | 3 +- fabric-client/lib/CertificateAuthority.js | 8 +- fabric-client/lib/Chaincode.js | 14 +- fabric-client/lib/Channel.js | 5 +- fabric-client/lib/ChannelEventHub.js | 22 +- fabric-client/lib/Client.js | 11 +- fabric-client/lib/Orderer.js | 11 +- fabric-client/lib/Organization.js | 2 +- fabric-client/lib/Package.js | 2 +- fabric-client/lib/Packager.js | 2 +- fabric-client/lib/Peer.js | 6 +- fabric-client/lib/Remote.js | 5 +- fabric-client/lib/SideDB.js | 4 +- fabric-client/lib/TokenClient.js | 9 +- fabric-client/lib/TransactionID.js | 29 +- fabric-client/lib/client-utils.js | 4 +- fabric-client/lib/impl/BasicCommitHandler.js | 5 +- fabric-client/lib/impl/BasicProverHandler.js | 2 +- .../lib/impl/DiscoveryEndorsementHandler.js | 5 +- fabric-client/lib/impl/NetworkConfig_1_0.js | 7 +- fabric-client/lib/msp/msp-manager.js | 19 +- fabric-client/lib/packager/BasePackager.js | 18 +- fabric-client/lib/packager/Car.js | 2 +- fabric-client/lib/packager/Golang.js | 7 +- fabric-client/lib/packager/Java.js | 7 +- fabric-client/lib/packager/Node.js | 7 +- fabric-client/lib/token-utils.js | 2 +- fabric-client/lib/utils/format.js | 30 ++ fabric-client/package.json | 5 +- fabric-client/test/BaseClient.js | 4 +- fabric-client/test/Channel.js | 491 ++++++++++++------ fabric-client/test/ChannelEventHub.js | 64 ++- fabric-client/test/Client.js | 252 +++++++-- fabric-client/test/Peer.js | 6 +- fabric-client/test/TransactionID.js | 7 +- fabric-client/test/User.js | 410 ++++++++++----- .../test/impl/CouchDBKeyValueStore.js | 4 +- fabric-client/test/impl/FileKeyValueStore.js | 2 +- fabric-client/test/impl/bccsp_pkcs11.js | 2 +- fabric-client/test/impl/ecdsa/key.js | 6 +- fabric-client/test/msp/msp.js | 11 +- fabric-client/test/utils.js | 45 +- fabric-client/test/utils/format.js | 49 ++ fabric-common/index.js | 10 +- .../lib/BaseClient.js | 20 +- .../msp/msp.js => fabric-common/lib/Msp.js | 22 +- {fabric-client => fabric-common}/lib/User.js | 31 +- .../utils.js => fabric-common/lib/Utils.js | 43 +- .../lib/impl/CouchDBKeyValueStore.js | 3 +- .../lib/impl/CryptoKeyStore.js | 7 +- .../lib/impl/CryptoSuite_ECDSA_AES.js | 11 +- .../lib/impl/FileKeyValueStore.js | 3 +- .../lib/impl/aes/pkcs11_key.js | 0 .../lib/impl/bccsp_pkcs11.js | 35 +- .../lib/impl/ecdsa/key.js | 3 +- .../lib/impl/ecdsa/pkcs11_key.js | 0 fabric-common/package.json | 4 +- .../lib/impl/event/abstracteventlistener.js | 3 +- .../lib/impl/wallet/couchdbwallet.js | 2 +- .../lib/impl/wallet/filesystemwallet.js | 2 +- .../lib/impl/wallet/hsmwalletmixin.js | 2 +- fabric-network/lib/logger.js | 4 +- fabric-network/package.json | 1 + .../test/impl/wallet/couchdbwallet.js | 2 +- .../test/impl/wallet/hsmwalletmixin.js | 3 +- fabric-protos/grpc.js | 1 + test/fixtures/credentials/cloudant.json | 4 +- test/fixtures/credentials/couchdb.json | 2 +- test/integration/channel-event-hub.js | 2 +- test/integration/client.js | 10 +- test/integration/cloudant-fabricca-tests.js | 5 +- test/integration/configtxlator.js | 4 +- test/integration/couchdb-fabricca-tests.js | 5 +- test/integration/create-configtx-channel.js | 4 +- test/integration/discovery.js | 2 +- test/integration/e2e/create-channel.js | 4 +- test/integration/e2e/e2eUtils.js | 2 +- .../integration/e2e/install-chaincode-fail.js | 2 +- test/integration/e2e/install-chaincode.js | 2 +- test/integration/e2e/instantiate-chaincode.js | 2 +- test/integration/e2e/join-channel.js | 2 +- test/integration/e2e/private-data.js | 2 +- test/integration/e2e/updateAnchorPeers.js | 4 +- test/integration/eventutil.js | 2 +- .../fabric-ca-affiliation-service-tests.js | 2 +- .../fabric-ca-certificate-service-tests.js | 2 +- .../fabric-ca-identity-service-tests.js | 12 +- test/integration/fabric-ca-services-tests.js | 77 ++- .../fileKeyValueStore-fabricca-tests.js | 5 +- test/integration/get-config.js | 2 +- test/integration/grpc.js | 2 +- test/integration/install.js | 2 +- test/integration/instantiate.js | 2 +- test/integration/invoke.js | 2 +- test/integration/memory.js | 2 +- test/integration/network-config.js | 2 +- test/integration/network-e2e/idmanager.js | 2 +- .../network-e2e/install-chaincode.js | 2 +- .../network-e2e/instantiate-chaincode.js | 2 +- .../network-e2e/updateAnchorPeers.js | 10 +- .../nodechaincode/install-chaincode.js | 2 +- .../nodechaincode/instantiate-chaincode.js | 2 +- test/integration/only-admin.js | 2 +- test/integration/orderer-channel-tests.js | 4 +- test/integration/query.js | 4 +- test/integration/token.js | 2 +- test/integration/upgrade.js | 2 +- test/typescript/test.ts | 4 +- test/unit/crypto-key-store.js | 12 +- test/unit/cryptosuite-ecdsa-aes.js | 9 +- test/unit/logger.js | 2 +- test/unit/network-config.js | 3 +- test/unit/read-configtx.js | 2 +- test/unit/util.js | 5 +- 133 files changed, 1438 insertions(+), 990 deletions(-) delete mode 100644 build/tasks/ca.js delete mode 100644 build/tasks/watch.js create mode 100644 fabric-client/lib/utils/format.js create mode 100644 fabric-client/test/utils/format.js rename {fabric-client => fabric-common}/lib/BaseClient.js (93%) rename fabric-client/lib/msp/msp.js => fabric-common/lib/Msp.js (85%) rename {fabric-client => fabric-common}/lib/User.js (90%) rename fabric-client/lib/utils.js => fabric-common/lib/Utils.js (91%) rename {fabric-client => fabric-common}/lib/impl/CouchDBKeyValueStore.js (97%) rename {fabric-client => fabric-common}/lib/impl/CryptoKeyStore.js (96%) rename {fabric-client => fabric-common}/lib/impl/CryptoSuite_ECDSA_AES.js (97%) rename {fabric-client => fabric-common}/lib/impl/FileKeyValueStore.js (95%) rename {fabric-client => fabric-common}/lib/impl/aes/pkcs11_key.js (100%) rename {fabric-client => fabric-common}/lib/impl/bccsp_pkcs11.js (98%) rename {fabric-client => fabric-common}/lib/impl/ecdsa/key.js (98%) rename {fabric-client => fabric-common}/lib/impl/ecdsa/pkcs11_key.js (100%) create mode 100644 fabric-protos/grpc.js diff --git a/.eslintignore b/.eslintignore index 006e8b1761..abfd5e6d29 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,3 +5,4 @@ # ./test coverage +node_modules diff --git a/.gitignore b/.gitignore index 8bbef81aa5..8412fcdb01 100644 --- a/.gitignore +++ b/.gitignore @@ -38,16 +38,6 @@ fabric-client/.nyc_output fabric-ca-client/.DS_Store fabric-ca-client/node_modules/* fabric-ca-client/.nyc_output -fabric-ca-client/lib/api.js -fabric-ca-client/lib/utils.js -fabric-ca-client/lib/BaseClient.js -fabric-ca-client/lib/Config.js -fabric-ca-client/lib/Remote.js -fabric-ca-client/lib/User.js -fabric-ca-client/lib/msp/* -fabric-ca-client/lib/protos/* -fabric-ca-client/lib/hash.js -fabric-ca-client/lib/impl/* fabric-ca-client/types/base.d.ts fabric-ca-client/types/tsconfig.json diff --git a/build/tasks/ca.js b/build/tasks/ca.js deleted file mode 100644 index 924af452ca..0000000000 --- a/build/tasks/ca.js +++ /dev/null @@ -1,35 +0,0 @@ -/* -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 -*/ -'use strict'; - -const gulp = require('gulp'); -const debug = require('gulp-debug'); - -const DEPS = [ - 'fabric-client/lib/utils.js', - 'fabric-client/lib/BaseClient.js', - 'fabric-client/lib/Remote.js', - 'fabric-client/lib/User.js', - 'fabric-client/lib/impl/bccsp_pkcs11.js', - 'fabric-client/lib/impl/CouchDBKeyValueStore.js', - 'fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js', - 'fabric-client/lib/impl/aes/*', - 'fabric-client/lib/impl/ecdsa/*', - 'fabric-client/lib/impl/CryptoKeyStore.js', - 'fabric-client/lib/impl/FileKeyValueStore.js', - 'fabric-client/lib/msp/msp.js', - 'fabric-client/types/tsconfig.json', - 'fabric-client/types/base.d.ts' -]; - -gulp.task('ca', () => { - return gulp.src(DEPS, {base: 'fabric-client/'}) - .pipe(debug()) - .pipe(gulp.dest('fabric-ca-client/')) - .pipe(gulp.dest('node_modules/fabric-ca-client')); -}); - -module.exports.DEPS = DEPS; diff --git a/build/tasks/doc.js b/build/tasks/doc.js index bae66e653b..1801dbe91c 100644 --- a/build/tasks/doc.js +++ b/build/tasks/doc.js @@ -1,18 +1,7 @@ -/* - Copyright 2016 IBM All Rights Reserved. +/** + * SPDX-License-Identifier: Apache-2.0 + */ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ const gulp = require('gulp'); const jsdoc = require('gulp-jsdoc3'); @@ -42,8 +31,6 @@ const docSrc = [ 'fabric-client/index.js', 'fabric-client/lib/**/*.js', '!fabric-client/lib/protos/**', - '!fabric-client/lib/hash.js', - '!fabric-client/lib/utils.js', 'fabric-ca-client/index.js', 'fabric-ca-client/lib/FabricCAServices.js', 'fabric-ca-client/lib/FabricCAClient.js', diff --git a/build/tasks/test.js b/build/tasks/test.js index 5decc0b802..ec5d98fa65 100644 --- a/build/tasks/test.js +++ b/build/tasks/test.js @@ -79,7 +79,7 @@ gulp.task('pre-test', () => { '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-ca-client/lib/AffiliationService.js' ]); }); @@ -116,7 +116,7 @@ gulp.task('docker-ready', ['docker-clean'], shell.task([ gulp.task('lint', ['eslint', 'tslint']); gulp.task('compile', shell.task([ - 'npm run compile', + 'npm run compile' ], { verbose: true, // so we can see the docker command output ignoreErrors: false // once compile failed, throw error @@ -143,7 +143,6 @@ gulp.task('run-test-mocha', (done) => { const tasks = ['mocha-fabric-common', 'mocha-fabric-ca-client', 'mocha-fabric-client', 'mocha-fabric-network', 'mocha-fabric-protos']; runSequence(...tasks, done); }); - gulp.task('mocha-fabric-common', () => { return gulp.src(['./fabric-common/test/**/*.js'], {read: false}) @@ -206,19 +205,19 @@ gulp.task('run-test-scenario', (done) => { // Main test method to run all test suites // - lint, unit first, then FV, then scenario gulp.task('run-test', (done) => { - const tasks = ['clean-up', 'docker-clean', 'pre-test', 'ca', 'compile', 'lint', 'docs', 'test-mocha', 'run-tape-unit', 'test-fv-only']; + const tasks = ['clean-up', 'docker-clean', 'pre-test', 'compile', 'lint', 'docs', 'test-mocha', 'run-tape-unit', 'test-fv-only']; runSequence(...tasks, done); }); // fabric end-to-end test gulp.task('run-end-to-end', (done) => { - const tasks = ['clean-up', 'docker-clean', 'pre-test', 'ca', 'compile', 'run-tape-e2e']; + const tasks = ['clean-up', 'docker-clean', 'pre-test', 'compile', 'run-tape-e2e']; runSequence(...tasks, done); }); // Run all non-integration tests gulp.task('run-test-headless', (done) => { - const tasks = ['clean-up', 'pre-test', 'ca', 'lint', 'test-mocha', 'run-tape-unit']; + const tasks = ['clean-up', 'pre-test', 'lint', 'test-mocha', 'run-tape-unit']; runSequence(...tasks, done); }); @@ -232,7 +231,7 @@ gulp.task('run-tape-unit', 'test/unit/**/*.js', '!test/unit/constants.js', '!test/unit/util.js', - '!test/unit/logger.js', + '!test/unit/logger.js' ])) .pipe(tape({ reporter: tapColorize() @@ -302,7 +301,7 @@ gulp.task('run-tape-e2e', ['docker-ready'], 'test/integration/token.js', // Typescript - 'test/typescript/test.js', + 'test/typescript/test.js' ])) .pipe(tape({ reporter: tapColorize() @@ -319,21 +318,21 @@ function shouldRunTests(tests) { if (arch.indexOf('s390') === 0) { tests.push('!test/unit/pkcs11.js'); tests.push('!test/integration/network-e2e/e2e-hsm.js'); - // check to see if they want to test PKCS11 + // check to see if they want to test PKCS11 } else if (typeof process.env.PKCS11_TESTS === 'string' && process.env.PKCS11_TESTS.toLowerCase() === 'true') { tests.push('!test/integration/network-e2e/e2e.js'); - // check to see if they do not want to test PKCS11 + // check to see if they do not want to test PKCS11 } else if (typeof process.env.PKCS11_TESTS === 'string' && process.env.PKCS11_TESTS.toLowerCase() === 'false') { tests.push('!test/unit/pkcs11.js'); tests.push('!test/integration/network-e2e/e2e-hsm.js'); - // default is to run the PKCS11 tests so we need to disable the non HSM version + // default is to run the PKCS11 tests so we need to disable the non HSM version } else { tests.push('!test/integration/network-e2e/e2e.js'); } // keep the java tests if (typeof process.env.JAVA_TESTS === 'string' && process.env.JAVA_TESTS.toLowerCase() === 'true') { - // disable when z390 or when JAVA tests is off - } else if ((arch.indexOf('s390') === 0) || (typeof process.env.JAVA_TESTS === 'string' && process.env.JAVA_TESTS.toLowerCase() === 'false')) { + // disable when z390 or when JAVA tests is off + } else if ((arch.indexOf('s390') === 0) || (typeof process.env.JAVA_TESTS === 'string' && process.env.JAVA_TESTS.toLowerCase() === 'false')) { tests.push('!test/integration/javachaincode/e2e.js'); } diff --git a/build/tasks/watch.js b/build/tasks/watch.js deleted file mode 100644 index ec0c9453e0..0000000000 --- a/build/tasks/watch.js +++ /dev/null @@ -1,33 +0,0 @@ -/* -# Copyright IBM Corp. All Rights Reserved. -# -# SPDX-License-Identifier: Apache-2.0 -*/ -const gulp = require('gulp'), - watch = require('gulp-watch'), - debug = require('gulp-debug'), - fs = require('fs'), - ca = require('./ca.js'); - -gulp.task('watch', () => { - watch(ca.DEPS, {ignoreInitial: false, base: 'fabric-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 - 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', - 'fabric-client/config/**/*', - 'fabric-client/lib/**/*', - 'fabric-ca-client/index.js', - 'fabric-ca-client/config/**/*', - 'fabric-ca-client/lib/**/*' - ], {ignoreInitial: false, base: './'}) - .pipe(debug()) - .pipe(gulp.dest('node_modules')); - } -}); diff --git a/fabric-ca-client/config/default.json b/fabric-ca-client/config/default.json index e261955aa8..7ca255b94b 100644 --- a/fabric-ca-client/config/default.json +++ b/fabric-ca-client/config/default.json @@ -5,11 +5,11 @@ "crypto-keysize": 256, "crypto-hsm": false, "crypto-suite-software": { - "EC": "fabric-ca-client/lib/impl/CryptoSuite_ECDSA_AES.js" + "EC": "fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js" }, "crypto-suite-hsm": { - "EC": "fabric-ca-client/lib/impl/bccsp_pkcs11.js" + "EC": "fabric-common/lib/impl/bccsp_pkcs11.js" }, - "key-value-store": "fabric-ca-client/lib/impl/FileKeyValueStore.js", + "key-value-store": "fabric-common/lib/impl/FileKeyValueStore.js", "connection-timeout": 3000 } diff --git a/fabric-ca-client/lib/AffiliationService.js b/fabric-ca-client/lib/AffiliationService.js index d0e4419975..26647777fd 100644 --- a/fabric-ca-client/lib/AffiliationService.js +++ b/fabric-ca-client/lib/AffiliationService.js @@ -1,13 +1,10 @@ -/* - Copyright 2018 IBM All Rights Reserved. - - SPDX-License-Identifier: Apache-2.0 - -*/ +/** + * SPDX-License-Identifier: Apache-2.0 + */ 'use strict'; - -const logger = require('./utils').getLogger('AffiliationService'); +const {Utils} = require('fabric-common'); +const logger = Utils.getLogger('AffiliationService'); const checkRegistrar = require('./helper').checkRegistrar; /** diff --git a/fabric-ca-client/lib/CertificateService.js b/fabric-ca-client/lib/CertificateService.js index d9fed8168a..e2ffce0fc9 100644 --- a/fabric-ca-client/lib/CertificateService.js +++ b/fabric-ca-client/lib/CertificateService.js @@ -5,7 +5,9 @@ */ const querystring = require('querystring'); -const logger = require('./utils.js').getLogger('CertificateService'); +const {Utils} = require('fabric-common'); + +const logger = Utils.getLogger('CertificateService'); const checkRegistrar = require('./helper').checkRegistrar; class CertificateService { diff --git a/fabric-ca-client/lib/FabricCAClient.js b/fabric-ca-client/lib/FabricCAClient.js index 2684b7602c..c272c83c66 100644 --- a/fabric-ca-client/lib/FabricCAClient.js +++ b/fabric-ca-client/lib/FabricCAClient.js @@ -1,20 +1,10 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const config = utils.getConfig(); const logger = utils.getLogger('FabricCAClient.js'); const http = require('http'); @@ -54,7 +44,7 @@ const FabricCAClient = class { } this._caName = connect_opts.caname, - this._httpClient = (connect_opts.protocol === 'http') ? http : https; + this._httpClient = (connect_opts.protocol === 'http') ? http : https; this._hostname = connect_opts.hostname; if (connect_opts.port) { this._port = connect_opts.port; diff --git a/fabric-ca-client/lib/FabricCAServices.js b/fabric-ca-client/lib/FabricCAServices.js index ad228b23cc..0df69a70d4 100644 --- a/fabric-ca-client/lib/FabricCAServices.js +++ b/fabric-ca-client/lib/FabricCAServices.js @@ -7,11 +7,11 @@ 'use strict'; -const utils = require('./utils.js'); -const BaseClient = require('./BaseClient'); +const {Utils: utils, BaseClient} = require('fabric-common'); + const FabricCAClient = require('./FabricCAClient'); -const normalizeX509 = require('./BaseClient').normalizeX509; +const {normalizeX509} = BaseClient; const util = require('util'); const parseURL = require('./helper').parseURL; const path = require('path'); @@ -41,7 +41,7 @@ const FabricCAServices = class extends BaseClient { * constructor * * @param {string | object} url The endpoint URL for Fabric CA services of the form: "http://host:port" or "https://host:port" - When this parameter is an object then it must include the parameters listed as key value pairs. + When this parameter is an object then it must include the parameters listed as key value pairs. * @param {TLSOptions} tlsOptions The TLS settings to use when the Fabric CA services endpoint uses "https" * @param {string} caName The optional name of the CA. Fabric-ca servers support multiple Certificate Authorities from * a single server. If omitted or null or an empty string, then the default CA is the target of requests @@ -55,43 +55,44 @@ const FabricCAServices = class extends BaseClient { * is provided for this purpose, which can be used on top of any implementation of the {@link KeyValueStore} interface, * such as a file-based store or a database-based one. The specific implementation is determined by the value of this configuration setting. */ - constructor(url_p, tlsOptions_p, caName_p, cryptoSuite_p) { + constructor(url, tlsOptions, caName, cryptoSuite) { super(); - let url, tlsOptions, caName, cryptoSuite; - if (typeof url_p === 'object') { - url = url_p.url; - tlsOptions = url_p.tlsOptions; - caName = url_p.caName; - cryptoSuite = url_p.cryptoSuite; + let _url, _tlsOptions, _caName, _cryptoSuite; + if (typeof url === 'object') { + _url = url.url; + _tlsOptions = url.tlsOptions; + _caName = url.caName; + _cryptoSuite = url.cryptoSuite; } else { - url = url_p; - tlsOptions = tlsOptions_p; - caName = caName_p; - cryptoSuite = cryptoSuite_p; + _url = url; + _tlsOptions = tlsOptions; + _caName = caName; + _cryptoSuite = cryptoSuite; } - this.caName = caName; + this.caName = _caName; - const endpoint = parseURL(url); + const endpoint = parseURL(_url); - if (cryptoSuite) { - this.setCryptoSuite(cryptoSuite); + if (_cryptoSuite) { + this.setCryptoSuite(_cryptoSuite); } else { this.setCryptoSuite(utils.newCryptoSuite()); this.getCryptoSuite().setCryptoKeyStore(utils.newCryptoKeyStore()); } this._fabricCAClient = new FabricCAClient({ - caname: caName, + caname: _caName, protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, - tlsOptions: tlsOptions + tlsOptions: _tlsOptions }, this.getCryptoSuite()); logger.debug('Successfully constructed Fabric CA service client: endpoint - %j', endpoint); } + /** * Returns the name of the certificate authority. * @@ -230,7 +231,7 @@ const FabricCAServices = class extends BaseClient { const enrollment = { certificate: enrollResponse.enrollmentCert, - rootCertificate: enrollResponse.caCertChain, + rootCertificate: enrollResponse.caCertChain }; if (!req.csr) { enrollment.key = privateKey; @@ -422,8 +423,8 @@ const FabricCAServices = class extends BaseClient { */ /** - * return a printable representation of this object - */ + * return a printable representation of this object + */ toString() { return 'FabricCAServices : {' + 'hostname: ' + this._fabricCAClient._hostname + diff --git a/fabric-ca-client/package.json b/fabric-ca-client/package.json index 6e90d2fc8a..b3c59722ca 100644 --- a/fabric-ca-client/package.json +++ b/fabric-ca-client/package.json @@ -27,16 +27,11 @@ "fabric-common": "file:../fabric-common", "fabric-protos": "file:../fabric-protos", "fs-extra": "^6.0.1", - "grpc": "1.17.0", "js-sha3": "^0.7.0", "jsrsasign": "^7.2.2", "jssha": "^2.1.0", - "long": "^4.0.0", - "nconf": "^0.10.0", - "sjcl": "1.0.7", "url": "^0.11.0", - "util": "^0.10.3", - "winston": "^2.2.0" + "util": "^0.10.3" }, "devDependencies": { "chai": "^4.1.2", diff --git a/fabric-ca-client/test/AffiliationService.js b/fabric-ca-client/test/AffiliationService.js index 56ea630cc5..325585fae2 100644 --- a/fabric-ca-client/test/AffiliationService.js +++ b/fabric-ca-client/test/AffiliationService.js @@ -1,15 +1,5 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; @@ -17,8 +7,8 @@ const rewire = require('rewire'); const AffiliationService = require('../lib/AffiliationService'); const AffiliationServiceRewire = rewire('../lib/AffiliationService'); -const FabricCAClient = require('../lib/FabricCAClient'); -const User = require('../lib/User'); +const FabricCAClient = require('../lib/FabricCAClient'); +const {User} = require('fabric-common'); const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); diff --git a/fabric-ca-client/test/CertificateService.js b/fabric-ca-client/test/CertificateService.js index c154985bef..fe5eb57794 100644 --- a/fabric-ca-client/test/CertificateService.js +++ b/fabric-ca-client/test/CertificateService.js @@ -1,15 +1,5 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; @@ -17,7 +7,7 @@ const rewire = require('rewire'); const CertificateServiceRewire = rewire('../lib/CertificateService'); const FabricCAClient = require('../lib/FabricCAClient'); -const User = require('../lib/User'); +const {User} = require('fabric-common'); require('chai').should(); const sinon = require('sinon'); @@ -51,8 +41,10 @@ describe('IdentityService', () => { service = new CertificateServiceRewire(clientStub); const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; debugStub = sinon.stub(FakeLogger, 'debug'); @@ -104,7 +96,7 @@ describe('IdentityService', () => { callArgs[1].should.deep.equal('myID'); }); - it('should call get with the correctly mapped request', async() => { + it('should call get with the correctly mapped request', async () => { const registrar = new User('bob'); registrar._signingIdentity = 'myID'; diff --git a/fabric-ca-client/test/FabricCAClient.js b/fabric-ca-client/test/FabricCAClient.js index ad2c792652..e9b6e50030 100644 --- a/fabric-ca-client/test/FabricCAClient.js +++ b/fabric-ca-client/test/FabricCAClient.js @@ -1,22 +1,12 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; const rewire = require('rewire'); const FabricCAClientRewire = rewire('../lib/FabricCAClient.js'); -const CryptoSuite = require('../lib/impl/CryptoSuite_ECDSA_AES.js'); +const CryptoSuite = require('fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js'); const http = require('http'); const https = require('https'); diff --git a/fabric-ca-client/test/FabricCAServices.js b/fabric-ca-client/test/FabricCAServices.js index 3315312e2b..182015f9ce 100644 --- a/fabric-ca-client/test/FabricCAServices.js +++ b/fabric-ca-client/test/FabricCAServices.js @@ -18,9 +18,9 @@ const rewire = require('rewire'); const FabricCAServicesRewire = rewire('../lib/FabricCAServices'); const FabricCAClient = rewire('../lib/FabricCAClient'); -const CryptoSuite = require('../lib/impl/CryptoSuite_ECDSA_AES.js'); -const ECDSAKey = require('../lib/impl/ecdsa/key'); -const User = require('../lib/User'); +const CryptoSuite = require('fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js'); +const ECDSAKey = require('fabric-common/lib/impl/ecdsa/key'); +const {User} = require('fabric-common'); const chai = require('chai'); const should = chai.should(); @@ -193,7 +193,14 @@ describe('FabricCAServices', () => { const registrar = new User('bob'); registrar._signingIdentity = 'myID'; - service.register({enrollmentID: 'bob', enrollmentSecret: 'shhh!', maxEnrollments: 7, role: 'test_role', affiliation: 'test_affiliation', attrs: 'test_atts'}, registrar); + service.register({ + enrollmentID: 'bob', + enrollmentSecret: 'shhh!', + maxEnrollments: 7, + role: 'test_role', + affiliation: 'test_affiliation', + attrs: 'test_atts' + }, registrar); sinon.assert.calledOnce(clientMock.register); // should be called with test values @@ -239,11 +246,19 @@ describe('FabricCAServices', () => { }); it('should throw if request attributes is specified but not an array', async () => { - await service.enroll({enrollmentID: 'isSet', enrollmentSecret: 'shhhh!', attr_reqs: 'incorrect'}).should.be.rejectedWith(/req.attr_reqs is not an array/); + await service.enroll({ + enrollmentID: 'isSet', + enrollmentSecret: 'shhhh!', + attr_reqs: 'incorrect' + }).should.be.rejectedWith(/req.attr_reqs is not an array/); }); it('should throw if any request attributes are missing a name', async () => { - await service.enroll({enrollmentID: 'isSet', enrollmentSecret: 'shhhh!', attr_reqs: [{name: 'pingu'}, {missing: 'name'}]}).should.be.rejectedWith(/req.att_regs is missing the attribute name/); + await service.enroll({ + enrollmentID: 'isSet', + enrollmentSecret: 'shhhh!', + attr_reqs: [{name: 'pingu'}, {missing: 'name'}] + }).should.be.rejectedWith(/req.att_regs is missing the attribute name/); }); it('should reject on enroll failure', async () => { @@ -259,7 +274,12 @@ describe('FabricCAServices', () => { clientMock.enroll.rejects(new Error('enroll error')); const atts = [{name: 'penguin'}, {name: 'power'}]; - const req = {enrollmentID: 'enrollmentID', enrollmentSecret: 'enrollmentSecret', profile: 'profile', attr_reqs: atts}; + const req = { + enrollmentID: 'enrollmentID', + enrollmentSecret: 'enrollmentSecret', + profile: 'profile', + attr_reqs: atts + }; await service.enroll(req).should.be.rejectedWith(/enroll error/); }); @@ -275,7 +295,12 @@ describe('FabricCAServices', () => { cryptoPrimitives.generateEphemeralKey.returns(keyStub); const atts = [{name: 'penguin'}, {name: 'power'}]; - const req = {enrollmentID: 'enrollmentID', enrollmentSecret: 'enrollmentSecret', profile: 'profile', attr_reqs: atts}; + const req = { + enrollmentID: 'enrollmentID', + enrollmentSecret: 'enrollmentSecret', + profile: 'profile', + attr_reqs: atts + }; await service.enroll(req).should.be.rejectedWith(/Failed to generate CSR for enrollmemnt due to error \[Error: CSR error\]/); }); @@ -288,7 +313,12 @@ describe('FabricCAServices', () => { cryptoPrimitives.generateEphemeralKey.throws(new Error('Key error')); const atts = [{name: 'penguin'}, {name: 'power'}]; - const req = {enrollmentID: 'enrollmentID', enrollmentSecret: 'enrollmentSecret', profile: 'profile', attr_reqs: atts}; + const req = { + enrollmentID: 'enrollmentID', + enrollmentSecret: 'enrollmentSecret', + profile: 'profile', + attr_reqs: atts + }; await service.enroll(req).should.be.rejectedWith(/Failed to generate key for enrollment due to error \[Error: Key error\]/); }); @@ -318,7 +348,12 @@ describe('FabricCAServices', () => { }); const atts = [{name: 'penguin'}, {name: 'power'}]; - const req = {enrollmentID: 'enrollmentID', enrollmentSecret: 'enrollmentSecret', profile: 'profile', attr_reqs: atts}; + const req = { + enrollmentID: 'enrollmentID', + enrollmentSecret: 'enrollmentSecret', + profile: 'profile', + attr_reqs: atts + }; await service.enroll(req); // should call generateKey, not generateEphemeral @@ -342,7 +377,12 @@ describe('FabricCAServices', () => { }); const atts = [{name: 'penguin'}, {name: 'power'}]; - const req = {enrollmentID: 'enrollmentID', enrollmentSecret: 'enrollmentSecret', profile: 'profile', attr_reqs: atts}; + const req = { + enrollmentID: 'enrollmentID', + enrollmentSecret: 'enrollmentSecret', + profile: 'profile', + attr_reqs: atts + }; await service.enroll(req); // generateKey should be called diff --git a/fabric-ca-client/test/IdentityService.js b/fabric-ca-client/test/IdentityService.js index 56f8a8438f..e6216aaf46 100644 --- a/fabric-ca-client/test/IdentityService.js +++ b/fabric-ca-client/test/IdentityService.js @@ -18,7 +18,7 @@ const IdentityService = require('../lib/IdentityService'); const IdentityServiceRewire = rewire('../lib/IdentityService'); const FabricCAClient = require('../lib/FabricCAClient'); -const User = require('../lib/User'); +const {User} = require('fabric-common'); require('chai').should(); const sinon = require('sinon'); @@ -183,7 +183,10 @@ describe('IdentityService', () => { const registrar = new User('bob'); registrar._signingIdentity = 'myID'; - await identity.create({enrollmentID: 'dummy', affiliation: 'dummy'}, registrar).should.be.rejectedWith('forced error'); + await identity.create({ + enrollmentID: 'dummy', + affiliation: 'dummy' + }, registrar).should.be.rejectedWith('forced error'); }); }); diff --git a/fabric-ca-client/test/helper.js b/fabric-ca-client/test/helper.js index 6563506c5b..5d73004a03 100644 --- a/fabric-ca-client/test/helper.js +++ b/fabric-ca-client/test/helper.js @@ -15,7 +15,7 @@ 'use strict'; const Helper = require('../lib/helper'); -const User = require('../lib/User'); +const {User} = require('fabric-common'); const chai = require('chai'); const should = chai.should(); diff --git a/fabric-client/config/default.json b/fabric-client/config/default.json index f186bab074..347b652f0c 100644 --- a/fabric-client/config/default.json +++ b/fabric-client/config/default.json @@ -4,30 +4,30 @@ "crypto-keysize": 256, "crypto-hsm": false, "crypto-suite-software": { - "EC": "fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js" + "EC": "fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js" }, "crypto-suite-hsm": { - "EC": "fabric-client/lib/impl/bccsp_pkcs11.js" + "EC": "fabric-common/lib/impl/bccsp_pkcs11.js" }, "channel-name-regx-checker":{ "pattern":"^[a-z][a-z0-9.-]*$", "flags":"" }, - "key-value-store": "fabric-client/lib/impl/FileKeyValueStore.js", + "key-value-store": "fabric-common/lib/impl/FileKeyValueStore.js", "certificate-authority-client": "fabric-ca-client", "nonce-size" : 24, "grpc-ssl-cipher-suites": "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384", "connection-options": { "grpc.max_receive_message_length": -1, "grpc.max_send_message_length": -1, - "grpc.keepalive_time_ms": 120000, - "grpc.http2.min_time_between_pings_ms": 120000, - "grpc.keepalive_timeout_ms": 20000, - "grpc.http2.max_pings_without_data": 0, - "grpc.keepalive_permit_without_calls": 1 + "grpc.keepalive_time_ms": 120000, + "grpc.http2.min_time_between_pings_ms": 120000, + "grpc.keepalive_timeout_ms": 20000, + "grpc.http2.max_pings_without_data": 0, + "grpc.keepalive_permit_without_calls": 1 }, "network-config-schema" : { - "1.0": "./impl/NetworkConfig_1_0.js" + "1.0": "fabric-client/lib/impl/NetworkConfig_1_0.js" }, "grpc-wait-for-ready-timeout": 3000, "discovery-as-localhost": true, diff --git a/fabric-client/lib/BlockDecoder.js b/fabric-client/lib/BlockDecoder.js index d552cfbc4e..994e94982b 100644 --- a/fabric-client/lib/BlockDecoder.js +++ b/fabric-client/lib/BlockDecoder.js @@ -15,7 +15,8 @@ 'use strict'; const fabprotos = require('fabric-protos'); -const utils = require('./utils.js'); +const {Utils:utils} = require('fabric-common'); + const logger = utils.getLogger('BlockDecoder.js'); /** diff --git a/fabric-client/lib/CertificateAuthority.js b/fabric-client/lib/CertificateAuthority.js index a962cd6819..697bc1d960 100644 --- a/fabric-client/lib/CertificateAuthority.js +++ b/fabric-client/lib/CertificateAuthority.js @@ -15,7 +15,7 @@ 'use strict'; -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('CertificateAuthority.js'); /** @@ -193,9 +193,9 @@ const CertificateAuthority = class { */ toString() { return 'CertificateAuthority : {' + - 'name : ' + this._name + - ', url : ' + this._url + - '}'; + 'name : ' + this._name + + ', url : ' + this._url + + '}'; } }; diff --git a/fabric-client/lib/Chaincode.js b/fabric-client/lib/Chaincode.js index 71daacffe6..72e6812a21 100644 --- a/fabric-client/lib/Chaincode.js +++ b/fabric-client/lib/Chaincode.js @@ -15,15 +15,13 @@ 'use strict'; const {format} = require('util'); -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('Chaincode.js'); const Policy = require('./Policy.js'); const CollectionConfig = require('./SideDB.js'); const fabprotos = require('fabric-protos').protos; - - /** * @classdesc * The Chaincode class represents an Chaincode definition in the target @@ -446,8 +444,8 @@ const Chaincode = class { logger.debug('%s - hash values are the same :: %s', method, hash); } else { const msg = utils.format('The install for chaincode: %s version: ' + - '%s did not return the same hash value of %s, value was %s', - this._name, this._version, this._hash, hash); + '%s did not return the same hash value of %s, value was %s', + this._name, this._version, this._hash, hash); logger.error(msg); throw new Error(msg); } @@ -550,11 +548,11 @@ const Chaincode = class { */ toString() { return 'Chaincode : {' + - 'name : ' + this._name + - ', version : ' + this._version + + 'name : ' + this._name + + ', version : ' + this._version + ', sequence : ' + this._sequence + ', hash : ' + this._hash + - '}'; + '}'; } static translateCCType(type) { diff --git a/fabric-client/lib/Channel.js b/fabric-client/lib/Channel.js index 85e55a77a3..a96443afcd 100644 --- a/fabric-client/lib/Channel.js +++ b/fabric-client/lib/Channel.js @@ -14,8 +14,7 @@ */ 'use strict'; - -const sdk_utils = require('./utils.js'); +const {Identity, Utils: sdk_utils} = require('fabric-common'); const client_utils = require('./client-utils.js'); const token_utils = require('./token-utils.js'); const util = require('util'); @@ -31,7 +30,7 @@ const MSPManager = require('./msp/msp-manager.js'); const Policy = require('./Policy.js'); const Constants = require('./Constants.js'); const CollectionConfig = require('./SideDB.js'); -const {Identity} = require('fabric-common'); + const ChannelHelper = require('./utils/ChannelHelper'); const ImplicitMetaPolicy_Rule = {0: 'ANY', 1: 'ALL', 2: 'MAJORITY'}; diff --git a/fabric-client/lib/ChannelEventHub.js b/fabric-client/lib/ChannelEventHub.js index e8b64a3c3f..bf844504d6 100644 --- a/fabric-client/lib/ChannelEventHub.js +++ b/fabric-client/lib/ChannelEventHub.js @@ -14,11 +14,11 @@ 'use strict'; const Long = require('long'); -const utils = require('./utils.js'); +const {Utils: utils, Identity} = require('fabric-common'); const clientUtils = require('./client-utils.js'); const Constants = require('./Constants.js'); const logger = utils.getLogger('ChannelEventHub.js'); -const {Identity} = require('fabric-common'); +const {convertToLong} = require('./utils/format'); const TransactionID = require('./TransactionID'); const util = require('util'); const EventHubDisconnectError = require('./errors/EventHubDisconnectError'); @@ -369,7 +369,7 @@ class ChannelEventHub { this._filtered_stream = !full_block; logger.debug('%s - filtered block stream set to:%s', method, !full_block); } else { - logger.debug('%s - using a filtered block stream by default', method); + logger.debug('%s - using a filtered block stream by default', method); } logger.debug('%s - signed event:%s', method, !!signedEvent); @@ -498,10 +498,10 @@ class ChannelEventHub { let block = null; if (deliverResponse.Type === 'block') { block = BlockDecoder.decodeBlock(deliverResponse.block); - self._last_block_seen = utils.convertToLong(block.header.number); + self._last_block_seen = convertToLong(block.header.number); } else { block = JSON.parse(JSON.stringify(deliverResponse.filtered_block)); - self._last_block_seen = utils.convertToLong(block.number); + self._last_block_seen = convertToLong(block.number); } logger.debug('on.data - incoming block number %s', self._last_block_seen); @@ -660,7 +660,7 @@ class ChannelEventHub { const opt = { identity: signer, - txId, + txId }; const seekPayloadBytes = this.generateUnsignedRegistration(opt); @@ -695,7 +695,7 @@ class ChannelEventHub { logger.debug('%s - exit', method); return { signature: signedEvent.signature, - payload: signedEvent.payload, + payload: signedEvent.payload }; } @@ -906,11 +906,11 @@ class ChannelEventHub { _block_num = NEWEST; } else { // maybe it is a string number - _block_num = utils.convertToLong(block_num); + _block_num = convertToLong(block_num); } } else { if (typeof block_num !== 'undefined' && block_num !== null) { - _block_num = utils.convertToLong(block_num); + _block_num = convertToLong(block_num); } } @@ -928,6 +928,7 @@ class ChannelEventHub { return _endBlock; } + /* * Internal method * checks the startBlock/endBlock options @@ -1672,7 +1673,8 @@ class EventRegistration { this._onErrorFn = onError; this.unregister = default_unregister; this.disconnect = default_disconnect; - this.unregister_action = () => { }; // do nothing by default + this.unregister_action = () => { + }; // do nothing by default if (options) { if (typeof options.unregister === 'undefined' || options.unregister === null) { diff --git a/fabric-client/lib/Client.js b/fabric-client/lib/Client.js index 1b83ffc837..7849bce120 100644 --- a/fabric-client/lib/Client.js +++ b/fabric-client/lib/Client.js @@ -7,12 +7,9 @@ 'use strict'; -const sdkUtils = require('./utils.js'); -const clientUtils = require('./client-utils.js'); +const {KeyValueStore, Signer, SigningIdentity, Utils: sdkUtils, User, BaseClient} = require('fabric-common'); -const {KeyValueStore, Signer, SigningIdentity} = require('fabric-common'); -const BaseClient = require('./BaseClient.js'); -const User = require('./User.js'); +const clientUtils = require('./client-utils.js'); const Chaincode = require('./Chaincode.js'); const Channel = require('./Channel.js'); const Package = require('./Package.js'); @@ -900,7 +897,7 @@ const Client = class extends BaseClient { * @typedef {Object} PeerQueryResponse * @property {Object} peers_by_org * @example -{ + { "peers_by_org": { "Org1MSP": { "peers":[ @@ -914,7 +911,7 @@ const Client = class extends BaseClient { } } } - */ + */ /** * Queries the target peer for a list of {@link Peer} objects of all peers diff --git a/fabric-client/lib/Orderer.js b/fabric-client/lib/Orderer.js index 5269591e26..a35cafca0e 100644 --- a/fabric-client/lib/Orderer.js +++ b/fabric-client/lib/Orderer.js @@ -1,13 +1,10 @@ -/* - Copyright 2016, 2018 IBM All Rights Reserved. - - SPDX-License-Identifier: Apache-2.0 - -*/ +/** + * SPDX-License-Identifier: Apache-2.0 + */ 'use strict'; -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const Remote = require('./Remote'); const fabprotos = require('fabric-protos'); diff --git a/fabric-client/lib/Organization.js b/fabric-client/lib/Organization.js index ead1574d45..a7380cbdb6 100644 --- a/fabric-client/lib/Organization.js +++ b/fabric-client/lib/Organization.js @@ -14,7 +14,7 @@ 'use strict'; -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('Organization.js'); /** diff --git a/fabric-client/lib/Package.js b/fabric-client/lib/Package.js index 7f69891440..731e318bd1 100644 --- a/fabric-client/lib/Package.js +++ b/fabric-client/lib/Package.js @@ -10,7 +10,7 @@ const clientUtils = require('./client-utils.js'); const fabprotos = require('fabric-protos'); const Packager = require('./Packager.js'); const tar = require('tar-stream'); -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const zlib = require('zlib'); const logger = utils.getLogger('package'); diff --git a/fabric-client/lib/Packager.js b/fabric-client/lib/Packager.js index 0c4b7241c9..c899afbf81 100644 --- a/fabric-client/lib/Packager.js +++ b/fabric-client/lib/Packager.js @@ -18,7 +18,7 @@ const Golang = require('./packager/Golang.js'); const Car = require('./packager/Car.js'); const Node = require('./packager/Node.js'); const Java = require('./packager/Java.js'); -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('packager'); diff --git a/fabric-client/lib/Peer.js b/fabric-client/lib/Peer.js index 49814d8244..cf1fcec270 100644 --- a/fabric-client/lib/Peer.js +++ b/fabric-client/lib/Peer.js @@ -14,7 +14,7 @@ 'use strict'; -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const Remote = require('./Remote'); const fabprotos = require('fabric-protos'); const util = require('util'); @@ -138,7 +138,7 @@ class Peer extends Remote { } } else { if (proposalResponse) { - logger.debug('%s - Received proposal response from peer "%s": status - %s', method, self._url, (proposalResponse.response && proposalResponse.response.status) ? proposalResponse.response.status : 'undefined'); + logger.debug('%s - Received proposal response from peer "%s": status - %s', method, self._url, (proposalResponse.response && proposalResponse.response.status) ? proposalResponse.response.status : 'undefined'); // 400 is the error threshold level, anything below that the endorser will endorse it. if (proposalResponse.response && proposalResponse.response.status < 400) { proposalResponse.peer = self.getCharacteristics(); @@ -291,7 +291,7 @@ class Peer extends Remote { toString() { return 'Peer:{' + 'url:' + this._url + - '}'; + '}'; } } diff --git a/fabric-client/lib/Remote.js b/fabric-client/lib/Remote.js index cd24a61c34..2057391e17 100644 --- a/fabric-client/lib/Remote.js +++ b/fabric-client/lib/Remote.js @@ -15,12 +15,11 @@ 'use strict'; -const grpc = require('grpc'); +const grpc = require('fabric-protos/grpc'); const urlParser = require('url'); -const utils = require('./utils.js'); +const {Utils: utils, HashPrimitives} = require('fabric-common'); const logger = utils.getLogger('Remote.js'); -const {HashPrimitives} = require('fabric-common'); const MAX_SEND = 'grpc.max_send_message_length'; const MAX_RECEIVE = 'grpc.max_receive_message_length'; const MAX_SEND_V10 = 'grpc-max-send-message-length'; diff --git a/fabric-client/lib/SideDB.js b/fabric-client/lib/SideDB.js index 9d15aa9511..2fe791426c 100644 --- a/fabric-client/lib/SideDB.js +++ b/fabric-client/lib/SideDB.js @@ -16,8 +16,8 @@ const fabprotos = require('fabric-protos'); const fs = require('fs'); const Long = require('long'); const Policy = require('./Policy.js'); +const {Utils: utils} = require('fabric-common'); -const utils = require('./utils.js'); const logger = utils.getLogger('SideDB.js'); const {format} = require('util'); @@ -83,7 +83,7 @@ class CollectionConfig { name, policy, maxPeerCount, - requiredPeerCount, + requiredPeerCount } = collectionConfig; if (!name || typeof name !== 'string') { diff --git a/fabric-client/lib/TokenClient.js b/fabric-client/lib/TokenClient.js index 09d5d1b52e..82b889f6dd 100644 --- a/fabric-client/lib/TokenClient.js +++ b/fabric-client/lib/TokenClient.js @@ -14,15 +14,14 @@ 'use strict'; +const {Utils: utils, Identity, HashPrimitives} = require('fabric-common'); + const TransactionID = require('./TransactionID'); const util = require('util'); const clientUtils = require('./client-utils.js'); const tokenUtils = require('./token-utils.js'); -const utils = require('./utils.js'); const logger = utils.getLogger('TokenClient.js'); const fabprotos = require('fabric-protos'); -const {Identity} = require('fabric-common'); -const {HashPrimitives} = require('fabric-common'); /** * @classdesc @@ -111,7 +110,7 @@ const TokenClient = class { /** * Construct a TokenClient object. * - * @param {Client} client - The Client instance. + * @param {Client} client - The Client instance. * @param {Channel} channel - The channel object. * @param {Peer[]} targets - The prover peer(s) that are trusted by the token client */ @@ -191,7 +190,7 @@ const TokenClient = class { * @property {string} commandName - Required. The token command name, such as * issue, transfer, redeem, and list. * @property {byte[]} tokenIds - Required for transfer and redeem. - An array of token ids that will be spent by the token command. + An array of token ids that will be spent by the token command. * @property {TokenParam[]} params - Required. One or multiple TokenParam * for the token command. * @property {TransactionID} txId - Optional. Required for issue, transfer and redeem. diff --git a/fabric-client/lib/TransactionID.js b/fabric-client/lib/TransactionID.js index 8c8b9bbab1..95fd5d0896 100644 --- a/fabric-client/lib/TransactionID.js +++ b/fabric-client/lib/TransactionID.js @@ -7,10 +7,9 @@ 'use strict'; -const utils = require('./utils.js'); + +const {Utils: utils, HashPrimitives, User} = require('fabric-common'); const logger = utils.getLogger('TransactionID.js'); -const User = require('./User.js'); -const {HashPrimitives} = require('fabric-common'); /** * The class representing the transaction identifier. Provides for @@ -22,12 +21,12 @@ const {HashPrimitives} = require('fabric-common'); class TransactionID { /** - * Builds a new transaction Id based on a user's certificate and an automatically - * generates a nonce value. - * @param {Identity} signer_or_userContext - An instance of {@link Identity} that provides an unique - * base for this transaction id. This also may be an instance of a {@User}. - * @param {boolean} admin - Indicates that this instance will be used for administrative transactions. - */ + * Builds a new transaction Id based on a user's certificate and an automatically + * generates a nonce value. + * @param {Identity} signer_or_userContext - An instance of {@link Identity} that provides an unique + * base for this transaction id. This also may be an instance of a {@User}. + * @param {boolean} admin - Indicates that this instance will be used for administrative transactions. + */ constructor(signer_or_userContext, admin) { logger.debug('constructor - start'); if (!signer_or_userContext) { @@ -51,22 +50,22 @@ class TransactionID { } /** - * The transaction ID - */ + * The transaction ID + */ getTransactionID() { return this._transaction_id; } /** - * The nonce value - */ + * The nonce value + */ getNonce() { return this._nonce; } /** - * indicates if this transactionID was generated for an admin - */ + * indicates if this transactionID was generated for an admin + */ isAdmin() { if (this._admin) { return true; diff --git a/fabric-client/lib/client-utils.js b/fabric-client/lib/client-utils.js index 344b0ef0a9..917e13f120 100644 --- a/fabric-client/lib/client-utils.js +++ b/fabric-client/lib/client-utils.js @@ -8,7 +8,7 @@ const settle = require('promise-settle'); const util = require('util'); -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('client-utils.js'); const fabprotos = require('fabric-protos'); @@ -191,7 +191,7 @@ module.exports.ccTypeToString = (ccType) => { return value; }; -/* +/* TODO move it to fabric-proto * This function will create a timestamp from the current time */ module.exports.buildCurrentTimestamp = () => { diff --git a/fabric-client/lib/impl/BasicCommitHandler.js b/fabric-client/lib/impl/BasicCommitHandler.js index badbaeb9d8..a518db2939 100644 --- a/fabric-client/lib/impl/BasicCommitHandler.js +++ b/fabric-client/lib/impl/BasicCommitHandler.js @@ -7,7 +7,7 @@ 'use strict'; -const utils = require('../utils'); +const {Utils: utils} = require('fabric-common'); const Constants = require('../Constants.js'); const CommitHandler = require('../CommitHandler'); const logger = utils.getLogger('BasicCommitHandler'); @@ -110,7 +110,7 @@ class BasicCommitHandler extends CommitHandler { for (const orderer of orderers) { logger.debug('%s - starting orderer %s', method, orderer.getName()); try { - const results = await orderer.sendBroadcast(envelope, timeout); + const results = await orderer.sendBroadcast(envelope, timeout); if (results) { if (results.status === 'SUCCESS') { logger.debug('%s - Successfully sent transaction to the orderer %s', method, orderer.getName()); @@ -140,5 +140,4 @@ class BasicCommitHandler extends CommitHandler { } - module.exports = BasicCommitHandler; diff --git a/fabric-client/lib/impl/BasicProverHandler.js b/fabric-client/lib/impl/BasicProverHandler.js index 31f8a09ee4..a0269af923 100755 --- a/fabric-client/lib/impl/BasicProverHandler.js +++ b/fabric-client/lib/impl/BasicProverHandler.js @@ -8,7 +8,7 @@ 'use strict'; const token_utils = require('../token-utils'); -const utils = require('../utils'); +const {Utils: utils} = require('fabric-common'); const Constants = require('../Constants.js'); const ProverHandler = require('../ProverHandler'); const logger = utils.getLogger('BasicProverHandler'); diff --git a/fabric-client/lib/impl/DiscoveryEndorsementHandler.js b/fabric-client/lib/impl/DiscoveryEndorsementHandler.js index ccf02a2913..a68dbdbaa4 100644 --- a/fabric-client/lib/impl/DiscoveryEndorsementHandler.js +++ b/fabric-client/lib/impl/DiscoveryEndorsementHandler.js @@ -10,7 +10,7 @@ const Long = require('long'); const util = require('util'); -const utils = require('../utils'); +const {Utils: utils} = require('fabric-common'); const EndorsementHandler = require('../EndorsementHandler'); const logger = utils.getLogger('DiscoveryEndorsementHandler'); const client_utils = require('fabric-client/lib/client-utils.js'); @@ -315,6 +315,7 @@ class DiscoveryEndorsementHandler extends EndorsementHandler { } }); } + /* * utility method that will take a group of peers and modify the order * of the peers within the group based on the user's requirements @@ -459,7 +460,7 @@ class DiscoveryEndorsementHandler extends EndorsementHandler { return result; } - logger.debug('%s - compare not available (%s) (%s)', method, typeof(a.ledger_height), typeof(b.ledger_height)); + logger.debug('%s - compare not available (%s) (%s)', method, typeof (a.ledger_height), typeof (b.ledger_height)); return 1; }); diff --git a/fabric-client/lib/impl/NetworkConfig_1_0.js b/fabric-client/lib/impl/NetworkConfig_1_0.js index 6d9f481d36..054912d2f8 100644 --- a/fabric-client/lib/impl/NetworkConfig_1_0.js +++ b/fabric-client/lib/impl/NetworkConfig_1_0.js @@ -9,7 +9,7 @@ const fs = require('fs-extra'); const path = require('path'); -const utils = require('../utils'); +const {Utils: utils} = require('fabric-common'); const Constants = require('../Constants.js'); const Channel = require('../Channel.js'); const Organization = require('../Organization.js'); @@ -191,8 +191,8 @@ const NetworkConfig_1_0 = class { return; } if (opts && this.hasClient() && - this._network_config.client.connection && - this._network_config.client.connection.timeout) { + this._network_config.client.connection && + this._network_config.client.connection.timeout) { const timeouts = this._network_config.client.connection.timeout; let timeout = ''; if (type === ENDORSER && timeouts.peer && timeouts.peer.endorser) { @@ -244,6 +244,7 @@ const NetworkConfig_1_0 = class { } } } + getOrganization(name, only_client) { const method = 'getOrganization'; logger.debug('%s - name %s', method, name); diff --git a/fabric-client/lib/msp/msp-manager.js b/fabric-client/lib/msp/msp-manager.js index 14c9acbd85..75ea237d86 100755 --- a/fabric-client/lib/msp/msp-manager.js +++ b/fabric-client/lib/msp/msp-manager.js @@ -10,8 +10,7 @@ const util = require('util'); const fabprotos = require('fabric-protos'); -const MSP = require('./msp.js'); -const utils = require('../utils.js'); +const {Utils: utils, MSP} = require('fabric-common'); const logger = utils.getLogger('MSPManager.js'); /** @@ -86,7 +85,7 @@ const MSPManager = class { intermediateCerts: fabricConfig.getIntermediateCerts(), admins: fabricConfig.getAdmins(), id: fabricConfig.getName(), - orgs : orgs, + orgs: orgs, cryptoSuite: cs, tls_root_certs: fabricConfig.getTlsRootCerts(), tls_intermediate_certs: fabricConfig.getTlsIntermediateCerts() @@ -101,15 +100,15 @@ const MSPManager = class { * Create and add MSP instance to this manager according to configuration information * @param {Object} config A configuration object specific to the implementation. For this * implementation it uses the following fields: - *
`rootCerts`: array of {@link Identity} representing trust anchors for validating + *
`rootCerts`: array of {@link Identity} representing trust anchors for validating * signing certificates. Required for MSPs used in verifying signatures - *
`intermediateCerts`: array of {@link Identity} representing trust anchors for validating + *
`intermediateCerts`: array of {@link Identity} representing trust anchors for validating * signing certificates. optional for MSPs used in verifying signatures - *
`admins`: array of {@link Identity} representing admin privileges - *
`signer`: {@link SigningIdentity} signing identity. Required for MSPs used in signing - *
`id`: {string} value for the identifier of this instance - *
`orgs`: {string} array of organizational unit identifiers - *
`cryptoSuite': the underlying {@link module:api.CryptoSuite} for crypto primitive operations + *
`admins`: array of {@link Identity} representing admin privileges + *
`signer`: {@link SigningIdentity} signing identity. Required for MSPs used in signing + *
`id`: {string} value for the identifier of this instance + *
`orgs`: {string} array of organizational unit identifiers + *
`cryptoSuite': the underlying {@link module:api.CryptoSuite} for crypto primitive operations *@return {MSP} The newly created MSP instance */ addMSP(config) { diff --git a/fabric-client/lib/packager/BasePackager.js b/fabric-client/lib/packager/BasePackager.js index 25d7792790..f9da91babd 100644 --- a/fabric-client/lib/packager/BasePackager.js +++ b/fabric-client/lib/packager/BasePackager.js @@ -20,7 +20,7 @@ const klaw = require('klaw'); const tar = require('tar-stream'); const path = require('path'); const zlib = require('zlib'); -const utils = require('../utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('packager/BasePackager.js'); @@ -31,7 +31,7 @@ const BasePackager = class { * * @param {*} [keep] Array of valid source file extensions */ - constructor (keep) { + constructor(keep) { if (this.constructor === BasePackager) { // BasePackager can not be constructed. throw new TypeError('Can not construct abstract class.'); @@ -50,7 +50,7 @@ const BasePackager = class { * @param chaincodePath * @param metadataPath */ - package (chaincodePath, metadataPath) { + package(chaincodePath, metadataPath) { throw new TypeError('Please implement method package from child class'); } @@ -60,7 +60,7 @@ const BasePackager = class { * * @param filepath */ - findSource (filepath) { + findSource(filepath) { throw new Error('abstract function called'); } @@ -71,7 +71,7 @@ const BasePackager = class { * Only files with a ".json" extension will be included in the results. * @returns {Promise} */ - findMetadataDescriptors (filePath) { + findMetadataDescriptors(filePath) { return new Promise((resolve, reject) => { logger.debug('findMetadataDescriptors : start'); const descriptors = []; @@ -104,7 +104,7 @@ const BasePackager = class { * @param filePath The top-level directory containing the metadata descriptors. * @returns {boolean} Returns true for valid metadata descriptors. */ - isMetadata (filePath) { + isMetadata(filePath) { const extensions = ['.json']; return (extensions.indexOf(path.extname(filePath)) !== -1); } @@ -117,7 +117,7 @@ const BasePackager = class { * @param filePath * @returns {boolean} */ - isSource (filePath) { + isSource(filePath) { return (this.keep.indexOf(path.extname(filePath)) !== -1); } @@ -129,7 +129,7 @@ const BasePackager = class { * @param desc * @returns {Promise} */ - packEntry (pack, desc) { + packEntry(pack, desc) { return new Promise((resolve, reject) => { // Use a synchronous read to reduce non-determinism const content = fs.readFileSync(desc.fqp); @@ -165,7 +165,7 @@ const BasePackager = class { * @param dest * @returns {Promise} */ - generateTarGz (descriptors, dest) { + generateTarGz(descriptors, dest) { return new Promise((resolve, reject) => { const pack = tar.pack(); // Setup the pipeline to compress on the fly and resolve/reject the promise diff --git a/fabric-client/lib/packager/Car.js b/fabric-client/lib/packager/Car.js index 1b831e3f31..c2e56b4653 100644 --- a/fabric-client/lib/packager/Car.js +++ b/fabric-client/lib/packager/Car.js @@ -14,7 +14,7 @@ 'use strict'; -const utils = require('../utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('packager/Car.js'); const fs = require('fs-extra'); diff --git a/fabric-client/lib/packager/Golang.js b/fabric-client/lib/packager/Golang.js index 2f21cdb7f7..8ab620fc9f 100644 --- a/fabric-client/lib/packager/Golang.js +++ b/fabric-client/lib/packager/Golang.js @@ -17,7 +17,8 @@ const klaw = require('klaw'); const path = require('path'); const sbuf = require('stream-buffers'); -const utils = require('../utils.js'); +const {Utils: utils} = require('fabric-common'); + const BasePackager = require('./BasePackager'); const logger = utils.getLogger('packager/Golang.js'); @@ -31,7 +32,7 @@ class GolangPackager extends BasePackager { * @param {string} [metadataPath] The path to the top-level directory containing metadata descriptors. * @returns {Promise.} */ - package (chaincodePath, metadataPath) { + package(chaincodePath, metadataPath) { logger.debug('packaging GOLANG from %s', chaincodePath); // Determine the user's $GOPATH @@ -72,7 +73,7 @@ class GolangPackager extends BasePackager { * @param filePath * @returns {Promise} */ - findSource (goPath, filePath) { + findSource(goPath, filePath) { return new Promise((resolve, reject) => { const descriptors = []; klaw(filePath) diff --git a/fabric-client/lib/packager/Java.js b/fabric-client/lib/packager/Java.js index dd0779de36..7581db6e12 100644 --- a/fabric-client/lib/packager/Java.js +++ b/fabric-client/lib/packager/Java.js @@ -16,7 +16,8 @@ const path = require('path'); const sbuf = require('stream-buffers'); -const utils = require('../utils.js'); +const {Utils: utils} = require('fabric-common'); + const walk = require('ignore-walk'); const logger = utils.getLogger('JavaPackager.js'); @@ -31,7 +32,7 @@ class JavaPackager extends BasePackager { * @param {string} [metadataPath] The path to the top-level directory containing metadata descriptors * @returns {Promise.} */ - async package (chaincodePath, metadataPath) { + async package(chaincodePath, metadataPath) { logger.debug('packaging Java source from %s', chaincodePath); const buffer = new sbuf.WritableStreamBuffer(); @@ -55,7 +56,7 @@ class JavaPackager extends BasePackager { * @param filePath * @returns {Promise} */ - async findSource (filePath) { + async findSource(filePath) { const descriptors = []; const files = await walk({path: filePath, follow: true}); diff --git a/fabric-client/lib/packager/Node.js b/fabric-client/lib/packager/Node.js index 37a1e4ac40..ab1029471d 100644 --- a/fabric-client/lib/packager/Node.js +++ b/fabric-client/lib/packager/Node.js @@ -16,7 +16,8 @@ const path = require('path'); const sbuf = require('stream-buffers'); -const utils = require('../utils.js'); +const {Utils: utils} = require('fabric-common'); + const walk = require('ignore-walk'); const logger = utils.getLogger('packager/Node.js'); @@ -32,7 +33,7 @@ class NodePackager extends BasePackager { * @param {string} [metadataPath] The path to the top-level directory containing metadata descriptors * @returns {Promise.} */ - package (chaincodePath, metadataPath) { + package(chaincodePath, metadataPath) { logger.debug('packaging Node from %s', chaincodePath); // Compose the path to the chaincode project directory @@ -67,7 +68,7 @@ class NodePackager extends BasePackager { * @param filePath * @returns {Promise} */ - findSource (filePath) { + findSource(filePath) { return walk({ path: filePath, // applies filtering based on the same rules as "npm publish": diff --git a/fabric-client/lib/token-utils.js b/fabric-client/lib/token-utils.js index c042577155..f2caf63eb0 100644 --- a/fabric-client/lib/token-utils.js +++ b/fabric-client/lib/token-utils.js @@ -16,7 +16,7 @@ const util = require('util'); const client_utils = require('./client-utils.js'); -const utils = require('./utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('token-utils.js'); const fabprotos = require('fabric-protos'); diff --git a/fabric-client/lib/utils/format.js b/fabric-client/lib/utils/format.js new file mode 100644 index 0000000000..89b7c768b4 --- /dev/null +++ b/fabric-client/lib/utils/format.js @@ -0,0 +1,30 @@ +const Long = require('long'); + +/* + * Converts to a Long number + * Returns a null if the incoming value is not a string that represents a + * number or an actual javascript number. Also allows for a Long object to be + * passed in as the value to convert + */ +module.exports.convertToLong = (value) => { + let result; + if (Long.isLong(value)) { + result = value; // already a long + } else if (typeof value !== 'undefined' && value !== null) { + result = Long.fromValue(value); + // Long will return a zero for invalid strings so make sure we did + // not get a real zero as the incoming value + if (result.equals(Long.ZERO)) { + if (Number.isInteger(value) || value === '0') { + // all good + } else { + // anything else must be a string that is not a valid number + throw new Error(`value:${value} is not a valid number `); + } + } + } else { + throw new Error('value parameter is missing'); + } + + return result; +}; diff --git a/fabric-client/package.json b/fabric-client/package.json index af162b168c..44b7e96f74 100644 --- a/fabric-client/package.json +++ b/fabric-client/package.json @@ -28,7 +28,6 @@ "fabric-common": "file:../fabric-common", "fabric-protos": "file:../fabric-protos", "fs-extra": "^6.0.1", - "grpc": "1.17.0", "hoek": "^4.2.1", "ignore-walk": "^3.0.0", "js-sha3": "^0.7.0", @@ -41,11 +40,9 @@ "nconf": "^0.10.0", "pkcs11js": "^1.0.6", "promise-settle": "^0.3.0", - "sjcl": "1.0.7", "stream-buffers": "3.0.1", "tar-stream": "1.6.1", - "url": "^0.11.0", - "winston": "^2.2.0" + "url": "^0.11.0" }, "devDependencies": { "chai": "^4.1.2", diff --git a/fabric-client/test/BaseClient.js b/fabric-client/test/BaseClient.js index d6ddad4a47..44c776b53a 100644 --- a/fabric-client/test/BaseClient.js +++ b/fabric-client/test/BaseClient.js @@ -15,8 +15,8 @@ 'use strict'; const rewire = require('rewire'); -const BaseClientRewire = rewire('../lib/BaseClient'); -const BaseClient = require('../lib/BaseClient'); +const {BaseClient} = require('fabric-common'); +const BaseClientRewire = rewire('fabric-common/lib/BaseClient'); const chai = require('chai'); const sinon = require('sinon'); diff --git a/fabric-client/test/Channel.js b/fabric-client/test/Channel.js index dcd97d9070..81c19120f9 100644 --- a/fabric-client/test/Channel.js +++ b/fabric-client/test/Channel.js @@ -1,15 +1,5 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; @@ -29,13 +19,11 @@ const ChannelEventHub = require('fabric-client/lib/ChannelEventHub'); const Chaincode = require('fabric-client/lib/Chaincode'); const Client = require('fabric-client/lib/Client'); const Constants = require('fabric-client/lib/Constants'); -const {Identity, SigningIdentity} = require('fabric-common'); -const MSP = require('fabric-client/lib/msp/msp'); +const {Identity, SigningIdentity, Utils: sdk_utils, MSP} = require('fabric-common'); const MSPManager = require('fabric-client/lib/msp/msp-manager'); const Orderer = require('fabric-client/lib/Orderer'); const Peer = require('fabric-client/lib/Peer'); const TransactionID = require('fabric-client/lib/TransactionID'); -const sdk_utils = require('fabric-client/lib/utils.js'); const fabprotos = require('fabric-protos'); const responseProto = fabprotos.protos; @@ -74,12 +62,14 @@ describe('Channel', () => { beforeEach(() => { const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; const FakePolicy = { - buildPolicy :buildPolicyStub + buildPolicy: buildPolicyStub }; debugStub = sinon.stub(FakeLogger, 'debug'); @@ -669,7 +659,7 @@ describe('Channel', () => { request = { fcn: 'functionName', args: ['a', 'b', 'c'], - chaincodeId: 'chaincode-id', + chaincodeId: 'chaincode-id' }; }); @@ -970,7 +960,7 @@ describe('Channel', () => { getConfigSettingStub.callThrough(); const request = { - target: peer1, + target: peer1 }; return expect(channel.initialize(request)).to.be.fulfilled; }); @@ -1014,17 +1004,26 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1032,44 +1031,78 @@ describe('Channel', () => { const init = await channel.initialize({discover: true, target: peer1}); sinon.assert.calledWith(getClientCertHash, true); sinon.assert.calledWith(setClientTlsCertHashStub, 'hash'); - expect(init.orderers).to.deep.equal({[mspId]: {endpoints: [{name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}); + expect(init.orderers).to.deep.equal({ + [mspId]: { + endpoints: [{ + name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, + host: orderer1._endpoint.addr, + port: orderer1._endpoint.port + }] + } + }); }); it('finds orderers', async () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); const init = await channel.initialize({discover: true, target: peer1}); - expect(init.orderers).to.deep.equal({[mspId]: {endpoints: [{name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}); + expect(init.orderers).to.deep.equal({ + [mspId]: { + endpoints: [{ + name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, + host: orderer1._endpoint.addr, + port: orderer1._endpoint.port + }] + } + }); }); it('sets discovery interests', async () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: {msps: {[mspId]: stubMsp}}, - members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, + members: {peers_by_org: {[mspId]: {peers: [peer2]}}} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1083,20 +1116,31 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: {msps: {[mspId]: stubMsp}}, members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, - cc_query_res: {content: [{ - chaincode: {name: 'mynewcc'}, - endorsers_by_groups: {group1: {peers: [peer2]}}, - layouts: [{quantities_by_group: ['layout']}] - }]} + cc_query_res: { + content: [{ + chaincode: {name: 'mynewcc'}, + endorsers_by_groups: {group1: {peers: [peer2]}}, + layouts: [{quantities_by_group: ['layout']}] + }] + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1127,7 +1171,16 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ @@ -1136,7 +1189,7 @@ describe('Channel', () => { members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, cc_query_res: {} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1148,7 +1201,16 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ @@ -1157,7 +1219,7 @@ describe('Channel', () => { members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, cc_query_res: {content: 'not an array'} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1215,15 +1277,20 @@ describe('Channel', () => { }); }); - describe('#_initialize', () => {}); + describe('#_initialize', () => { + }); - describe('_buildDiscoveryMSPs', () => {}); + describe('_buildDiscoveryMSPs', () => { + }); - describe('#_buildDiscoveryOrderers', () => {}); + describe('#_buildDiscoveryOrderers', () => { + }); - describe('#_buildDiscoveryPeers', () => {}); + describe('#_buildDiscoveryPeers', () => { + }); - describe('#_buildDiscoveryEndorsementPlan', () => {}); + describe('#_buildDiscoveryEndorsementPlan', () => { + }); describe('#_discover', () => { }); @@ -1233,7 +1300,7 @@ describe('Channel', () => { const discoveryResponse = { interests: [{name: 'mycc'}], peer: peer1, - results: [{config_result: {msps: {[mspId]: stubMsp}}}], + results: [{config_result: {msps: {[mspId]: stubMsp}}}] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1247,7 +1314,7 @@ describe('Channel', () => { orgs: mspId, rootCerts: 'root-certs', tls_intermediate_certs: 'tls_intermediate_certs', - tls_root_certs: 'tls_root_certs', + tls_root_certs: 'tls_root_certs' } }); expect(discoveryResults.orders).to.be.undefined; @@ -1291,33 +1358,47 @@ describe('Channel', () => { }); }); - describe('#getOrganizations', () => {}); + describe('#getOrganizations', () => { + }); - describe('#setMSPManager', () => {}); + describe('#setMSPManager', () => { + }); - describe('#getMSPManager', () => {}); + describe('#getMSPManager', () => { + }); - describe('#addPeer', () => {}); + describe('#addPeer', () => { + }); - describe('#removePeer', () => {}); + describe('#removePeer', () => { + }); - describe('#gePeer', () => {}); + describe('#gePeer', () => { + }); - describe('#getChannelPeers', () => {}); + describe('#getChannelPeers', () => { + }); - describe('#addOrderer', () => {}); + describe('#addOrderer', () => { + }); - describe('#removeOrderer', () => {}); + describe('#removeOrderer', () => { + }); - describe('#getOrderer', () => {}); + describe('#getOrderer', () => { + }); - describe('#getOrderers', () => {}); + describe('#getOrderers', () => { + }); - describe('#newChannelEventHub', () => {}); + describe('#newChannelEventHub', () => { + }); - describe('#getChannelEventHub', () => {}); + describe('#getChannelEventHub', () => { + }); - describe('#getChannelEventHubsForOrg', () => {}); + describe('#getChannelEventHubsForOrg', () => { + }); describe('#getGenesisBlock', () => { @@ -1325,23 +1406,40 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer3); const init = await channel.initialize({discover: true, target: peer1}); - expect(init.orderers).to.deep.equal({[mspId]: {endpoints: [{name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}); + expect(init.orderers).to.deep.equal({ + [mspId]: { + endpoints: [{ + name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, + host: orderer1._endpoint.addr, + port: orderer1._endpoint.port + }] + } + }); orderer3.sendDeliver.returns('genesis-block'); const block = await channel.getGenesisBlock(); sinon.assert.called(channel._clientContext.getTargetOrderer); @@ -1355,23 +1453,40 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer3); const init = await channel.initialize({discover: true, target: peer1}); - expect(init.orderers).to.deep.equal({[mspId]: {endpoints: [{name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}); + expect(init.orderers).to.deep.equal({ + [mspId]: { + endpoints: [{ + name: `${orderer1._endpoint.addr}:${orderer1._endpoint.port}`, + host: orderer1._endpoint.addr, + port: orderer1._endpoint.port + }] + } + }); orderer3.sendDeliver.returns('genesis-block'); const txId = client.newTransactionID(); const block = await channel.getGenesisBlock({txId}); @@ -1395,10 +1510,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1413,18 +1528,27 @@ describe('Channel', () => { peer2.identity = new identityProto.SerializedIdentity({mspid: mspId}).toBuffer(); peer2.membership_info = {payload: new gossipProto.GossipMessage({alive_msg: {membership: {endpoint: peer2.getUrl()}}}).toBuffer()}; peer2.chaincodes = [{name: 'mynewcc'}]; - peer2.state_info = {payload: new gossipProto.GossipMessage({state_info: {properties: {ledger_height: 1, chaincodes: [{name: 'mynewcc'}]}}}).toBuffer()}; + peer2.state_info = { + payload: new gossipProto.GossipMessage({ + state_info: { + properties: { + ledger_height: 1, + chaincodes: [{name: 'mynewcc'}] + } + } + }).toBuffer() + }; const discoveryResponse = { peer: peer1, results: [ { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} }, - members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, + members: {peers_by_org: {[mspId]: {peers: [peer2]}}} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1443,10 +1567,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1507,7 +1631,7 @@ describe('Channel', () => { it('should not thow if no config_result is given', () => { const discoveryResponse = { peer: peer1, - results: [{}], + results: [{}] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1518,7 +1642,7 @@ describe('Channel', () => { it('should not error given an empty result.config_result', () => { const discoveryResponse = { peer: peer1, - results: [{config_result: null}], + results: [{config_result: null}] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1529,7 +1653,7 @@ describe('Channel', () => { it('should not error given an empty result.config_result.msps', () => { const discoveryResponse = { peer: peer1, - results: [{config_result: {}}], + results: [{config_result: {}}] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1540,9 +1664,11 @@ describe('Channel', () => { it('should throw if anything errors whilst building the discovery config', () => { const discoveryResponse = { peer: peer1, - results: [{config_result: { - msps: {[mspId]: {}} - }}], + results: [{ + config_result: { + msps: {[mspId]: {}} + } + }] }; debugStub.withArgs('%s - found organization %s', '_processDiscoveryConfigResults', 'org1').callsFake(() => { throw new Error('forced error'); @@ -1561,9 +1687,9 @@ describe('Channel', () => { config_result: { msps: {[mspId]: {}} }, - members: {peers_by_org: null}, + members: {peers_by_org: null} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1582,11 +1708,11 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} }, - members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, + members: {peers_by_org: {[mspId]: {peers: [peer2]}}} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1606,11 +1732,11 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}}, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} }, - members: {peers_by_org: {[mspId]: {peers: [peer2]}}}, + members: {peers_by_org: {[mspId]: {peers: [peer2]}}} } - ], + ] }; sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -1620,15 +1746,20 @@ describe('Channel', () => { }); }); - describe('#_processDiscoveryChaincodeResults', () => {}); + describe('#_processDiscoveryChaincodeResults', () => { + }); - describe('#_processDiscoveryResults', () => {}); + describe('#_processDiscoveryResults', () => { + }); - describe('#_processDiscoveryMembershipResults', () => {}); + describe('#_processDiscoveryMembershipResults', () => { + }); - describe('#_processPeers', () => {}); + describe('#_processPeers', () => { + }); - describe('#_processPeers', () => {}); + describe('#_processPeers', () => { + }); describe('#_buildOrdererName', () => { @@ -2056,15 +2187,26 @@ describe('Channel', () => { }); it('should throw if targets is missing', () => { - expect(() => channel.joinChannel({txId: 1, block: 'something'})).to.throw(/"targets" parameter not specified and no peers are set on this Channel instance or specfied for this channel in the network/); + expect(() => channel.joinChannel({ + txId: 1, + block: 'something' + })).to.throw(/"targets" parameter not specified and no peers are set on this Channel instance or specfied for this channel in the network/); }); it('should throw if invalid target', () => { - expect(() => channel.joinChannel({txId: 1, block: 'something', targets: [{}]})).to.throw(/Target peer is not a valid peer object instance/); + expect(() => channel.joinChannel({ + txId: 1, + block: 'something', + targets: [{}] + })).to.throw(/Target peer is not a valid peer object instance/); }); it('should throw if not existing target', () => { - expect(() => channel.joinChannel({txId: 1, block: 'something', targets: 'penguin'})).to.throw(/Peer with name "penguin" not assigned to this channel/); + expect(() => channel.joinChannel({ + txId: 1, + block: 'something', + targets: 'penguin' + })).to.throw(/Peer with name "penguin" not assigned to this channel/); }); it('should be rejected is sendPeersProposal fails', async () => { @@ -2077,7 +2219,7 @@ describe('Channel', () => { const request = { txId: client.newTransactionID(), block: {toBuffer: () => new Buffer('{}')}, - targets: [peer1], + targets: [peer1] }; const res = await channel.joinChannel(request); expect(res).to.deep.equal([err]); @@ -2111,10 +2253,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer1); sinon.stub(orderer1, 'sendDeliver').returns(null); @@ -2132,10 +2274,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer1); sinon.stub(orderer1, 'sendDeliver').onCall(0).returns({ @@ -2145,7 +2287,8 @@ describe('Channel', () => { null, commonProto.Metadata.encode('{value: []}') ] - }}); + } + }); orderer1.sendDeliver.onCall(1).returns(null); sinon.stub(peer1, 'waitForReady').resolves(); sinon.stub(peer1._discoveryClient, 'discover').callsArgWith(1, null, discoveryResponse); @@ -2161,10 +2304,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer1); sinon.stub(orderer1, 'sendDeliver').onCall(0).returns({ @@ -2174,7 +2317,8 @@ describe('Channel', () => { null, commonProto.Metadata.encode('{value: []}') ] - }}); + } + }); orderer1.sendDeliver.onCall(1).returns({ header: {number: 1}, data: {data: []} @@ -2193,10 +2337,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer1); sinon.stub(orderer1, 'sendDeliver').onCall(0).returns({ @@ -2206,7 +2350,8 @@ describe('Channel', () => { null, commonProto.Metadata.encode('{value: []}') ] - }}); + } + }); const envelope = new commonProto.Envelope(); const payload = new commonProto.Payload(); const header = new commonProto.Header(); @@ -2237,10 +2382,10 @@ describe('Channel', () => { { config_result: { msps: {[mspId]: stubMsp}, - orderers: {[mspId]: {endpoint:[{host:orderer1._endpoint.addr, port:orderer1._endpoint.port}]}} - }, + orderers: {[mspId]: {endpoint: [{host: orderer1._endpoint.addr, port: orderer1._endpoint.port}]}} + } } - ], + ] }; sinon.stub(channel._clientContext, 'getTargetOrderer').returns(orderer1); sinon.stub(orderer1, 'sendDeliver').onCall(0).returns({ @@ -2250,7 +2395,8 @@ describe('Channel', () => { null, commonProto.Metadata.encode('{value: []}') ] - }}); + } + }); const envelope = new commonProto.Envelope(); const payload = new commonProto.Payload(); const header = new commonProto.Header(); @@ -2262,7 +2408,7 @@ describe('Channel', () => { tx_id: 'tx_id', epoch: 1, extension: '', - tls_cert_hash:'' + tls_cert_hash: '' }); const data = new configtxProto.ConfigEnvelope(); data.setConfig({}); @@ -2678,13 +2824,30 @@ describe('Channel', () => { }); const response = await channel.queryInstantiatedChaincodes(peer1); sinon.match({ - 'chaincodes':[ - {'name':'mycc', 'version':'', 'path':'', 'input':'', 'escc':'', 'vscc':'', 'id':{'buffer': sinon.match.instanceOf(Buffer), 'offset':0, 'markedOffset':-1, 'limit':0, 'littleEndian':false, 'noAssert':false}} - ]}).test(response); + 'chaincodes': [ + { + 'name': 'mycc', + 'version': '', + 'path': '', + 'input': '', + 'escc': '', + 'vscc': '', + 'id': { + 'buffer': sinon.match.instanceOf(Buffer), + 'offset': 0, + 'markedOffset': -1, + 'limit': 0, + 'littleEndian': false, + 'noAssert': false + } + } + ] + }).test(response); }); }); - describe('#queryCollectionsConfig', () => {}); + describe('#queryCollectionsConfig', () => { + }); describe('#sendInstantiateProposal', () => { it('should call _sendChaincodeProposal', () => { @@ -2919,7 +3082,8 @@ describe('Channel', () => { }); - describe('Channel.sendTransactionProposal', () => {}); + describe('Channel.sendTransactionProposal', () => { + }); describe('#sendTransaction', () => { @@ -2936,14 +3100,19 @@ describe('Channel', () => { }); it('should throw if no endorsements in request object', () => { - return expect(channel.sendTransaction({proposal: 'blah', proposalResponses: {response: {status: 500}}})).to.be.rejectedWith('no valid endorsements found'); + return expect(channel.sendTransaction({ + proposal: 'blah', + proposalResponses: {response: {status: 500}} + })).to.be.rejectedWith('no valid endorsements found'); }); }); - describe('#sendSignedTransation', () => {}); + describe('#sendSignedTransation', () => { + }); - describe('#buildEnvelope', () => {}); + describe('#buildEnvelope', () => { + }); describe('#queryByChaincode', () => { const peer1Result = 'PEER1_RESULT'; @@ -3036,11 +3205,14 @@ describe('Channel', () => { }); }); - describe('#_getTargetForQuery', () => {}); + describe('#_getTargetForQuery', () => { + }); - describe('#_getTargetForDiscovery', () => {}); + describe('#_getTargetForDiscovery', () => { + }); - describe('#_getTargets', () => {}); + describe('#_getTargets', () => { + }); describe('#_getOrderer', () => { @@ -3080,11 +3252,14 @@ describe('Channel', () => { }); - describe('#_getProposalResponseResults', () => {}); + describe('#_getProposalResponseResults', () => { + }); - describe('#loadConfigGroup', () => {}); + describe('#loadConfigGroup', () => { + }); - describe('#loadConfigValue', () => {}); + describe('#loadConfigValue', () => { + }); describe('#sendTokenCommand(static)', () => { let sandbox; @@ -3103,8 +3278,10 @@ describe('Channel', () => { beforeEach(() => { const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; debugStub = sinon.stub(FakeLogger, 'debug'); @@ -3155,7 +3332,7 @@ describe('Channel', () => { } }); - it('should throw an error if sendTokenCommandToPeer fails', async () => { + it('should throw an error if sendTokenCommandToPeer fails', async () => { try { const fakeError = new Error('forced send command error'); sendTokenCommandToPeerStub.throws(fakeError); @@ -3184,8 +3361,10 @@ describe('Channel', () => { beforeEach(() => { const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; debugStub = sinon.stub(FakeLogger, 'debug'); @@ -3307,8 +3486,10 @@ describe('Channel', () => { beforeEach(() => { const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; debugStub = sinon.stub(FakeLogger, 'debug'); @@ -3420,8 +3601,10 @@ describe('Channel', () => { beforeEach(() => { const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; debugStub = sinon.stub(FakeLogger, 'debug'); @@ -3551,8 +3734,10 @@ describe('Channel', () => { beforeEach(() => { const FakeLogger = { - debug : () => {}, - error: () => {} + debug: () => { + }, + error: () => { + } }; debugStub = sinon.stub(FakeLogger, 'debug'); diff --git a/fabric-client/test/ChannelEventHub.js b/fabric-client/test/ChannelEventHub.js index aace9c013c..1402e34c32 100644 --- a/fabric-client/test/ChannelEventHub.js +++ b/fabric-client/test/ChannelEventHub.js @@ -39,9 +39,12 @@ describe('ChannelEventHub', () => { sandbox = sinon.createSandbox(); FakeLogger = { - debug : () => {}, - error: () => {}, - warn: () => {} + debug: () => { + }, + error: () => { + }, + warn: () => { + } }; sandbox.stub(FakeLogger); revert.push(ChannelEventHub.__set__('logger', FakeLogger)); @@ -267,7 +270,7 @@ describe('ChannelEventHub', () => { }); describe('#_checkAllowRegistrations', () => { - it ('should throw an error if registration is not allowed', () => { + it('should throw an error if registration is not allowed', () => { const hub = new ChannelEventHub('channel', 'peer'); hub._start_stop_registration = true; (() => { @@ -275,7 +278,7 @@ describe('ChannelEventHub', () => { }).should.throw(/This ChannelEventHub is not open to event listener registrations/); }); - it ('should not throw an error if registration is allowed', () => { + it('should not throw an error if registration is allowed', () => { const hub = new ChannelEventHub('channel', 'peer'); hub._allowRegistration = true; (() => { @@ -411,7 +414,6 @@ describe('ChannelEventHub', () => { }); describe('#_connect', () => { - let convertToLongStub; let _shutdownStub; let _disconnectStub; let setTimeoutStub; @@ -429,8 +431,6 @@ describe('ChannelEventHub', () => { let hub; beforeEach(() => { - convertToLongStub = sandbox.stub(); - revert.push(ChannelEventHub.__set__('utils.convertToLong', convertToLongStub)); isStreamReadyStub = sandbox.stub(); revert.push(ChannelEventHub.__set__('isStreamReady', isStreamReadyStub)); _sendSignedRegistrationStub = sandbox.stub(); @@ -644,10 +644,8 @@ describe('ChannelEventHub', () => { isStreamReadyStub.returns(true); onStub.yields({Type: 'block'}); decodeBlockStub.returns({header: {number: 1}}); - convertToLongStub.returns(1); hub._connect({signedEvent: true}); - sinon.assert.calledWith(convertToLongStub, 1); - hub._last_block_seen.should.equal(1); + hub._last_block_seen.should.deep.equal(Long.fromInt(1)); }); it('should parse a filtered block and update _last_seen_block', () => { @@ -656,11 +654,9 @@ describe('ChannelEventHub', () => { checkAndAddConfigSettingStub.onCall(2).returns({}); getConfigSettingStub.withArgs('request-timeout', 3000).returns(1000); isStreamReadyStub.returns(true); - convertToLongStub.returns(1); onStub.yields({Type: 'filtered_block', filtered_block: {number: 1}}); hub._connect({signedEvent: true}); - sinon.assert.calledWith(convertToLongStub, 1); - hub._last_block_seen.should.equal(1); + hub._last_block_seen.should.deep.equal(Long.fromInt(1)); }); it('should call disconnect if called with instance of Error', () => { @@ -669,7 +665,6 @@ describe('ChannelEventHub', () => { checkAndAddConfigSettingStub.onCall(2).returns({}); getConfigSettingStub.withArgs('request-timeout', 3000).returns(1000); isStreamReadyStub.returns(true); - convertToLongStub.returns(1); const error = new Error('test error'); onStub.yields(error); hub._connect({signedEvent: true}); @@ -743,7 +738,7 @@ describe('ChannelEventHub', () => { hub._setReplayDefaults = _setReplayDefaultsStub; hub.getPeerAddr = getPeerAddrStub; - hub.disconnect({message:'error'}); + hub.disconnect({message: 'error'}); sinon.assert.called(_closeAllCallbacksStub); sinon.assert.called(_shutdownStub); sinon.assert.called(_setReplayDefaultsStub); @@ -807,12 +802,12 @@ describe('ChannelEventHub', () => { hub = new ChannelEventHub('channel', 'peer'); }); - it ('should log entry', () => { + it('should log entry', () => { hub._validateSignedEvent({signature: 'signature', payload: 'payload'}); sinon.assert.calledWith(FakeLogger.debug, '%s - enter', '_validateSignedEvent'); }); - it ('should log exit', () => { + it('should log exit', () => { hub._validateSignedEvent({signature: 'signature', payload: 'payload'}); sinon.assert.calledWith(FakeLogger.debug, '%s - exit', '_validateSignedEvent'); }); @@ -1512,9 +1507,11 @@ describe('ChannelEventHub', () => { }); it('should throw a string and call _disconnect if _stream is not set but force_reconnect is', () => { - hub._stream = {isPaused: () => { - throw 'Error'; - }}; + hub._stream = { + isPaused: () => { + throw 'Error'; + } + }; hub.checkConnection(true); sinon.assert.called(FakeLogger.error); sinon.assert.calledWith(FakeLogger.error, 'checkConnection - error ::Error'); @@ -1522,9 +1519,11 @@ describe('ChannelEventHub', () => { }); it('should throw a string and call _disconnect if _stream is not set but force_reconnect is', () => { - hub._stream = {isPaused: () => { - throw new Error(); - }}; + hub._stream = { + isPaused: () => { + throw new Error(); + } + }; hub.checkConnection(true); sinon.assert.called(FakeLogger.error); sinon.assert.calledWithMatch(FakeLogger.error, Error); @@ -2078,7 +2077,14 @@ describe('ChannelEventHub', () => { it('should call _callChaincodeListener for every chaincode_action', () => { const mockAction = {chaincode_event: 'event'}; hub._chaincodeRegistrants = {'cc': 'val'}; - hub._processChaincodeEvents({number: 1, filtered_transactions: [{txid: 'txid', tx_validation_code: 'code', transaction_actions: {chaincode_actions: [mockAction, mockAction]}}]}); + hub._processChaincodeEvents({ + number: 1, + filtered_transactions: [{ + txid: 'txid', + tx_validation_code: 'code', + transaction_actions: {chaincode_actions: [mockAction, mockAction]} + }] + }); sinon.assert.calledTwice(_callChaincodeListenerStub); sinon.assert.calledWith(_callChaincodeListenerStub, 'event', 1, 'txid', 'code', true); }); @@ -2347,7 +2353,8 @@ describe('isStreamReady', () => { beforeEach(() => { FakeLogger = { - debug: () => {} + debug: () => { + } }; sinon.stub(FakeLogger); ChannelEventHub.__set__('logger', FakeLogger); @@ -2398,7 +2405,10 @@ describe('EventRegistration', () => { beforeEach(() => { sandbox = sinon.createSandbox(); - FakeLogger = {debug: () => {}}; + FakeLogger = { + debug: () => { + } + }; sandbox.stub(FakeLogger); ChannelEventHub.__set__('logger', FakeLogger); }); diff --git a/fabric-client/test/Client.js b/fabric-client/test/Client.js index 807c16f971..4c4e22357a 100644 --- a/fabric-client/test/Client.js +++ b/fabric-client/test/Client.js @@ -20,10 +20,9 @@ const Client = rewire('../lib/Client'); const Channel = require('../lib/Channel'); const NetworkConfig = require('../lib/impl/NetworkConfig_1_0'); const fs = require('fs'); -const {Identity} = require('fabric-common'); +const {Identity, User} = require('fabric-common'); const Package = require('../lib/Package'); const path = require('path'); -const User = require('../lib/User'); const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); @@ -46,8 +45,10 @@ describe('Client', () => { revert = []; FakeLogger = { - debug: () => { }, - error: () => { } + debug: () => { + }, + error: () => { + } }; sinon.stub(FakeLogger); revert.push(Client.__set__('logger', FakeLogger)); @@ -56,7 +57,7 @@ describe('Client', () => { const publicKey = 'FAKE_PUBLIC_KEY'; const cryptoSuite = {_name: 'FAKE_CRYPTO_SUITE'}; const identity = new Identity(certificate, publicKey, userMspId, cryptoSuite); - fakeUser = new User({name:'user'}); + fakeUser = new User({name: 'user'}); const fakeGetIdentity = sinon.fake(() => identity); sinon.replace(fakeUser, 'getIdentity', fakeGetIdentity); @@ -177,7 +178,10 @@ describe('Client', () => { beforeEach(() => { toBytesStub = sinon.stub(); generateX509CertificateStub = sinon.stub(); - generateEphemeralKeyStub = sinon.stub().returns({toBytes: toBytesStub, generateX509Certificate: generateX509CertificateStub}); + generateEphemeralKeyStub = sinon.stub().returns({ + toBytes: toBytesStub, + generateX509Certificate: generateX509CertificateStub + }); newCryptoSuiteStub = sinon.stub().returns({generateEphemeralKey: generateEphemeralKeyStub}); revert.push(Client.__set__('Client.newCryptoSuite', newCryptoSuiteStub)); getNameStub = sinon.stub(); @@ -234,7 +238,10 @@ describe('Client', () => { beforeEach(() => { toBytesStub = sinon.stub(); generateX509CertificateStub = sinon.stub(); - generateEphemeralKeyStub = sinon.stub().returns({toBytes: toBytesStub, generateX509Certificate: generateX509CertificateStub}); + generateEphemeralKeyStub = sinon.stub().returns({ + toBytes: toBytesStub, + generateX509Certificate: generateX509CertificateStub + }); newCryptoSuiteStub = sinon.stub().returns({generateEphemeralKey: generateEphemeralKeyStub}); revert.push(Client.__set__('Client.newCryptoSuite', newCryptoSuiteStub)); getNameStub = sinon.stub(); @@ -715,7 +722,12 @@ describe('Client', () => { client._buildCAfromConfig(caInfo); sinon.assert.calledWith(getConfigSettingStub, 'certificate-authority-client'); sinon.assert.calledWith(requireStub, 'class-path'); - sinon.assert.calledWith(caServiceStub, {tlsOptions: {trustedRoots: ['cert'], verify: true}, caName: 'name', cryptoSuite: null, url: 'url'}); + sinon.assert.calledWith(caServiceStub, { + tlsOptions: {trustedRoots: ['cert'], verify: true}, + caName: 'name', + cryptoSuite: null, + url: 'url' + }); }); it('should return the ca service if no certs are returned', () => { @@ -725,7 +737,12 @@ describe('Client', () => { client._buildCAfromConfig(caInfo); sinon.assert.calledWith(getConfigSettingStub, 'certificate-authority-client'); sinon.assert.calledWith(requireStub, 'class-path'); - sinon.assert.calledWith(caServiceStub, {tlsOptions: {trustedRoots: [], verify: true}, caName: 'name', cryptoSuite: null, url: 'url'}); + sinon.assert.calledWith(caServiceStub, { + tlsOptions: {trustedRoots: [], verify: true}, + caName: 'name', + cryptoSuite: null, + url: 'url' + }); }); }); @@ -911,7 +928,11 @@ describe('Client', () => { bufferFromStub = sinon.stub(); bufferIsBufferStub = sinon.stub(); signStub = sinon.stub(); - revert.push(Client.__set__('Buffer', {concat: bufferConcatStub, from: bufferFromStub, isBuffer: bufferIsBufferStub})); + revert.push(Client.__set__('Buffer', { + concat: bufferConcatStub, + from: bufferFromStub, + isBuffer: bufferIsBufferStub + })); ConfigSignatureStub = sinon.stub(); revert.push(Client.__set__('fabprotos.common.ConfigSignature', ConfigSignatureStub)); setSignatureHeaderStub = sinon.stub(); @@ -1038,7 +1059,11 @@ describe('Client', () => { setConfigUpdateStub = sinon.stub(); _stringToSignatureStub = sinon.stub().returns('signatures'); setSignaturesStub = sinon.stub(); - ConfigUpdateEnvelopeStub.returns({setConfigUpdate: setConfigUpdateStub, setSignatures: setSignaturesStub, toBuffer: toBufferStub}); + ConfigUpdateEnvelopeStub.returns({ + setConfigUpdate: setConfigUpdateStub, + setSignatures: setSignaturesStub, + toBuffer: toBufferStub + }); revert.push(Client.__set__('_stringToSignature', _stringToSignatureStub)); revert.push(Client.__set__('fabprotos.common.Envelope.decode', envelopeDecodeStub)); @@ -1102,7 +1127,12 @@ describe('Client', () => { it('should throw an error if request.signatures is not an array', async () => { try { - await client._createOrUpdateChannel({name: 'name', txId: 'txId', config: {}, signatures: 'signatures'}, false); + await client._createOrUpdateChannel({ + name: 'name', + txId: 'txId', + config: {}, + signatures: 'signatures' + }, false); } catch (err) { err.message.should.equal('Signatures request parameter must be an array of signatures'); } @@ -1111,7 +1141,12 @@ describe('Client', () => { it('should return the results of the broadcast when have_envelope is true', async () => { const envelope = {signature: 'signature', payload: 'payload'}; envelopeDecodeStub.returns(envelope); - const results = await client._createOrUpdateChannel({name: 'name', txId: 'txId', orderer: 'orderer', envelope: 'envelope'}, true); + const results = await client._createOrUpdateChannel({ + name: 'name', + txId: 'txId', + orderer: 'orderer', + envelope: 'envelope' + }, true); sinon.assert.calledWith(getTargetOrdererStub, 'orderer', null, 'name'); sinon.assert.calledWith(FakeLogger.debug, '_createOrUpdateChannel - have envelope'); sinon.assert.calledWith(envelopeDecodeStub, 'envelope'); @@ -1123,7 +1158,13 @@ describe('Client', () => { buildChannelHeaderStub.returns('proto_channel_header'); toBufferStub.onCall(0).returns('data'); toBufferStub.onCall(1).returns('payload-bytes'); - const results = await client._createOrUpdateChannel({name: 'name', txId: txIdStub, orderer: 'orderer', config: 'config', signatures: ['signature']}); + const results = await client._createOrUpdateChannel({ + name: 'name', + txId: txIdStub, + orderer: 'orderer', + config: 'config', + signatures: ['signature'] + }); sinon.assert.calledWith(FakeLogger.debug, '_createOrUpdateChannel - have config_update'); sinon.assert.calledWith(setConfigUpdateStub, 'config'); sinon.assert.calledWith(_stringToSignatureStub, ['signature']); @@ -1155,7 +1196,7 @@ describe('Client', () => { client.getTargetPeers = getTargetPeersStub; }); - it('should throw an error if no request is given', async() => { + it('should throw an error if no request is given', async () => { try { await client.queryPeers(); should.fail(); @@ -1165,7 +1206,7 @@ describe('Client', () => { } }); - it('should throw an error if no request.target is given', async() => { + it('should throw an error if no request.target is given', async () => { try { await client.queryPeers({}); should.fail(); @@ -1174,7 +1215,7 @@ describe('Client', () => { } }); - it('should throw an error if undefined target peers are found', async() => { + it('should throw an error if undefined target peers are found', async () => { try { await client.queryPeers({target: 'peers'}); } catch (e) { @@ -1183,7 +1224,7 @@ describe('Client', () => { } }); - it('should throw an error if no target peers are found', async() => { + it('should throw an error if no target peers are found', async () => { getTargetPeersStub.returns([]); try { await client.queryPeers({target: 'peers'}); @@ -1193,7 +1234,7 @@ describe('Client', () => { } }); - it('should throw if creating a channel object throws', async() => { + it('should throw if creating a channel object throws', async () => { ChannelStub.throws(Error, 'test-error'); getTargetPeersStub.returns(['peer1']); try { @@ -1204,7 +1245,7 @@ describe('Client', () => { } }); - it('should call discover with the generated discover_request and return the discovered peers', async() => { + it('should call discover with the generated discover_request and return the discovered peers', async () => { getTargetPeersStub.returns(['peer1']); _discoverStub.returns(Promise.resolve('peer-results')); ChannelStub.returns({_discover: _discoverStub}); @@ -1346,7 +1387,12 @@ describe('Client', () => { it('should return the query trans for a channel', async () => { _getSigningIdentityStub.returns('signer'); - sendTransactionProposalStub.returns(Promise.resolve([[{response: {status: 'status', payload: 'payload'}}]])); + sendTransactionProposalStub.returns(Promise.resolve([[{ + response: { + status: 'status', + payload: 'payload' + } + }]])); const queryTrans = await client.queryChannels('peer'); sinon.assert.calledWith(FakeLogger.debug, 'queryChannels - start'); sinon.assert.calledWith(getTargetPeersStub, 'peer'); @@ -1406,7 +1452,6 @@ describe('Client', () => { }); - it('should throw an error if we are unsure what is happening', async () => { _getSigningIdentityStub.returns('signer'); sendTransactionProposalStub.returns(Promise.resolve([[new Error('unknown error')]])); @@ -1504,7 +1549,12 @@ describe('Client', () => { it('should return the query trans for a channel', async () => { _getSigningIdentityStub.returns('signer'); - sendTransactionProposalStub.returns(Promise.resolve([[{response: {status: 'status', payload: 'payload'}}]])); + sendTransactionProposalStub.returns(Promise.resolve([[{ + response: { + status: 'status', + payload: 'payload' + } + }]])); const queryTrans = await client.queryInstalledChaincodes('peer'); sinon.assert.calledWith(FakeLogger.debug, 'queryInstalledChaincodes - start peer %s', 'peer'); sinon.assert.calledWith(getTargetPeersStub, 'peer'); @@ -1556,7 +1606,11 @@ describe('Client', () => { getNonceStub = sinon.stub().returns('nonce'); isAdminStub = sinon.stub().returns(true); getTransactionIDStub = sinon.stub().returns('txId'); - TransactionIDStub = sinon.stub().returns({isAdmin: isAdminStub, getTransactionID: getTransactionIDStub, getNonce: getNonceStub}); + TransactionIDStub = sinon.stub().returns({ + isAdmin: isAdminStub, + getTransactionID: getTransactionIDStub, + getNonce: getNonceStub + }); revert.push(Client.__set__('TransactionID', TransactionIDStub)); buildChannelHeaderStub = sinon.stub().returns('channel-header'); revert.push(Client.__set__('clientUtils.buildChannelHeader', buildChannelHeaderStub)); @@ -1640,7 +1694,13 @@ describe('Client', () => { metadataPath: undefined }).resolves(smartContractPackage); getTargetPeersStub.withArgs(['peer']).returns(['peer']); - const request = {chaincodeId: 'mycc', chaincodeVersion: '0.0.1', chaincodePath: 'mycc', chaincodeType: 'java', targets: ['peer']}; + const request = { + chaincodeId: 'mycc', + chaincodeVersion: '0.0.1', + chaincodePath: 'mycc', + chaincodeType: 'java', + targets: ['peer'] + }; const response = await client.installChaincode(request); sinon.assert.calledWith(getTargetPeersStub, ['peer']); sinon.assert.calledOnce(fromDirectoryStub); @@ -1667,7 +1727,14 @@ describe('Client', () => { metadataPath: 'mycc/META-INF' }).resolves(smartContractPackage); getTargetPeersStub.withArgs(['peer']).returns(['peer']); - const request = {chaincodeId: 'mycc', chaincodeVersion: '0.0.1', chaincodePath: 'mycc', chaincodeType: 'java', metadataPath: 'mycc/META-INF', targets: ['peer']}; + const request = { + chaincodeId: 'mycc', + chaincodeVersion: '0.0.1', + chaincodePath: 'mycc', + chaincodeType: 'java', + metadataPath: 'mycc/META-INF', + targets: ['peer'] + }; const response = await client.installChaincode(request); sinon.assert.calledWith(getTargetPeersStub, ['peer']); sinon.assert.calledOnce(fromDirectoryStub); @@ -1737,7 +1804,14 @@ describe('Client', () => { metadataPath: undefined }).resolves(smartContractPackage); getTargetPeersStub.returns(['peer']); - const request = {chaincodeId: 'mycc', chaincodeVersion: '0.0.1', chaincodePath: 'mycc', targets: [], channelNames: [], txId: {isAdmin: isAdminStub, getNonce: getNonceStub, getTransactionID: getTransactionIDStub}}; + const request = { + chaincodeId: 'mycc', + chaincodeVersion: '0.0.1', + chaincodePath: 'mycc', + targets: [], + channelNames: [], + txId: {isAdmin: isAdminStub, getNonce: getNonceStub, getTransactionID: getTransactionIDStub} + }; const response = await client.installChaincode(request); sinon.assert.calledWith(getTargetPeersStub, []); sinon.assert.calledOnce(fromDirectoryStub); @@ -1763,7 +1837,14 @@ describe('Client', () => { metadataPath: undefined }).resolves(smartContractPackage); getTargetPeersStub.returns(['peer']); - const request = {chaincodeId: 'mycc', chaincodeVersion: '0.0.1', chaincodePath: 'mycc', targets: [], channelNames: [], txId: {isAdmin: isAdminStub, getNonce: getNonceStub, getTransactionID: getTransactionIDStub}}; + const request = { + chaincodeId: 'mycc', + chaincodeVersion: '0.0.1', + chaincodePath: 'mycc', + targets: [], + channelNames: [], + txId: {isAdmin: isAdminStub, getNonce: getNonceStub, getTransactionID: getTransactionIDStub} + }; const response = await client.installChaincode(request); sinon.assert.calledWith(getTargetPeersStub, []); sinon.assert.calledOnce(fromDirectoryStub); @@ -1790,7 +1871,12 @@ describe('Client', () => { }).resolves(smartContractPackage); getTargetPeersStub.returns(); getPeersForOrgOnChannelStub.withArgs(['mychannel']).returns(['peer']); - const request = {chaincodeId: 'mycc', chaincodeVersion: '0.0.1', chaincodePath: 'mycc', channelNames: ['mychannel']}; + const request = { + chaincodeId: 'mycc', + chaincodeVersion: '0.0.1', + chaincodePath: 'mycc', + channelNames: ['mychannel'] + }; const response = await client.installChaincode(request); sinon.assert.calledWith(getTargetPeersStub, undefined); sinon.assert.calledOnce(fromDirectoryStub); @@ -1894,7 +1980,10 @@ describe('Client', () => { }); it('should set _stateStore and _userContext properties', () => { - const kvs = {method: () => { }}; + const kvs = { + method: () => { + } + }; client.setStateStore(kvs); client._stateStore.should.equal(kvs); should.equal(client._userContext, null); @@ -2294,7 +2383,11 @@ describe('Client', () => { sinon.assert.called(getMspidStub); sinon.assert.calledWith(getCertificateAuthorityStub, 'ca'); sinon.assert.calledWith(FakeLogger.debug, 'Successfully enrolled user "test"'); - sinon.assert.calledWith(createUserStub, {username: 'test', mspid: 1, cryptoContent: {privateKeyObj: 'key', signedCertPEM: 'cert'}}); + sinon.assert.calledWith(createUserStub, { + username: 'test', + mspid: 1, + cryptoContent: {privateKeyObj: 'key', signedCertPEM: 'cert'} + }); user.should.equal('user'); }); @@ -2308,9 +2401,13 @@ describe('Client', () => { }; client._stateStore = {}; client._cryptoSuite = {}; - enrollStub.returns({key: {toBytes: () => { - throw new Error(); - }}, certificate: 'cert'}); + enrollStub.returns({ + key: { + toBytes: () => { + throw new Error(); + } + }, certificate: 'cert' + }); const user = await client._setUserFromConfig({username: 'test', password: 'password', caName: 'ca'}); sinon.assert.calledWith(getUserContextStub, 'test', true); @@ -2321,7 +2418,11 @@ describe('Client', () => { sinon.assert.calledWith(getCertificateAuthorityStub, 'ca'); sinon.assert.calledWith(FakeLogger.debug, 'Successfully enrolled user "test"'); sinon.assert.calledWith(FakeLogger.debug, 'Cannot access enrollment private key bytes'); - sinon.assert.calledWith(createUserStub, {username: 'test', mspid: 1, cryptoContent: {privateKeyObj: enrollStub().key, signedCertPEM: 'cert'}}); + sinon.assert.calledWith(createUserStub, { + username: 'test', + mspid: 1, + cryptoContent: {privateKeyObj: enrollStub().key, signedCertPEM: 'cert'} + }); user.should.equal('user'); }); @@ -2345,7 +2446,11 @@ describe('Client', () => { sinon.assert.called(getMspidStub); sinon.assert.calledWith(getCertificateAuthorityStub, 'ca'); sinon.assert.calledWith(FakeLogger.debug, 'Successfully enrolled user "test"'); - sinon.assert.calledWith(createUserStub, {username: 'test', mspid: 1, cryptoContent: {privateKeyPEM: '-----BEGIN', signedCertPEM: 'cert'}}); + sinon.assert.calledWith(createUserStub, { + username: 'test', + mspid: 1, + cryptoContent: {privateKeyPEM: '-----BEGIN', signedCertPEM: 'cert'} + }); user.should.equal('user'); }); }); @@ -2543,7 +2648,8 @@ describe('Client', () => { }); describe('#loadUserFromStateStore', () => { - const FakeUser = class { }; + const FakeUser = class { + }; let getValueStub; let getCryptoSuiteStub; let setCryptoSuiteStub; @@ -2618,7 +2724,8 @@ describe('Client', () => { let client; beforeEach(() => { userConstructorStub = sinon.stub(); - FakeUser = class { }; + FakeUser = class { + }; setCryptoSuiteStub = sinon.stub(); setEnrollmentStub = sinon.stub().returns(Promise.resolve()); FakeUser.prototype.constructor = userConstructorStub; @@ -2687,12 +2794,21 @@ describe('Client', () => { it('should throw an error if opts.cryptoContent.signedCert and signedCertPEM are not given', async () => { await client.createUser({username: 'name', mspid: '1', cryptoContent: {privateKey: 'private-key'}}) .should.eventually.be.rejectedWith('Client.createUser either \'opts cryptoContent signedCert or signedCertPEM\' is required.'); - sinon.assert.calledWith(FakeLogger.debug, 'opts = %j', {username: 'name', mspid: '1', cryptoContent: {privateKey: 'private-key'}}); + sinon.assert.calledWith(FakeLogger.debug, 'opts = %j', { + username: 'name', + mspid: '1', + cryptoContent: {privateKey: 'private-key'} + }); }); it('should return a user', async () => { readFileStub.returns(Promise.resolve('privateKeyPEM')); - const user = await client.createUser({username: 'name', mspid: '1', cryptoContent: {privateKey: 'private-key', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, skipPersistence: true}); + const user = await client.createUser({ + username: 'name', + mspid: '1', + cryptoContent: {privateKey: 'private-key', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, + skipPersistence: true + }); sinon.assert.calledWith(readFileStub, 'private-key'); sinon.assert.calledWith(FakeLogger.debug, 'then privateKeyPEM data'); sinon.assert.calledWith(readFileStub, 'signed-cert'); @@ -2710,7 +2826,12 @@ describe('Client', () => { getCryptoSuiteStub.onCall(0).returns(null); getCryptoSuiteStub.onCall(1).returns({setCryptoKeyStore: setCryptoKeyStoreStub}); readFileStub.returns(Promise.resolve('privateKeyPEM')); - const user = await client.createUser({username: 'name', mspid: '1', cryptoContent: {privateKey: 'private-key', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, skipPersistence: true}); + const user = await client.createUser({ + username: 'name', + mspid: '1', + cryptoContent: {privateKey: 'private-key', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, + skipPersistence: true + }); sinon.assert.calledWith(readFileStub, 'private-key'); sinon.assert.calledWith(FakeLogger.debug, 'then privateKeyPEM data'); sinon.assert.calledWith(readFileStub, 'signed-cert'); @@ -2757,8 +2878,21 @@ describe('Client', () => { }); it('should return a user if getCryptoSuite does not return null', async () => { - getCryptoSuiteStub.returns({setCryptoKeyStore: setCryptoKeyStoreStub, importKey: importKeyStub, _cryptoKeyStore: {}}); - const user = await client.createUser({username: 'name', mspid: '1', cryptoContent: {privateKeyPEM: 'privateKeyPem', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, skipPersistence: false}); + getCryptoSuiteStub.returns({ + setCryptoKeyStore: setCryptoKeyStoreStub, + importKey: importKeyStub, + _cryptoKeyStore: {} + }); + const user = await client.createUser({ + username: 'name', + mspid: '1', + cryptoContent: { + privateKeyPEM: 'privateKeyPem', + signedCert: 'signed-cert', + signedCertPEM: 'signed-cert-PEM' + }, + skipPersistence: false + }); sinon.assert.calledWith(FakeLogger.debug, 'then privateKeyPEM data'); sinon.assert.calledWith(readFileStub, 'signed-cert'); sinon.assert.calledWith(FakeLogger.debug, 'then signedCertPEM data'); @@ -2773,10 +2907,19 @@ describe('Client', () => { }); it('should return a user if getCryptoSuite does not return null', async () => { - getCryptoSuiteStub.returns({setCryptoKeyStore: setCryptoKeyStoreStub, importKey: importKeyStub, _cryptoKeyStore: {}}); + getCryptoSuiteStub.returns({ + setCryptoKeyStore: setCryptoKeyStoreStub, + importKey: importKeyStub, + _cryptoKeyStore: {} + }); readFileStub.onCall(0).returns(null); readFileStub.onCall(1).returns(123); - const user = await client.createUser({username: 'name', mspid: '1', cryptoContent: {privateKey: 'private-key', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, skipPersistence: false}); + const user = await client.createUser({ + username: 'name', + mspid: '1', + cryptoContent: {privateKey: 'private-key', signedCert: 'signed-cert', signedCertPEM: 'signed-cert-PEM'}, + skipPersistence: false + }); sinon.assert.calledWith(readFileStub, 'signed-cert'); sinon.assert.calledWith(FakeLogger.debug, 'then signedCertPEM data'); sinon.assert.calledWith(setCryptoSuiteStub, getCryptoSuiteStub()); @@ -2789,10 +2932,19 @@ describe('Client', () => { }); it('should return a user if getCryptoSuite does not return null', async () => { - getCryptoSuiteStub.returns({setCryptoKeyStore: setCryptoKeyStoreStub, importKey: importKeyStub, _cryptoKeyStore: {}}); + getCryptoSuiteStub.returns({ + setCryptoKeyStore: setCryptoKeyStoreStub, + importKey: importKeyStub, + _cryptoKeyStore: {} + }); readFileStub.onCall(0).returns(null); readFileStub.onCall(1).returns(123); - const user = await client.createUser({username: 'name', mspid: '1', cryptoContent: {privateKey: 'private-key', signedCertPEM: 'signed-cert-PEM'}, skipPersistence: false}); + const user = await client.createUser({ + username: 'name', + mspid: '1', + cryptoContent: {privateKey: 'private-key', signedCertPEM: 'signed-cert-PEM'}, + skipPersistence: false + }); sinon.assert.calledWith(readFileStub, 'private-key'); sinon.assert.calledWith(FakeLogger.debug, 'then signedCertPEM data'); sinon.assert.calledWith(setCryptoSuiteStub, getCryptoSuiteStub()); @@ -2807,7 +2959,8 @@ describe('Client', () => { describe('#getTargetPeers', () => { let getPeerStub; - const Peer = class { }; + const Peer = class { + }; let client; beforeEach(() => { @@ -2849,7 +3002,8 @@ describe('Client', () => { let getOrdererStub; let getChannelStub; let getOrderersStub; - const Orderer = class { }; + const Orderer = class { + }; let client; beforeEach(() => { diff --git a/fabric-client/test/Peer.js b/fabric-client/test/Peer.js index 7d1ac87030..7d29fa9483 100644 --- a/fabric-client/test/Peer.js +++ b/fabric-client/test/Peer.js @@ -106,7 +106,7 @@ describe('Peer', () => { }) .catch(() => { sinon.assert.called(debugStub); - debugStub.getCall(1).args.should.deep.equal(['%s - Start ----%s %s', 'sendProposal', 'host:2700', 'grpc://host:2700']); + debugStub.getCall(1).lastArg.should.equal('_createClients - create peer endorser connection host:2700'); }); }); @@ -387,7 +387,7 @@ describe('Peer', () => { }) .catch(() => { sinon.assert.called(debugStub); - debugStub.getCall(1).args.should.deep.equal(['%s - Start', 'sendDiscovery']); + debugStub.getCall(1).lastArg.should.equal('_createClients - create peer endorser connection host:2700'); }); }); @@ -572,7 +572,7 @@ describe('Peer', () => { }) .catch(() => { sinon.assert.called(debugStub); - debugStub.getCall(1).args.should.deep.equal(['%s - Start ----%s %s', 'sendTokenCommand', 'host:2700', 'grpc://host:2700']); + debugStub.getCall(1).lastArg.should.equal('_createClients - create peer endorser connection host:2700'); }); }); diff --git a/fabric-client/test/TransactionID.js b/fabric-client/test/TransactionID.js index f6230ae35d..25ea15d8e7 100644 --- a/fabric-client/test/TransactionID.js +++ b/fabric-client/test/TransactionID.js @@ -18,9 +18,8 @@ const rewire = require('rewire'); const TransactionID = require('../lib/TransactionID'); const TransactionIDRewire = rewire('../lib/TransactionID'); -const {Identity} = require('fabric-common'); -const User = require('../lib/User'); -const Utils = require('../lib/utils'); +const {Identity, Utils, User} = require('fabric-common'); + require('chai').should(); const sinon = require('sinon'); @@ -188,4 +187,4 @@ describe('TransactionID', () => { }); }); -}); \ No newline at end of file +}); diff --git a/fabric-client/test/User.js b/fabric-client/test/User.js index c19dfe140d..eb155cc751 100644 --- a/fabric-client/test/User.js +++ b/fabric-client/test/User.js @@ -15,8 +15,8 @@ 'use strict'; const rewire = require('rewire'); -const UserRewire = rewire('../lib/User'); -const User = require('../lib/User'); +const UserRewire = rewire('fabric-common/lib/User'); +const {User} = require('fabric-common'); const chai = require('chai'); const should = chai.should(); @@ -46,7 +46,12 @@ describe('User', () => { }); it('should conditionally initialise parameters if cfg is an object with an enrollmentID and roles', () => { - const obj = new Object({enrollmentID: 'user_enrollmentID', name: 'user_name', roles: ['role_1', 'role_2'], affiliation: 'user_affiliation'}); + const obj = new Object({ + enrollmentID: 'user_enrollmentID', + name: 'user_name', + roles: ['role_1', 'role_2'], + affiliation: 'user_affiliation' + }); const myUser = new User(obj); myUser._name.should.equal(obj.enrollmentID); myUser._roles.should.equal(obj.roles); @@ -81,7 +86,12 @@ describe('User', () => { describe('#getRoles', () => { it('should get the users roles', () => { - const obj = new Object({enrollmentID: 'user_enrollmentID', name: 'user_name', roles: ['role_1', 'role_2'], affiliation: 'user_affiliation'}); + const obj = new Object({ + enrollmentID: 'user_enrollmentID', + name: 'user_name', + roles: ['role_1', 'role_2'], + affiliation: 'user_affiliation' + }); const myUser = new User(obj); myUser.getRoles().should.equal(obj.roles); }); @@ -89,7 +99,12 @@ describe('User', () => { describe('#setRoles', () => { it('should set the users roles', () => { - const myUser = new User({enrollmentID: 'user_enrollmentID', name: 'user_name', roles: ['role_1', 'role_2'], affiliation: 'user_affiliation'}); + const myUser = new User({ + enrollmentID: 'user_enrollmentID', + name: 'user_name', + roles: ['role_1', 'role_2'], + affiliation: 'user_affiliation' + }); myUser.setRoles(['new_role_1', 'new_role_2']); myUser._roles.should.deep.equal(['new_role_1', 'new_role_2']); }); @@ -97,7 +112,12 @@ describe('User', () => { describe('#getAffiliation', () => { it('should get the users affiliation', () => { - const obj = new Object({enrollmentID: 'user_enrollmentID', name: 'user_name', roles: ['role_1', 'role_2'], affiliation: 'user_affiliation'}); + const obj = new Object({ + enrollmentID: 'user_enrollmentID', + name: 'user_name', + roles: ['role_1', 'role_2'], + affiliation: 'user_affiliation' + }); const myUser = new User(obj); myUser.getAffiliation().should.equal(obj.affiliation); }); @@ -105,7 +125,12 @@ describe('User', () => { describe('#setAffiliation', () => { it('should set the users affiliation', () => { - const myUser = new User({enrollmentID: 'user_enrollmentID', name: 'user_name', roles: ['role_1', 'role_2'], affiliation: 'user_affiliation'}); + const myUser = new User({ + enrollmentID: 'user_enrollmentID', + name: 'user_name', + roles: ['role_1', 'role_2'], + affiliation: 'user_affiliation' + }); myUser.setAffiliation('new_affiliation'); myUser._affiliation.should.equal('new_affiliation'); }); @@ -144,52 +169,58 @@ describe('User', () => { }); describe('#setEnrollment', () => { - it('should throw error if no privateKey parameter', async() => { + it('should throw error if no privateKey parameter', async () => { const myUser = new User('my_cfg'); await myUser.setEnrollment(null, 'test_certificate', 'test_mspId', true) .should.be.rejectedWith(/Invalid parameter. Must have a valid private key./); }); - it('should throw error if the privateKey parameter is an empty string', async() => { + it('should throw error if the privateKey parameter is an empty string', async () => { const myUser = new User('my_cfg'); await myUser.setEnrollment('', 'test_certificate', 'test_mspId', true) .should.be.rejectedWith(/Invalid parameter. Must have a valid private key./); }); - it('should throw error if no certificate parameter', async() => { + it('should throw error if no certificate parameter', async () => { const myUser = new User('my_cfg'); await myUser.setEnrollment('test_privateKey', null, 'test_mspId', true) .should.be.rejectedWith(/Invalid parameter. Must have a valid certificate./); }); - it('should throw error if certificate parameter is an empty string', async() => { + it('should throw error if certificate parameter is an empty string', async () => { const myUser = new User('my_cfg'); await myUser.setEnrollment('test_privateKey', '', 'test_mspId', true) .should.be.rejectedWith(/Invalid parameter. Must have a valid certificate./); }); - it('should throw error if no mspId parameter', async() => { + it('should throw error if no mspId parameter', async () => { const myUser = new User('my_cfg'); await myUser.setEnrollment('test_privateKey', 'test_certificate', null, true) .should.be.rejectedWith(/Invalid parameter. Must have a valid mspId./); }); - it('should throw error if mspId parameter is an empty string', async() => { + it('should throw error if mspId parameter is an empty string', async () => { const myUser = new User('my_cfg'); await myUser.setEnrollment('test_privateKey', 'test_certificate', '', true) .should.be.rejectedWith(/Invalid parameter. Must have a valid mspId./); }); - it('should set the cryptoSuite if its not already set', async() => { + it('should set the cryptoSuite if its not already set', async () => { const sandbox = sinon.createSandbox(); const FakeSdkUtils = { - newCryptoSuite: () => {}, + newCryptoSuite: () => { + } }; const FakeIdentity = sandbox.stub(); const FakeSigningIdentity = sandbox.stub(); - const returnStub = sandbox.stub({setCryptoKeyStore: () => {}, importKey: () => {}, createKeyFromRaw: () => {}}); + const returnStub = sandbox.stub({ + setCryptoKeyStore: () => { + }, importKey: () => { + }, createKeyFromRaw: () => { + } + }); const newCryptoSuiteStub = sandbox.stub(FakeSdkUtils, 'newCryptoSuite').returns(returnStub); UserRewire.__set__('sdkUtils', FakeSdkUtils); @@ -203,20 +234,25 @@ describe('User', () => { obj._cryptoSuite.should.equal(returnStub); }); - it('should set users crypto key store if skipPersistance is false', async() => { + it('should set users crypto key store if skipPersistance is false', async () => { const sandbox = sinon.createSandbox(); const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeIdentity = sandbox.stub(); const FakeSigningIdentity = sandbox.stub(); const cryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + createKeyFromRaw: () => { + } }; const FakeSetCryptoKeyStore = sandbox.stub(cryptoSuite, 'setCryptoKeyStore'); @@ -236,20 +272,24 @@ describe('User', () => { sinon.assert.calledWith(FakeSetCryptoKeyStore, 'test_cryptoKeyStore'); }); - it('should create and set a pubKey variable if the cryptoKeyStore is set and skipPersistence is false', async() => { + it('should create and set a pubKey variable if the cryptoKeyStore is set and skipPersistence is false', async () => { const sandbox = sinon.createSandbox(); const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeIdentity = sandbox.stub(); const FakeSigningIdentity = sandbox.stub(); const cryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - _cryptoKeyStore: 'cryptoKeyStore', + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + _cryptoKeyStore: 'cryptoKeyStore' }; const FakeImportKey = sandbox.stub(cryptoSuite, 'importKey'); @@ -269,20 +309,25 @@ describe('User', () => { sinon.assert.calledWith(FakeImportKey, 'test_certificate'); }); - it('should create and set a pubKey variable if the either the cryptoKeyStore is not set or skipPersitence is true', async() => { + it('should create and set a pubKey variable if the either the cryptoKeyStore is not set or skipPersitence is true', async () => { const sandbox = sinon.createSandbox(); const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeIdentity = sandbox.stub(); const FakeSigningIdentity = sandbox.stub(); const cryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + createKeyFromRaw: () => { + } }; const FakeCreateKey = sandbox.stub(cryptoSuite, 'createKeyFromRaw'); @@ -302,20 +347,25 @@ describe('User', () => { sinon.assert.calledWith(FakeCreateKey, 'test_certificate'); }); - it('should set the users identity', async() => { + it('should set the users identity', async () => { const sandbox = sinon.createSandbox(); const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeIdentity = sandbox.stub(); const FakeSigningIdentity = sandbox.stub(); const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - createKeyFromRaw: () => {}, + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + createKeyFromRaw: () => { + }, _cryptoKeyStore: true }; @@ -335,20 +385,25 @@ describe('User', () => { sinon.assert.calledWith(FakeIdentity, 'test_certificate', 'import_key', 'test_mspId', FakeCryptoSuite); }); - it('should set the users signingIdentity', async() => { + it('should set the users signingIdentity', async () => { const sandbox = sinon.createSandbox(); const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeIdentity = sandbox.stub(); const FakeSigningIdentity = sandbox.stub(); const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + createKeyFromRaw: () => { + } }; sandbox.stub(FakeSdkUtils, 'newCryptoSuite').returns(FakeCryptoSuite); @@ -404,12 +459,15 @@ describe('User', () => { it('should log and set the users state, name, roles, afilliation and enrollmentSecret', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const privateStub = { @@ -419,10 +477,12 @@ describe('User', () => { }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, + setCryptoKeyStore: () => { + }, importKey: () => sinon.stub().resolves(), getKey: sinon.stub().returns(privateStub), - createKeyFromRaw: () => {} + createKeyFromRaw: () => { + } }; const debugStub = sandbox.stub(FakeLogger, 'debug'); @@ -448,7 +508,8 @@ describe('User', () => { it('should throw error if state name is not the same as user name', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; sandbox.stub(FakeLogger, 'debug'); @@ -461,7 +522,8 @@ describe('User', () => { it('should throw error if the state has no mspid', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; sandbox.stub(FakeLogger, 'debug'); @@ -474,12 +536,15 @@ describe('User', () => { it('should set the users mspid to the state mspid', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const privateStub = { @@ -489,14 +554,18 @@ describe('User', () => { }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, + setCryptoKeyStore: () => { + }, + importKey: () => { + }, getKey: sinon.stub().returns(privateStub), - createKeyFromRaw: () => {} + createKeyFromRaw: () => { + } }; const FakeIdentity = sandbox.stub(); - const promise = new Promise(() => {}); + const promise = new Promise(() => { + }); sandbox.stub(FakeSdkUtils, 'newCryptoSuite').returns(FakeCryptoSuite); sandbox.stub(FakeSdkUtils, 'newCryptoKeyStore').returns('test_cryptoKeyStore'); @@ -516,12 +585,15 @@ describe('User', () => { it('should throw an error if resulting key is not private', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const privateStub = { @@ -531,14 +603,18 @@ describe('User', () => { }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, + setCryptoKeyStore: () => { + }, + importKey: () => { + }, getKey: sinon.stub().returns(privateStub), - createKeyFromRaw: () => {} + createKeyFromRaw: () => { + } }; const FakeIdentity = sandbox.stub(); - const promise = new Promise(() => {}); + const promise = new Promise(() => { + }); sandbox.stub(FakeSdkUtils, 'newCryptoSuite').returns(FakeCryptoSuite); sandbox.stub(FakeSdkUtils, 'newCryptoKeyStore').returns('test_cryptoKeyStore'); @@ -555,30 +631,39 @@ describe('User', () => { it('should set import_promise if no_save is false', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - getKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + getKey: () => { + }, + createKeyFromRaw: () => { + } }; const FakeCryptoAlgorithms = { - X509Certificate: 'X509Certificate', + X509Certificate: 'X509Certificate' }; const FakeIdentity = sandbox.stub(); const promise = new Promise((resolve) => { - resolve({isPrivate() { - return true; - }}); + resolve({ + isPrivate() { + return true; + } + }); }); const FakeImportKey = sandbox.stub(FakeCryptoSuite, 'importKey').returns(promise); @@ -600,23 +685,30 @@ describe('User', () => { it('should return the _cryptoSuite key', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - getKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + getKey: () => { + }, + createKeyFromRaw: () => { + } }; const FakeCryptoAlgorithms = { - X509Certificate: 'X509Certificate', + X509Certificate: 'X509Certificate' }; const FakeKey = { @@ -647,19 +739,26 @@ describe('User', () => { it('should assign the self variable with a signing identity if the privateKey is private', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - getKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + getKey: () => { + }, + createKeyFromRaw: () => { + } }; const FakeKey = { @@ -694,26 +793,35 @@ describe('User', () => { it('should throw error if private key is missing', async () => { const FakeLogger = { - debug: () => {} + debug: () => { + } }; const FakeSdkUtils = { - newCryptoSuite: () => {}, - newCryptoKeyStore: () => {}, + newCryptoSuite: () => { + }, + newCryptoKeyStore: () => { + } }; const FakeCryptoSuite = { - setCryptoKeyStore: () => {}, - importKey: () => {}, - getKey: () => {}, - createKeyFromRaw: () => {} + setCryptoKeyStore: () => { + }, + importKey: () => { + }, + getKey: () => { + }, + createKeyFromRaw: () => { + } }; const FakeIdentity = sandbox.stub(); const promise = new Promise(((resolve) => { - resolve({isPrivate() { - return false; - }}); + resolve({ + isPrivate() { + return false; + } + }); })); sandbox.stub(FakeCryptoSuite, 'importKey').returns(promise); @@ -732,22 +840,43 @@ describe('User', () => { describe('#toString', () => { it('should create a state and return it when the user has no signingIdentity or identity', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user.toString().should.equal('{"name":"cfg","mspid":"","roles":"test_role","affiliation":"test_affiliation","enrollmentSecret":"","enrollment":{}}'); }); it('should set serializedEnrollment.signingIdentity if the user has a signingIdentity', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); - user._signingIdentity = {_signer: {_key: {getSKI() { - return 'test_signingIdentity'; - }}}}; + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); + user._signingIdentity = { + _signer: { + _key: { + getSKI() { + return 'test_signingIdentity'; + } + } + } + }; user.toString().should.equal('{"name":"cfg","mspid":"","roles":"test_role","affiliation":"test_affiliation","enrollmentSecret":"","enrollment":{"signingIdentity":"test_signingIdentity"}}'); }); it('should set serializedEnrollment.identity.certificate if the user has an identity.certificate', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._identity = {_certificate: 'test_certificate'}; user.toString().should.equal('{"name":"cfg","mspid":"","roles":"test_role","affiliation":"test_affiliation","enrollmentSecret":"","enrollment":{"identity":{"certificate":"test_certificate"}}}'); @@ -756,7 +885,12 @@ describe('User', () => { describe('#User.isInstance', () => { it('should return true if every user parameter is defined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; @@ -767,7 +901,12 @@ describe('User', () => { }); it('should return false if user._name is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; @@ -779,7 +918,12 @@ describe('User', () => { }); it('should return false if user._roles is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; @@ -791,7 +935,12 @@ describe('User', () => { }); it('should return false if user._affiliation is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; @@ -803,7 +952,12 @@ describe('User', () => { }); it('should return false if user._enrollmentSecret is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = undefined; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; @@ -814,7 +968,12 @@ describe('User', () => { }); it('should return false if user._identity is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = undefined; user._signingIdentity = 'test_signingIdentity'; @@ -825,7 +984,12 @@ describe('User', () => { }); it('should return false if user._signingIdentity is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = undefined; @@ -836,7 +1000,12 @@ describe('User', () => { }); it('should return false if user._mspId is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; @@ -847,7 +1016,12 @@ describe('User', () => { }); it('should return false if user._cryptoSuite is undefined', () => { - const user = new User({enrollmentID: 'cfg', name: 'cfg', roles: 'test_role', affiliation: 'test_affiliation'}); + const user = new User({ + enrollmentID: 'cfg', + name: 'cfg', + roles: 'test_role', + affiliation: 'test_affiliation' + }); user._enrollmentSecret = 'test_enrollmentSecret'; user._identity = 'test_identity'; user._signingIdentity = 'test_signingIdentity'; diff --git a/fabric-client/test/impl/CouchDBKeyValueStore.js b/fabric-client/test/impl/CouchDBKeyValueStore.js index c047360ac9..88fd5c7c69 100644 --- a/fabric-client/test/impl/CouchDBKeyValueStore.js +++ b/fabric-client/test/impl/CouchDBKeyValueStore.js @@ -7,8 +7,8 @@ 'use strict'; const rewire = require('rewire'); -const CouchDBKeyValueStoreRW = rewire('../../lib/impl/CouchDBKeyValueStore'); -const CouchDBKeyValueStore = require('../../lib/impl/CouchDBKeyValueStore'); +const CouchDBKeyValueStoreRW = rewire('fabric-common/lib/impl/CouchDBKeyValueStore'); +const CouchDBKeyValueStore = require('fabric-common/lib/impl/CouchDBKeyValueStore'); const CouchdbMock = require('mock-couch'); const chai = require('chai'); diff --git a/fabric-client/test/impl/FileKeyValueStore.js b/fabric-client/test/impl/FileKeyValueStore.js index 2c8f0e3bc7..0377757832 100644 --- a/fabric-client/test/impl/FileKeyValueStore.js +++ b/fabric-client/test/impl/FileKeyValueStore.js @@ -7,7 +7,7 @@ 'use strict'; const rewire = require('rewire'); -const FileKeyValueStoreRW = rewire('../../lib/impl/FileKeyValueStore'); +const FileKeyValueStoreRW = rewire('../../../fabric-common/lib/impl/FileKeyValueStore'); const chai = require('chai'); const should = chai.should(); diff --git a/fabric-client/test/impl/bccsp_pkcs11.js b/fabric-client/test/impl/bccsp_pkcs11.js index 926ad68ab0..e82f04b192 100644 --- a/fabric-client/test/impl/bccsp_pkcs11.js +++ b/fabric-client/test/impl/bccsp_pkcs11.js @@ -7,7 +7,7 @@ 'use strict'; const rewire = require('rewire'); -const PKCS11_Rewire = rewire('../../lib/impl/bccsp_pkcs11'); +const PKCS11_Rewire = rewire('../../../fabric-common/lib/impl/bccsp_pkcs11'); const chai = require('chai'); chai.should(); diff --git a/fabric-client/test/impl/ecdsa/key.js b/fabric-client/test/impl/ecdsa/key.js index 2d9820cd05..a96adc7e3a 100644 --- a/fabric-client/test/impl/ecdsa/key.js +++ b/fabric-client/test/impl/ecdsa/key.js @@ -7,7 +7,7 @@ 'use strict'; const rewire = require('rewire'); -const ECDSA_KEY_REWIRE = rewire('../../../lib/impl/ecdsa/key'); +const ECDSA_KEY_REWIRE = rewire('../../../../fabric-common/lib/impl/ecdsa/key'); const jsrsa = require('jsrsasign'); const KEYUTIL = jsrsa.KEYUTIL; @@ -117,7 +117,7 @@ describe('ECDSA_KEY', () => { if (revert) { revert(); } - revert = null; + revert = null; }); it('should throw when trying to generate if public', () => { @@ -190,7 +190,7 @@ describe('ECDSA_KEY', () => { if (revert) { revert(); } - revert = null; + revert = null; }); it('should throw when trying to generate if public', () => { diff --git a/fabric-client/test/msp/msp.js b/fabric-client/test/msp/msp.js index a7a0d6a424..49a4d8fa4a 100644 --- a/fabric-client/test/msp/msp.js +++ b/fabric-client/test/msp/msp.js @@ -7,9 +7,7 @@ 'use strict'; -const MSP = require('../../lib/msp/msp'); -const {Config, CryptoAlgorithms, Identity, SigningIdentity} = require('fabric-common'); -const utils = require('../../lib/utils'); +const {Config, CryptoAlgorithms, Identity, SigningIdentity, Utils: utils, MSP} = require('fabric-common'); const path = require('path'); const fs = require('fs'); @@ -17,7 +15,7 @@ require('chai'); const sinon = require('sinon'); const rewire = require('rewire'); -const MspRewire = rewire('../../lib/msp/msp'); +const MspRewire = rewire('../../../fabric-common/lib/Msp.js'); const certificateAsPEM = fs.readFileSync(path.join(__dirname, '..', 'data', 'cert.pem')).toString('utf8'); @@ -370,7 +368,10 @@ describe('MSP', () => { cryptoSuite: cryptoUtils }); - const pubKey = cryptoUtils.importKey(certificateAsPEM, {algorithm: CryptoAlgorithms.X509Certificate, ephemeral: true}); + const pubKey = cryptoUtils.importKey(certificateAsPEM, { + algorithm: CryptoAlgorithms.X509Certificate, + ephemeral: true + }); const identity = new Identity(certificateAsPEM, pubKey, msp.getId(), cryptoUtils); const serializedID = identity.serialize(); diff --git a/fabric-client/test/utils.js b/fabric-client/test/utils.js index 277c9eb14b..9a4de90f42 100644 --- a/fabric-client/test/utils.js +++ b/fabric-client/test/utils.js @@ -1,22 +1,11 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; const rewire = require('rewire'); -const Utils = rewire('../lib/utils'); -const Long = require('long'); +const Utils = rewire('../../fabric-common/lib/Utils'); const should = require('chai').should(); @@ -499,34 +488,6 @@ describe('Utils', () => { }); }); - describe('#convertToLong', () => { - it('should throw an error if value is not set', () => { - (() => { - Utils.convertToLong(); - }).should.throw(/value parameter is missing/); - }); - - it('should throw an error if value is not a number', () => { - (() => { - Utils.convertToLong('test'); - }).should.throw(/value:test is not a valid number/); - }); - - it('should return the Long value', () => { - const result = Utils.convertToLong(Long.fromValue(1)); - result.should.deep.equal(Long.fromValue(1)); - }); - - it('should return the Long value', () => { - const result = Utils.convertToLong(1.0); - result.should.deep.equal(Long.fromValue(1)); - }); - - it('should return the Long value', () => { - const result = Utils.convertToLong(0.0); - result.should.deep.equal(Long.fromValue(0)); - }); - }); describe('#checkIntegerConfig', () => { it('should throw an error if config value is not an integer', () => { diff --git a/fabric-client/test/utils/format.js b/fabric-client/test/utils/format.js new file mode 100644 index 0000000000..c1955bb404 --- /dev/null +++ b/fabric-client/test/utils/format.js @@ -0,0 +1,49 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const Format = require('../../lib/utils/format'); +const Long = require('long'); +const should = require('chai').should(); + +describe('#convertToLong', () => { + should; + it('should throw an error if value is not set', () => { + (() => { + Format.convertToLong(); + }).should.throw(/value parameter is missing/); + }); + + it('should throw an error if value is not a number', () => { + (() => { + Format.convertToLong('test'); + }).should.throw(/value:test is not a valid number/); + }); + + it('should return the Long value', () => { + const result = Format.convertToLong(Long.fromValue(1)); + result.should.deep.equal(Long.fromValue(1)); + }); + + it('should return the Long value', () => { + const result = Format.convertToLong(1.0); + result.should.deep.equal(Long.fromValue(1)); + }); + + it('should return the Long value', () => { + const result = Format.convertToLong(0.0); + result.should.deep.equal(Long.fromValue(0)); + }); +}); diff --git a/fabric-common/index.js b/fabric-common/index.js index 8439e2a166..43a68d6fb1 100644 --- a/fabric-common/index.js +++ b/fabric-common/index.js @@ -13,6 +13,10 @@ const Key = require('./lib/Key'); const KeyValueStore = require('./lib/KeyValueStore'); const Signer = require('./lib/Signer'); const SigningIdentity = require('./lib/SigningIdentity'); +const Utils = require('./lib/Utils'); +const User = require('./lib/User'); +const BaseClient = require('./lib/BaseClient'); +const MSP = require('./lib/Msp'); module.exports = { Config, @@ -23,5 +27,9 @@ module.exports = { Key, KeyValueStore, Signer, - SigningIdentity + SigningIdentity, + Utils, + User, + BaseClient, + MSP }; diff --git a/fabric-client/lib/BaseClient.js b/fabric-common/lib/BaseClient.js similarity index 93% rename from fabric-client/lib/BaseClient.js rename to fabric-common/lib/BaseClient.js index 5d9fc3b371..d47827583b 100644 --- a/fabric-client/lib/BaseClient.js +++ b/fabric-common/lib/BaseClient.js @@ -1,20 +1,10 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; -const sdkUtils = require('./utils.js'); +const sdkUtils = require('./Utils'); /** * Base class for a client that can use a {@link CryptoSuite} to sign and hash. @@ -31,7 +21,7 @@ const BaseClient = class { /** * @typedef {Object} CryptoSetting * @property {boolean} software Whether to load a software-based implementation (true) or HSM implementation (false) - * default is true (for software based implementation), specific implementation module is specified + * default is true (for software based implementation), specific implementation module is specified * in the setting 'crypto-suite-software' * @property {number} keysize The key size to use for the crypto suite instance. default is value of the setting 'crypto-keysize' * @property {string} algorithm Digital signature algorithm, currently supporting ECDSA only with value 'EC' @@ -152,6 +142,7 @@ const BaseClient = class { return sdkUtils.getConfigSetting(name, default_value); } + // make available from the client instance getConfigSetting(name, default_value) { @@ -185,6 +176,7 @@ const BaseClient = class { static setConfigSetting(name, value) { sdkUtils.setConfigSetting(name, value); } + // make available from the client instance setConfigSetting(name, value) { BaseClient.setConfigSetting(name, value); diff --git a/fabric-client/lib/msp/msp.js b/fabric-common/lib/Msp.js similarity index 85% rename from fabric-client/lib/msp/msp.js rename to fabric-common/lib/Msp.js index 760c8c8b0b..babede0669 100755 --- a/fabric-client/lib/msp/msp.js +++ b/fabric-common/lib/Msp.js @@ -5,8 +5,10 @@ */ 'use strict'; -const {CryptoAlgorithms, Identity, SigningIdentity} = require('fabric-common'); -const utils = require('../utils.js'); +const CryptoAlgorithms = require('./CryptoAlgorithms'); +const Identity = require('./Identity'); +const SigningIdentity = require('./SigningIdentity'); +const utils = require('./Utils'); const logger = utils.getLogger('msp.js'); const fabprotos = require('fabric-protos'); @@ -23,15 +25,15 @@ const MSP = class { * Setup the MSP instance according to configuration information * @param {Object} config A configuration object specific to the implementation. For this * implementation it uses the following fields: - *
`rootCerts`: array of {@link Identity} representing trust anchors for validating + *
`rootCerts`: array of {@link Identity} representing trust anchors for validating * signing certificates. Required for MSPs used in verifying signatures - *
`intermediateCerts`: array of {@link Identity} representing trust anchors for validating + *
`intermediateCerts`: array of {@link Identity} representing trust anchors for validating * signing certificates. optional for MSPs used in verifying signatures - *
`admins`: array of {@link Identity} representing admin privileges - *
`signer`: {@link SigningIdentity} signing identity. Required for MSPs used in signing - *
`id`: {string} value for the identifier of this instance - *
`orgs`: {string} array of organizational unit identifiers - *
`cryptoSuite': the underlying {@link module:api.CryptoSuite} for crypto primitive operations + *
`admins`: array of {@link Identity} representing admin privileges + *
`signer`: {@link SigningIdentity} signing identity. Required for MSPs used in signing + *
`id`: {string} value for the identifier of this instance + *
`orgs`: {string} array of organizational unit identifiers + *
`cryptoSuite': the underlying {@link module:api.CryptoSuite} for crypto primitive operations */ constructor(config) { logger.debug('const - start'); @@ -135,7 +137,7 @@ const MSP = class { /** * DeserializeIdentity deserializes an identity * @param {byte[]} serializedIdentity - A protobuf-based serialization of an object with - * two fields: mspid and idBytes for certificate PEM bytes + * two fields: mspid and idBytes for certificate PEM bytes * @param {boolean} storeKey - if the user should be stored in the key store. Only when * false will a promise not be returned * @returns {Promise} Promise for an {@link Identity} instance or diff --git a/fabric-client/lib/User.js b/fabric-common/lib/User.js similarity index 90% rename from fabric-client/lib/User.js rename to fabric-common/lib/User.js index 77b4819937..e5d3b60dab 100644 --- a/fabric-client/lib/User.js +++ b/fabric-common/lib/User.js @@ -1,29 +1,22 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +/** + * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; const util = require('util'); -const sdkUtils = require('./utils.js'); -const {CryptoAlgorithms, Identity, Signer, SigningIdentity} = require('fabric-common'); +const CryptoAlgorithms = require('./CryptoAlgorithms'); +const Identity = require('./Identity'); +const Signer = require('./Signer'); +const SigningIdentity = require('./SigningIdentity'); +const sdkUtils = require('./Utils'); const logger = sdkUtils.getLogger('User.js'); /** * The User class represents users that have been enrolled and represented by * an enrollment certificate (ECert) and a signing key. The ECert must have * been signed by one of the CAs the blockchain network has been configured to trust. - * An enrolled user (having a signing key and ECert) can conduct chaincode instantiate, + * An enrolled Admin user (having a signing key and ECert) can conduct chaincode instantiate, * transactions and queries with the Channel. * * User ECerts can be obtained from a CA beforehand as part of installing and instantiating @@ -33,7 +26,7 @@ const logger = sdkUtils.getLogger('User.js'); * Sometimes User identities are confused with Peer identities. User identities represent * signing capability because it has access to the private key, while Peer identities in * the context of the application/SDK only has the certificate for verifying signatures. - * An application cannot use the Peer identity to sign things because the application doesn’t + * An application cannot use the Peer identity to sign things because the application does not * have access to the Peer identity’s private key. * * @class @@ -43,18 +36,18 @@ const User = class { /** * Constructor for a member. * - * @param {string} cfg - The member name or an object with the following attributes: + * @param {string|Object} cfg - The member name or an object with the following attributes: * - enrollmentID {string}: user name * - name {string}: user name, if "enrollmentID" is also specified, the "name" is ignored * - roles {string[]}: optional. array of roles * - affiliation {string}: optional. affiliation with a group or organization */ constructor(cfg) { - if (util.isString(cfg)) { + if (typeof cfg === 'string') { this._name = cfg; this._roles = null; // string[] this._affiliation = ''; - } else if (util.isObject(cfg)) { + } else if (cfg !== null && typeof cfg === 'object') { const req = cfg; this._name = req.enrollmentID || req.name; this._roles = req.roles || ['fabric.user']; diff --git a/fabric-client/lib/utils.js b/fabric-common/lib/Utils.js similarity index 91% rename from fabric-client/lib/utils.js rename to fabric-common/lib/Utils.js index 071f14fe9b..70376e11fc 100644 --- a/fabric-client/lib/utils.js +++ b/fabric-common/lib/Utils.js @@ -12,9 +12,8 @@ const winston = require('winston'); const crypto = require('crypto'); const path = require('path'); const os = require('os'); -const Long = require('long'); -const {Config} = require('fabric-common'); +const Config = require('./Config'); const sjcl = require('sjcl'); // @@ -28,9 +27,9 @@ const sjcl = require('sjcl'); * - newCryptoSuite({keysize: 384}) * - newCryptoSuite() * @param {Object} setting This optional parameter is an object with the following optional properties: - * - software {boolean}: Whether to load a software-based implementation (true) or HSM implementation (false) - * default is true (for software based implementation), specific implementation module is specified - * in the setting 'crypto-suite-software' + * - software {boolean}: Whether to load a software-based implementation (true) or HSM implementation (false) + * default is true (for software based implementation), specific implementation module is specified + * in the setting 'crypto-suite-software' * - keysize {number}: The key size to use for the crypto suite instance. default is value of the setting 'crypto-keysize' * - algorithm {string}: Digital signature algorithm, currently supporting ECDSA only with value "EC" * - hash {string}: 'SHA2' or 'SHA3' @@ -394,13 +393,13 @@ const CryptoKeyStore = function (KVSImplClass, opts) { }; this._getKeyStore = async function () { - const CKS = require('fabric-client/lib/impl/CryptoKeyStore'); + const CKS = require('./impl/CryptoKeyStore'); if (this._store === null) { this.logger.debug(util.format('This class requires a CryptoKeyStore to save keys, using the store: %j', this._storeConfig)); try { - this._store = await CKS(this._storeConfig.superClass, this._storeConfig.opts); + this._store = await CKS(this._storeConfig.superClass, this._storeConfig.opts); await this._store.initialize(); return this._store; } catch (err) { @@ -492,36 +491,6 @@ module.exports.pemToDER = (pem) => { return hex; }; - -/* - * Converts to a Long number - * Returns a null if the incoming value is not a string that represents a - * number or an actual javascript number. Also allows for a Long object to be - * passed in as the value to convert - */ -module.exports.convertToLong = (value) => { - let result; - if (Long.isLong(value)) { - result = value; // already a long - } else if (typeof value !== 'undefined' && value !== null) { - result = Long.fromValue(value); - // Long will return a zero for invalid strings so make sure we did - // not get a real zero as the incoming value - if (result.equals(Long.ZERO)) { - if (Number.isInteger(value) || value === '0') { - // all good - } else { - // anything else must be a string that is not a valid number - throw new Error(util.format('value:%s is not a valid number ', value)); - } - } - } else { - throw new Error('value parameter is missing'); - } - - return result; -}; - module.exports.checkIntegerConfig = (opts, configName) => { let result = false; if (opts && opts[configName]) { diff --git a/fabric-client/lib/impl/CouchDBKeyValueStore.js b/fabric-common/lib/impl/CouchDBKeyValueStore.js similarity index 97% rename from fabric-client/lib/impl/CouchDBKeyValueStore.js rename to fabric-common/lib/impl/CouchDBKeyValueStore.js index 5310b0abdf..322dae57b4 100644 --- a/fabric-client/lib/impl/CouchDBKeyValueStore.js +++ b/fabric-common/lib/impl/CouchDBKeyValueStore.js @@ -7,9 +7,8 @@ 'use strict'; -const {KeyValueStore} = require('fabric-common'); +const {KeyValueStore, Utils: utils} = require('fabric-common'); const util = require('util'); -const utils = require('../utils'); const nano = require('nano'); const logger = utils.getLogger('CouchDBKeyValueStore.js'); diff --git a/fabric-client/lib/impl/CryptoKeyStore.js b/fabric-common/lib/impl/CryptoKeyStore.js similarity index 96% rename from fabric-client/lib/impl/CryptoKeyStore.js rename to fabric-common/lib/impl/CryptoKeyStore.js index 208e9f4662..2b1193d062 100644 --- a/fabric-client/lib/impl/CryptoKeyStore.js +++ b/fabric-common/lib/impl/CryptoKeyStore.js @@ -6,10 +6,10 @@ */ 'use strict'; +const {Utils: utils} = require('fabric-common'); const jsrsasign = require('jsrsasign'); const KEYUTIL = jsrsasign.KEYUTIL; -const utils = require('../utils.js'); const ECDSAKey = require('./ecdsa/key.js'); /* @@ -68,7 +68,7 @@ const CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { * * @class */ -const CryptoKeyStore = function(KVSImplClass, opts) { +const CryptoKeyStore = function (KVSImplClass, opts) { let superClass; if (typeof KVSImplClass !== 'function') { @@ -86,7 +86,8 @@ const CryptoKeyStore = function(KVSImplClass, opts) { opts = KVSImplClass; } - const MyClass = class extends CryptoKeyStoreMixin(superClass) {}; + const MyClass = class extends CryptoKeyStoreMixin(superClass) { + }; return new MyClass(opts); }; diff --git a/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js b/fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js similarity index 97% rename from fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js rename to fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js index 37b76ab440..18884379b8 100755 --- a/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js +++ b/fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js @@ -8,14 +8,13 @@ 'use strict'; // requires -const {CryptoAlgorithms, CryptoSuite, HashPrimitives} = require('fabric-common'); +const {CryptoAlgorithms, CryptoSuite, HashPrimitives, Utils: utils} = require('fabric-common'); const elliptic = require('elliptic'); const EC = elliptic.ec; const jsrsa = require('jsrsasign'); const {KEYUTIL} = jsrsa; const util = require('util'); const Signature = require('elliptic/lib/elliptic/ec/signature.js'); -const utils = require('../utils'); const ECDSAKey = require('./ecdsa/key.js'); const logger = utils.getLogger('crypto_ecdsa_aes'); @@ -150,10 +149,10 @@ class CryptoSuite_ECDSA_AES extends CryptoSuite { /** * This is an implementation of {@link module:api.CryptoSuite#importKey} * Attempt to import the raw content, assuming it's one of the following: - * X.509v1/v3 PEM certificate (RSA/DSA/ECC) - * PKCS#8 PEM RSA/DSA/ECC public key - * PKCS#5 plain PEM DSA/RSA private key - * PKCS#8 plain PEM RSA/ECDSA private key + * X.509v1/v3 PEM certificate (RSA/DSA/ECC) + * PKCS#8 PEM RSA/DSA/ECC public key + * PKCS#5 plain PEM DSA/RSA private key + * PKCS#8 plain PEM RSA/ECDSA private key */ async importKey(pem) { diff --git a/fabric-client/lib/impl/FileKeyValueStore.js b/fabric-common/lib/impl/FileKeyValueStore.js similarity index 95% rename from fabric-client/lib/impl/FileKeyValueStore.js rename to fabric-common/lib/impl/FileKeyValueStore.js index cd0edb1f30..015cb66679 100644 --- a/fabric-client/lib/impl/FileKeyValueStore.js +++ b/fabric-common/lib/impl/FileKeyValueStore.js @@ -7,10 +7,9 @@ 'use strict'; -const {KeyValueStore} = require('fabric-common'); +const {KeyValueStore, Utils: utils} = require('fabric-common'); const fs = require('fs-extra'); const path = require('path'); -const utils = require('../utils'); const logger = utils.getLogger('FileKeyValueStore.js'); diff --git a/fabric-client/lib/impl/aes/pkcs11_key.js b/fabric-common/lib/impl/aes/pkcs11_key.js similarity index 100% rename from fabric-client/lib/impl/aes/pkcs11_key.js rename to fabric-common/lib/impl/aes/pkcs11_key.js diff --git a/fabric-client/lib/impl/bccsp_pkcs11.js b/fabric-common/lib/impl/bccsp_pkcs11.js similarity index 98% rename from fabric-client/lib/impl/bccsp_pkcs11.js rename to fabric-common/lib/impl/bccsp_pkcs11.js index d62e2555a4..49f3cf9290 100644 --- a/fabric-client/lib/impl/bccsp_pkcs11.js +++ b/fabric-common/lib/impl/bccsp_pkcs11.js @@ -7,8 +7,8 @@ 'use strict'; -const {CryptoAlgorithms, CryptoSuite, HashPrimitives} = require('fabric-common'); -const utils = require('../utils'); +const {CryptoAlgorithms, CryptoSuite, HashPrimitives, Utils: utils} = require('fabric-common'); + const aesKey = require('./aes/pkcs11_key.js'); const ecdsaKey = require('./ecdsa/pkcs11_key.js'); @@ -76,7 +76,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { * pin: string, // the user's PIN * usertype: number, // the user type * readwrite: boolean // true if the session is read/write or false if read-only - * } + * } * * If 'lib' is not specified or null, its value will be taken from the * CRYPTO_PKCS11_LIB env var, and if the env var is not set, its value will @@ -366,7 +366,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { * private key pair. */ {type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login}, - {type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token}, + {type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token} ]; try { @@ -387,7 +387,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { {type: pkcs11js.CKA_ENCRYPT}, {type: pkcs11js.CKA_DECRYPT}, {type: pkcs11js.CKA_PRIVATE}, - {type: pkcs11js.CKA_TOKEN}, + {type: pkcs11js.CKA_TOKEN} ]; logger.debug(__func() + 'secretKey: ' + util.inspect( this._pkcs11GetAttributeValue( @@ -414,7 +414,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { {type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login}, {type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token}, {type: pkcs11js.CKA_SIGN, value: true}, - {type: pkcs11js.CKA_DERIVE, value: true}, + {type: pkcs11js.CKA_DERIVE, value: true} ]; const publicKeyTemplate = [ // { type: pkcs11js.CKA_ID, value: ski }, @@ -426,7 +426,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { { type: pkcs11js.CKA_EC_PARAMS, value: Buffer.from(_pkcs11ParamsSizeToOid[this._keySize], 'hex') - }, + } ]; try { @@ -446,7 +446,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { {type: pkcs11js.CKA_CLASS}, {type: pkcs11js.CKA_KEY_TYPE}, {type: pkcs11js.CKA_PRIVATE}, - {type: pkcs11js.CKA_TOKEN}, + {type: pkcs11js.CKA_TOKEN} ]; logger.debug(__func() + 'privateKey: ' + util.inspect( this._pkcs11GetAttributeValue( @@ -511,7 +511,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { const secretKeyHandle = this._pkcs11FindObjects(pkcs11, pkcs11Session, [ {type: pkcs11js.CKA_ID, value: ski}, {type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY}, - {type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES}, + {type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES} ]); if (secretKeyHandle.length === 1) { return {secretKey: secretKeyHandle[0]}; @@ -522,12 +522,12 @@ class CryptoSuite_PKCS11 extends CryptoSuite { const privKeyHandle = this._pkcs11FindObjects(pkcs11, pkcs11Session, [ {type: pkcs11js.CKA_ID, value: ski}, {type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PRIVATE_KEY}, - {type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC}, + {type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC} ]); const pubKeyHandle = this._pkcs11FindObjects(pkcs11, pkcs11Session, [ {type: pkcs11js.CKA_ID, value: ski}, {type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PUBLIC_KEY}, - {type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC}, + {type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC} ]); if (pubKeyHandle.length !== 1 || privKeyHandle.length !== 1) { throw new Error(__func() + 'no key with SKI ' + @@ -553,7 +553,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { this._pkcs11, this._pkcs11Session, publicKey, [ {type: pkcs11js.CKA_EC_PARAMS}, - {type: pkcs11js.CKA_EC_POINT}, + {type: pkcs11js.CKA_EC_POINT} ]); logger.debug(__func() + 'attribuites: ' + util.inspect(attribs, {depth: null})); @@ -700,7 +700,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { {type: pkcs11js.CKA_ENCRYPT, value: true}, {type: pkcs11js.CKA_DECRYPT, value: true}, {type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login}, - {type: pkcs11js.CKA_TOKEN, value: false}, + {type: pkcs11js.CKA_TOKEN, value: false} ]; try { @@ -711,7 +711,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { parameter: { type: pkcs11js.CK_PARAMS_EC_DH, kdf: pkcs11js.CKD_SHA256_KDF, - publicData: pub._ecpt, + publicData: pub._ecpt } }, key._handle, derivedKeyTemplate); @@ -732,7 +732,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { {type: pkcs11js.CKA_ENCRYPT, value: true}, {type: pkcs11js.CKA_DECRYPT, value: true}, {type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login}, - {type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token}, + {type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token} ]; try { @@ -774,7 +774,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { {type: pkcs11js.CKA_KEY_TYPE}, {type: pkcs11js.CKA_PRIVATE}, {type: pkcs11js.CKA_TOKEN}, - {type: pkcs11js.CKA_ID}, + {type: pkcs11js.CKA_ID} ]; logger.debug(__func() + 'obj: ' + util.inspect(obj, {depth: null})); logger.debug(__func() + 'attr: ' + @@ -911,8 +911,7 @@ class CryptoSuite_PKCS11 extends CryptoSuite { handle.publicKey); const keySize = _pkcs11ParamsOidToSize[ - attr.ecparams.toString('hex'). - toUpperCase()]; + attr.ecparams.toString('hex').toUpperCase()]; if (keySize === undefined || keySize !== self._keySize) { throw new Error(__func() + ' key size mismatch, class: ' + self._keySize + ', ski: ' + keySize); diff --git a/fabric-client/lib/impl/ecdsa/key.js b/fabric-common/lib/impl/ecdsa/key.js similarity index 98% rename from fabric-client/lib/impl/ecdsa/key.js rename to fabric-common/lib/impl/ecdsa/key.js index d1d27ce072..07f27b1fb4 100644 --- a/fabric-client/lib/impl/ecdsa/key.js +++ b/fabric-common/lib/impl/ecdsa/key.js @@ -7,13 +7,12 @@ 'use strict'; -const utils = require('../../utils.js'); +const {HashPrimitives, Key, Utils: utils} = require('fabric-common'); const jsrsa = require('jsrsasign'); const asn1 = jsrsa.asn1; const KEYUTIL = jsrsa.KEYUTIL; const ECDSA = jsrsa.ECDSA; const jws = jsrsa.jws; -const {HashPrimitives, Key} = require('fabric-common'); const logger = utils.getLogger('ecdsa/key.js'); /** diff --git a/fabric-client/lib/impl/ecdsa/pkcs11_key.js b/fabric-common/lib/impl/ecdsa/pkcs11_key.js similarity index 100% rename from fabric-client/lib/impl/ecdsa/pkcs11_key.js rename to fabric-common/lib/impl/ecdsa/pkcs11_key.js diff --git a/fabric-common/package.json b/fabric-common/package.json index 953c2894d8..089366c34f 100644 --- a/fabric-common/package.json +++ b/fabric-common/package.json @@ -21,7 +21,9 @@ "test": "nyc mocha --exclude 'test/data/**/*.js' --recursive -t 10000" }, "dependencies": { - "nconf": "^0.10.0" + "winston": "^2.2.0", + "nconf": "^0.10.0", + "sjcl": "1.0.7" }, "devDependencies": { "chai": "^4.1.2", diff --git a/fabric-network/lib/impl/event/abstracteventlistener.js b/fabric-network/lib/impl/event/abstracteventlistener.js index 1d94d2add7..167a0b4a0e 100644 --- a/fabric-network/lib/impl/event/abstracteventlistener.js +++ b/fabric-network/lib/impl/event/abstracteventlistener.js @@ -9,7 +9,8 @@ const Long = require('long'); const EventHubDisconnectError = require('fabric-client/lib/errors/EventHubDisconnectError'); const BaseCheckpointer = require('./basecheckpointer'); -const logger = require('fabric-client/lib/utils').getLogger('AbstractEventListener'); +const {Utils} = require('fabric-common'); +const logger = Utils.getLogger('AbstractEventListener'); /** * @typedef {Object} module:fabric-network.Network~ListenerOptions diff --git a/fabric-network/lib/impl/wallet/couchdbwallet.js b/fabric-network/lib/impl/wallet/couchdbwallet.js index 245e9144c2..5a3486c8cf 100644 --- a/fabric-network/lib/impl/wallet/couchdbwallet.js +++ b/fabric-network/lib/impl/wallet/couchdbwallet.js @@ -7,7 +7,7 @@ const Client = require('fabric-client'); const BaseWallet = require('./basewallet'); -const CouchDBVStore = require('fabric-client/lib/impl/CouchDBKeyValueStore'); +const CouchDBVStore = require('fabric-common/lib/impl/CouchDBKeyValueStore'); const logger = require('../../logger').getLogger('CouchDBWallet'); const Nano = require('nano'); diff --git a/fabric-network/lib/impl/wallet/filesystemwallet.js b/fabric-network/lib/impl/wallet/filesystemwallet.js index 2d6d2e8cf4..707011370e 100644 --- a/fabric-network/lib/impl/wallet/filesystemwallet.js +++ b/fabric-network/lib/impl/wallet/filesystemwallet.js @@ -10,7 +10,7 @@ const rimraf = require('rimraf'); const fs = require('fs-extra'); const Path = require('path'); const BaseWallet = require('./basewallet'); -const FileKVS = require('fabric-client/lib/impl/FileKeyValueStore'); +const FileKVS = require('fabric-common/lib/impl/FileKeyValueStore'); const logger = require('../../logger').getLogger('FileSystemWallet'); /** diff --git a/fabric-network/lib/impl/wallet/hsmwalletmixin.js b/fabric-network/lib/impl/wallet/hsmwalletmixin.js index b4affbbe55..a42359c034 100644 --- a/fabric-network/lib/impl/wallet/hsmwalletmixin.js +++ b/fabric-network/lib/impl/wallet/hsmwalletmixin.js @@ -7,7 +7,7 @@ const Client = require('fabric-client'); const {KEYUTIL} = require('jsrsasign'); -const ecdsaKey = require('fabric-client/lib/impl/ecdsa/key.js'); +const ecdsaKey = require('fabric-common/lib/impl/ecdsa/key.js'); const HSMSuite = new Map(); diff --git a/fabric-network/lib/logger.js b/fabric-network/lib/logger.js index 632ef80bc8..f2637d6347 100644 --- a/fabric-network/lib/logger.js +++ b/fabric-network/lib/logger.js @@ -8,5 +8,5 @@ // reuse the client implementation of the logger as we are part of the client // abstracted out in case we want to change this in the future. -const sdkUtils = require('fabric-client/lib/utils'); -module.exports.getLogger = sdkUtils.getLogger; \ No newline at end of file +const {Utils} = require('fabric-common'); +module.exports.getLogger = Utils.getLogger; diff --git a/fabric-network/package.json b/fabric-network/package.json index 0346b86ec1..3474efbc4a 100644 --- a/fabric-network/package.json +++ b/fabric-network/package.json @@ -24,6 +24,7 @@ "dependencies": { "fabric-client": "file:../fabric-client", "fabric-ca-client": "file:../fabric-ca-client", + "fabric-common": "file:../fabric-common", "nano": "^6.4.4", "rimraf": "^2.6.2", "uuid": "^3.2.1" diff --git a/fabric-network/test/impl/wallet/couchdbwallet.js b/fabric-network/test/impl/wallet/couchdbwallet.js index 6eb466dc60..544e7afb8c 100644 --- a/fabric-network/test/impl/wallet/couchdbwallet.js +++ b/fabric-network/test/impl/wallet/couchdbwallet.js @@ -186,7 +186,7 @@ describe('CouchDBWalletKeyValueStore', () => { let kvs; before(() => { CouchDBWallet = proxyquire('../../../lib/impl/wallet/couchdbwallet', { - 'fabric-client/lib/impl/CouchDBKeyValueStore': class {} + 'fabric-common/lib/impl/CouchDBKeyValueStore': class {} }); }); beforeEach(() => { diff --git a/fabric-network/test/impl/wallet/hsmwalletmixin.js b/fabric-network/test/impl/wallet/hsmwalletmixin.js index aa45de1cb2..1783a4c6f6 100644 --- a/fabric-network/test/impl/wallet/hsmwalletmixin.js +++ b/fabric-network/test/impl/wallet/hsmwalletmixin.js @@ -13,8 +13,7 @@ const should = chai.should(); const rewire = require('rewire'); const Client = require('fabric-client'); -const {CryptoSuite, KeyValueStore} = require('fabric-common'); -const User = require('fabric-client/lib/User'); +const {CryptoSuite, KeyValueStore, User} = require('fabric-common'); const HSMWalletMixin = rewire('./../../../lib/impl/wallet/hsmwalletmixin'); const {KEYUTIL} = require('jsrsasign'); diff --git a/fabric-protos/grpc.js b/fabric-protos/grpc.js new file mode 100644 index 0000000000..7681d27765 --- /dev/null +++ b/fabric-protos/grpc.js @@ -0,0 +1 @@ +module.exports = require('grpc'); diff --git a/test/fixtures/credentials/cloudant.json b/test/fixtures/credentials/cloudant.json index ddf4f9b5d9..c416c87546 100644 --- a/test/fixtures/credentials/cloudant.json +++ b/test/fixtures/credentials/cloudant.json @@ -2,5 +2,5 @@ "cloudant-username" : "1421acc7-6faa-491a-8e10-951e2e190684-bluemix", "cloudant-password" : "7179ef7a72602189243deeabe207889bde1c2fada173ae1022b5592e5a79dacc", "cloudant-bluemix" : "@1421acc7-6faa-491a-8e10-951e2e190684-bluemix.cloudant.com", - "key-value-store" : "fabric-client/lib/impl/CouchDBKeyValueStore.js" -} \ No newline at end of file + "key-value-store" : "fabric-common/lib/impl/CouchDBKeyValueStore.js" +} diff --git a/test/fixtures/credentials/couchdb.json b/test/fixtures/credentials/couchdb.json index 76f2ee7c6d..bb081c48c0 100644 --- a/test/fixtures/credentials/couchdb.json +++ b/test/fixtures/credentials/couchdb.json @@ -1,5 +1,5 @@ { "couchdb-ip-addr" : "http://localhost", "couchdb-port" : "5984", - "key-value-store" : "fabric-client/lib/impl/CouchDBKeyValueStore.js" + "key-value-store" : "fabric-common/lib/impl/CouchDBKeyValueStore.js" } diff --git a/test/integration/channel-event-hub.js b/test/integration/channel-event-hub.js index b9b955a434..0646626407 100644 --- a/test/integration/channel-event-hub.js +++ b/test/integration/channel-event-hub.js @@ -6,7 +6,7 @@ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('channel-event-hub'); const tape = require('tape'); diff --git a/test/integration/client.js b/test/integration/client.js index 551634c032..d7ebdf27fd 100644 --- a/test/integration/client.js +++ b/test/integration/client.js @@ -6,7 +6,7 @@ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('integration.client'); const tape = require('tape'); @@ -28,7 +28,7 @@ test('\n\n ** createUser happy path - file store **\n\n', (t) => { Client.addConfigFile(path.join(__dirname, '../fixtures/profiles/caimport.json')); caImport = utils.getConfigSetting('ca-import', 'notfound'); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); utils.setConfigSetting('crypto-keysize', 256); const userOrg = 'org1'; @@ -81,7 +81,7 @@ test('\n\n ** createUser happy path - CouchDB **\n\n', (t) => { // Use the CouchDB specific config file Client.addConfigFile('test/fixtures/credentials/couchdb.json'); utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/CouchDBKeyValueStore.js');// override + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/CouchDBKeyValueStore.js');// override const couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); const couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); const keyValStorePath = couchdbIPAddr + ':' + couchdbPort; @@ -133,7 +133,7 @@ test('\n\n ** createUser happy path - Cloudant **\n\n', (t) => { // Use the Cloudant specific config file Client.addConfigFile('test/fixtures/credentials/cloudant.json'); utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/CouchDBKeyValueStore.js');// override + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/CouchDBKeyValueStore.js');// override const cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); const cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); const cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); @@ -185,7 +185,7 @@ test('\n\n ** createUser happy path - Cloudant - PEM Strings **\n\n', (t) => { // Use the Cloudant specific config file Client.addConfigFile('test/fixtures/credentials/cloudant.json'); utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/CouchDBKeyValueStore.js');// override + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/CouchDBKeyValueStore.js');// override const cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); const cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); const cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); diff --git a/test/integration/cloudant-fabricca-tests.js b/test/integration/cloudant-fabricca-tests.js index caa5bb555d..681b4de970 100644 --- a/test/integration/cloudant-fabricca-tests.js +++ b/test/integration/cloudant-fabricca-tests.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils, User} = require('fabric-common'); const logger = utils.getLogger('cloudant-fabricca'); const tape = require('tape'); @@ -13,7 +13,6 @@ const test = _test(tape); 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'); @@ -61,7 +60,7 @@ test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', (t) => { // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/CouchDBKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/CouchDBKeyValueStore.js'); // Clean up the cloudant couchdb test database const dbname = 'member_db'; diff --git a/test/integration/configtxlator.js b/test/integration/configtxlator.js index b8609c744a..0f10ca3d86 100644 --- a/test/integration/configtxlator.js +++ b/test/integration/configtxlator.js @@ -15,7 +15,7 @@ * superagent * superagent-promise */ -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('configinator'); const tape = require('tape'); @@ -60,7 +60,7 @@ test('\n\n***** configtxlator flow for create and then update *****\n\n', async // Acting as a client in org1 when creating the channel const org = ORGS.org1.name; - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); try { const tlsInfo = await e2eUtils.tlsEnroll(org); diff --git a/test/integration/couchdb-fabricca-tests.js b/test/integration/couchdb-fabricca-tests.js index 0c6818c45a..8497b5b68a 100644 --- a/test/integration/couchdb-fabricca-tests.js +++ b/test/integration/couchdb-fabricca-tests.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils, User} = require('fabric-common'); const logger = utils.getLogger('couchdb-fabricca'); const tape = require('tape'); @@ -14,7 +14,6 @@ const test = _test(tape); 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'); @@ -66,7 +65,7 @@ test('Use FabricCAServices with a CouchDB KeyValueStore', (t) => { // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/CouchDBKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/CouchDBKeyValueStore.js'); // Clean up the couchdb test database const dbname = 'my_member_db'; diff --git a/test/integration/create-configtx-channel.js b/test/integration/create-configtx-channel.js index 1ab2460e13..87ad76578b 100644 --- a/test/integration/create-configtx-channel.js +++ b/test/integration/create-configtx-channel.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E create-channel'); const tape = require('tape'); @@ -50,7 +50,7 @@ test('\n\n***** Configtx Built config create flow *****\n\n', (t) => { // Acting as a client in org1 when creating the channel const org = ORGS.org1.name; - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); return e2eUtils.tlsEnroll('org1') .then((enrollment) => { diff --git a/test/integration/discovery.js b/test/integration/discovery.js index 1f22989a36..70bc937630 100644 --- a/test/integration/discovery.js +++ b/test/integration/discovery.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('DISCOVERY'); const tape = require('tape'); diff --git a/test/integration/e2e/create-channel.js b/test/integration/e2e/create-channel.js index 775c850c43..944fa1fe5b 100644 --- a/test/integration/e2e/create-channel.js +++ b/test/integration/e2e/create-channel.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E create-channel'); const tape = require('tape'); @@ -42,7 +42,7 @@ test('\n\n***** SDK Built config update create flow *****\n\n', async (t) => { // Acting as a client in org1 when creating the channel const org = ORGS.org1.name; - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); const tlsInfo = await e2eUtils.tlsEnroll('org1'); t.pass('Successfully retrieved TLS certificate'); diff --git a/test/integration/e2e/e2eUtils.js b/test/integration/e2e/e2eUtils.js index 21d2160ea9..457ec31d0d 100644 --- a/test/integration/e2e/e2eUtils.js +++ b/test/integration/e2e/e2eUtils.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; const FabricCAServices = require('../../../fabric-ca-client'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E testing'); const path = require('path'); diff --git a/test/integration/e2e/install-chaincode-fail.js b/test/integration/e2e/install-chaincode-fail.js index 3f619a0327..d685277f0e 100644 --- a/test/integration/e2e/install-chaincode-fail.js +++ b/test/integration/e2e/install-chaincode-fail.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E install-chaincode-fail'); const tape = require('tape'); diff --git a/test/integration/e2e/install-chaincode.js b/test/integration/e2e/install-chaincode.js index cc73435230..b18a6091f2 100644 --- a/test/integration/e2e/install-chaincode.js +++ b/test/integration/e2e/install-chaincode.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E install-chaincode'); const tape = require('tape'); diff --git a/test/integration/e2e/instantiate-chaincode.js b/test/integration/e2e/instantiate-chaincode.js index 4403029734..0adea99ea8 100644 --- a/test/integration/e2e/instantiate-chaincode.js +++ b/test/integration/e2e/instantiate-chaincode.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E instantiate-chaincode'); const tape = require('tape'); diff --git a/test/integration/e2e/join-channel.js b/test/integration/e2e/join-channel.js index 52933ea994..300496fee0 100644 --- a/test/integration/e2e/join-channel.js +++ b/test/integration/e2e/join-channel.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E join-channel'); const tape = require('tape'); diff --git a/test/integration/e2e/private-data.js b/test/integration/e2e/private-data.js index 434a143623..29b0942977 100755 --- a/test/integration/e2e/private-data.js +++ b/test/integration/e2e/private-data.js @@ -10,7 +10,7 @@ // Prerequisite: a chaincode reading/writing private data, install-channel.js and join-channels.js 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E private-data'); const tape = require('tape'); diff --git a/test/integration/e2e/updateAnchorPeers.js b/test/integration/e2e/updateAnchorPeers.js index cad9c1094b..b56936c64d 100644 --- a/test/integration/e2e/updateAnchorPeers.js +++ b/test/integration/e2e/updateAnchorPeers.js @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E setAnchorPeers'); const tape = require('tape'); @@ -61,7 +61,7 @@ test('\n\n***** End-to-end flow: setAnchorPeers *****\n\n', async (t) => { const data = fs.readFileSync(path.join(__dirname, caRootsPath)); const caroots = Buffer.from(data).toString(); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); const tlsInfo = await e2eUtils.tlsEnroll(org); client.setTlsClientCertAndKey(tlsInfo.certificate, tlsInfo.key); diff --git a/test/integration/eventutil.js b/test/integration/eventutil.js index a7f781510e..1ed915419d 100644 --- a/test/integration/eventutil.js +++ b/test/integration/eventutil.js @@ -6,7 +6,7 @@ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const util = require('util'); module.exports.registerTxEvent = function(eh, txid, timeout) { diff --git a/test/integration/fabric-ca-affiliation-service-tests.js b/test/integration/fabric-ca-affiliation-service-tests.js index b28bc513c2..65e100e110 100644 --- a/test/integration/fabric-ca-affiliation-service-tests.js +++ b/test/integration/fabric-ca-affiliation-service-tests.js @@ -9,7 +9,7 @@ const _test = require('tape-promise').default; const test = _test(tape); const path = require('path'); const FabricCAServices = require('../../fabric-ca-client'); -const User = require('../../fabric-ca-client/lib/User'); +const {User} = require('fabric-common'); const userOrg = 'org1'; const tlsOptions = { diff --git a/test/integration/fabric-ca-certificate-service-tests.js b/test/integration/fabric-ca-certificate-service-tests.js index e164db01f8..df92536ea6 100644 --- a/test/integration/fabric-ca-certificate-service-tests.js +++ b/test/integration/fabric-ca-certificate-service-tests.js @@ -9,7 +9,7 @@ const _test = require('tape-promise').default; const test = _test(tape); const path = require('path'); const FabricCAServices = require('../../fabric-ca-client/lib/FabricCAServices'); -const User = require('../../fabric-ca-client/lib/User'); +const {User} = require('fabric-common'); const {HFCAIdentityAttributes, HFCAIdentityType} = require('../../fabric-ca-client/lib/IdentityService'); const userOrg1 = 'org1'; diff --git a/test/integration/fabric-ca-identity-service-tests.js b/test/integration/fabric-ca-identity-service-tests.js index cded588ab2..7f53a8b94f 100644 --- a/test/integration/fabric-ca-identity-service-tests.js +++ b/test/integration/fabric-ca-identity-service-tests.js @@ -11,7 +11,7 @@ const path = require('path'); const FabricCAServices = require('../../fabric-ca-client'); const {HFCAIdentityAttributes, HFCAIdentityType} = require('../../fabric-ca-client/lib/IdentityService'); -const User = require('../../fabric-ca-client/lib/User'); +const {User} = require('fabric-common'); const userOrg1 = 'org1'; const userOrg2 = 'org2'; @@ -83,14 +83,20 @@ test('\n\n ** FabricCAServices - IdentityService Test **\n\n', async (t) => { let enrollment; // enroll the new created user at ca_Org1 - enrollment = await caService1.enroll({enrollmentID: testIdentity.enrollmentID, enrollmentSecret: testIdentity.enrollmentSecret}); + enrollment = await caService1.enroll({ + enrollmentID: testIdentity.enrollmentID, + enrollmentSecret: testIdentity.enrollmentSecret + }); t.pass(`Successfully enrolled ${testIdentity.enrollmentID} at ca_Org1`); const identity = new User(testIdentity.enrollmentID); await identity.setEnrollment(enrollment.key, enrollment.certificate, 'Org1MSP'); // should throw error if we enroll this new identity at ca_Org2 try { - enrollment = await caService2.enroll({enrollmentID: testIdentity.enrollmentID, enrollmentSecret: testIdentity.enrollmentSecret}); + enrollment = await caService2.enroll({ + enrollmentID: testIdentity.enrollmentID, + enrollmentSecret: testIdentity.enrollmentSecret + }); t.fail('should throw error if we enroll this new identity at ca_Org2'); t.end(); } catch (e) { diff --git a/test/integration/fabric-ca-services-tests.js b/test/integration/fabric-ca-services-tests.js index 9909813a44..d6e5ce7362 100644 --- a/test/integration/fabric-ca-services-tests.js +++ b/test/integration/fabric-ca-services-tests.js @@ -13,7 +13,7 @@ // the fabric-ca-client package by editing build/tasks/ca.js // /////////////////////////////////////////////////////////////// -const utils = require('fabric-client/lib/utils.js'); +const {Utils: utils, Signer, SigningIdentity, MSP, User} = require('fabric-common'); const logger = utils.getLogger('integration.client'); const tape = require('tape'); @@ -29,9 +29,6 @@ const http = require('http'); const testUtil = require('../unit/util.js'); -const LocalMSP = require('fabric-ca-client/lib/msp/msp.js'); -const {Signer, SigningIdentity} = require('fabric-common'); -const User = require('fabric-ca-client/lib/User.js'); // var keyValStorePath = testUtil.KVS; const FabricCAServices = require('fabric-ca-client/lib/FabricCAServices'); @@ -88,7 +85,7 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { }).then((pubKey) => { t.pass('Successfully imported public key from the resulting enrollment certificate'); - const msp = new LocalMSP({ + const msp = new MSP({ id: ORGS[userOrg].mspid, cryptoSuite: caService.getCryptoSuite() }); @@ -142,12 +139,16 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { return caService.revoke({enrollmentID: 'testUserX'}, member); }, (err) => { - t.fail('Failed to register "testUserX". ' + err.stack ? err.stack : err); + t.fail('Failed to register "testUserX". ' + err.stack ? err.stack : err); t.end(); }).then((response) => { t.equal(response.success, true, 'Successfully revoked "testUserX"'); - return caService.register({enrollmentID: 'testUserY', enrollmentSecret: 'testUserYSecret', affiliation: 'org2.department1'}, member); + return caService.register({ + enrollmentID: 'testUserY', + enrollmentSecret: 'testUserYSecret', + affiliation: 'org2.department1' + }, member); }, (err) => { t.fail('Failed to revoke "testUserX". ' + err.stack ? err.stack : err); t.end(); @@ -201,13 +202,14 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { affiliation: 'org1.department2', attrs: [ {name: 'hf.Registrar.Roles', value: 'client'}, - {name:'ecert', value:'default', ecert:true}, - {name:'test1attr', value:'test1attr'} - ]}, member); + {name: 'ecert', value: 'default', ecert: true}, + {name: 'test1attr', value: 'test1attr'} + ] + }, member); }).then((secret) => { t.pass('Successfully registered "test1" '); - return caService.enroll({enrollmentID: 'test1', enrollmentSecret: secret, attr_reqs :[]}); + return caService.enroll({enrollmentID: 'test1', enrollmentSecret: secret, attr_reqs: []}); }).then((enrollment) => { t.pass('Successfully enrolled "test1"'); @@ -220,9 +222,10 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { affiliation: 'org1.department2', attrs: [ {name: 'hf.Registrar.Roles', value: 'client'}, - {name:'ecert', value:'default', ecert:true}, - {name:'test2attr', value:'test2attr'} - ]}, member); + {name: 'ecert', value: 'default', ecert: true}, + {name: 'test2attr', value: 'test2attr'} + ] + }, member); }).then((secret) => { t.pass('Successfully registered "test2" '); @@ -239,13 +242,18 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { affiliation: 'org1.department2', attrs: [ {name: 'hf.Registrar.Roles', value: 'client'}, - {name:'ecert', value:'default', ecert:true}, - {name:'test3attr', value:'test3attr'} - ]}, member); + {name: 'ecert', value: 'default', ecert: true}, + {name: 'test3attr', value: 'test3attr'} + ] + }, member); }).then((secret) => { t.pass('Successfully registered "test3" '); - return caService.enroll({enrollmentID: 'test3', enrollmentSecret: secret, attr_reqs :[{name:'test3attr'}, {name:'ecert'}]}); + return caService.enroll({ + enrollmentID: 'test3', + enrollmentSecret: secret, + attr_reqs: [{name: 'test3attr'}, {name: 'ecert'}] + }); }).then((enrollment) => { t.pass('Successfully enrolled "test3"'); @@ -259,13 +267,18 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { attrs: [ {name: 'hf.Registrar.Roles', value: 'client'}, {name: 'hf.Registrar.Attributes', value: '*'}, - {name:'dfattrib', value:'default', ecert:true}, - {name:'myattrib', value:'somevalue and lots of other information'} - ]}, member); + {name: 'dfattrib', value: 'default', ecert: true}, + {name: 'myattrib', value: 'somevalue and lots of other information'} + ] + }, member); }).then((secret) => { t.pass('Successfully registered "webAdmin" who can register other users with no role'); - return caService.enroll({enrollmentID: 'webAdmin', enrollmentSecret: secret, attr_reqs :[{name:'myattrib', optional : false}]}); + return caService.enroll({ + enrollmentID: 'webAdmin', + enrollmentSecret: secret, + attr_reqs: [{name: 'myattrib', optional: false}] + }); }, (err) => { t.fail('Failed to register "webAdmin". ' + err.stack ? err.stack : err); t.end(); @@ -287,7 +300,11 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { }, (err) => { t.pass('Successfully rejected attempt to register a user of invalid role. ' + err); - return caService.register({enrollmentID: 'auditor', role: 'client', affiliation: 'org2.department1'}, webAdmin); + return caService.register({ + enrollmentID: 'auditor', + role: 'client', + affiliation: 'org2.department1' + }, webAdmin); }).then(() => { t.fail('Failed to capture the error when registering "auditor" of role "client" from "webAdmin" but using invalid affiliation'); }, (err) => { @@ -295,7 +312,11 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { t.pass('Successfully captured the error when registering "auditor" of role "client" from "webAdmin" but using invalid affiliation'); } - return caService.register({enrollmentID: 'auditor', role: 'client', affiliation: 'org1.department2'}, webAdmin); + return caService.register({ + enrollmentID: 'auditor', + role: 'client', + affiliation: 'org1.department2' + }, webAdmin); }).then(() => { t.pass('Successfully registered "auditor" of role "client" from "webAdmin"'); @@ -308,13 +329,13 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', (t) => { t.equal(typeof res.key !== 'undefined' && res.key !== null, true, 'Checking re-enroll response has the private key'); t.equal(typeof res.certificate !== 'undefined' && res.certificate !== null, true, 'Checking re-enroll response has the certificate'); - return caService.reenroll(webAdmin, [{name:'myattrib', require : true}]); + return caService.reenroll(webAdmin, [{name: 'myattrib', require: true}]); }).then((res) => { t.pass('Successfully re-enrolled "webAdmin" user with the request for attributes'); checkoutCertForAttributes(t, res.certificate, true, 'myattrib'); checkoutCertForAttributes(t, res.certificate, false, 'dfattrib'); - return caService.reenroll(webAdmin, [{name:'myattrib', require : true}, {name:'dfattrib'}]); + return caService.reenroll(webAdmin, [{name: 'myattrib', require: true}, {name: 'dfattrib'}]); }).then((res) => { t.pass('Successfully re-enrolled "webAdmin" user with the request for attributes'); checkoutCertForAttributes(t, res.certificate, true, 'myattrib'); @@ -398,7 +419,7 @@ test('\n\n ** FabricCAClient: Test enroll With a CSR **\n\n', async (t) => { const newUser = { enrollmentID: 'aTestUser', maxEnrollments: -1, - enrollmentSecret: 'userpw', + enrollmentSecret: 'userpw' }; await caService.register(newUser, admin); @@ -407,7 +428,7 @@ test('\n\n ** FabricCAClient: Test enroll With a CSR **\n\n', async (t) => { const req = { enrollmentID: newUser.enrollmentID, enrollmentSecret: newUser.enrollmentSecret, - csr: myCsr, + csr: myCsr }; const enrollment = await caService.enroll(req); diff --git a/test/integration/fileKeyValueStore-fabricca-tests.js b/test/integration/fileKeyValueStore-fabricca-tests.js index 363cd2e8bf..a71b9aeffd 100644 --- a/test/integration/fileKeyValueStore-fabricca-tests.js +++ b/test/integration/fileKeyValueStore-fabricca-tests.js @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils, User} = require('fabric-common'); const logger = utils.getLogger('fileKeyValStore-fabricca'); const tape = require('tape'); @@ -17,7 +17,6 @@ const fs = require('fs-extra'); 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 userOrg = 'org1'; @@ -37,7 +36,7 @@ test('Use FabricCAServices with a File KeyValueStore', (t) => { // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); // var keyValueStore = Client.getConfigSetting('key-value-store'); const keyValStorePath = path.join(testUtil.getTempDir(), 'customKeyValStorePath'); diff --git a/test/integration/get-config.js b/test/integration/get-config.js index 52e0875a5f..f5a1faeab6 100644 --- a/test/integration/get-config.js +++ b/test/integration/get-config.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('get-config'); const tape = require('tape'); diff --git a/test/integration/grpc.js b/test/integration/grpc.js index c7a1ab47b1..d47070e27b 100644 --- a/test/integration/grpc.js +++ b/test/integration/grpc.js @@ -6,7 +6,7 @@ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const tape = require('tape'); const _test = require('tape-promise').default; diff --git a/test/integration/install.js b/test/integration/install.js index 2be5cf30dd..e338f837d5 100644 --- a/test/integration/install.js +++ b/test/integration/install.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('install'); const tape = require('tape'); diff --git a/test/integration/instantiate.js b/test/integration/instantiate.js index 6e9ebd3add..07b326b176 100644 --- a/test/integration/instantiate.js +++ b/test/integration/instantiate.js @@ -15,7 +15,7 @@ const fs = require('fs'); const util = require('util'); const Client = require('fabric-client'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const e2eUtils = require('./e2e/e2eUtils.js'); const testUtil = require('../unit/util.js'); const logger = utils.getLogger('instantiate-chaincode'); diff --git a/test/integration/invoke.js b/test/integration/invoke.js index 77afe70023..b847edb333 100644 --- a/test/integration/invoke.js +++ b/test/integration/invoke.js @@ -16,7 +16,7 @@ const _test = require('tape-promise').default; const test = _test(tape); const Client = require('fabric-client'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const testUtil = require('../unit/util.js'); const e2e = testUtil.END2END; const e2eUtils = require('./e2e/e2eUtils.js'); diff --git a/test/integration/memory.js b/test/integration/memory.js index 1f50c887b1..409f21ae0b 100644 --- a/test/integration/memory.js +++ b/test/integration/memory.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('Memory Usage'); const tape = require('tape'); diff --git a/test/integration/network-config.js b/test/integration/network-config.js index 4d956978e2..f1d626228c 100644 --- a/test/integration/network-config.js +++ b/test/integration/network-config.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('connection profile'); const tape = require('tape'); diff --git a/test/integration/network-e2e/idmanager.js b/test/integration/network-e2e/idmanager.js index bed714322f..e3c7152e32 100644 --- a/test/integration/network-e2e/idmanager.js +++ b/test/integration/network-e2e/idmanager.js @@ -6,7 +6,7 @@ 'use strict'; const Client = require('fabric-client'); -const User = require('fabric-client/lib/User'); +const {User} = require('fabric-common'); class IDManager { diff --git a/test/integration/network-e2e/install-chaincode.js b/test/integration/network-e2e/install-chaincode.js index 931f674d70..256823997e 100644 --- a/test/integration/network-e2e/install-chaincode.js +++ b/test/integration/network-e2e/install-chaincode.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E install-chaincode'); const tape = require('tape'); diff --git a/test/integration/network-e2e/instantiate-chaincode.js b/test/integration/network-e2e/instantiate-chaincode.js index ba26464dde..5405c89099 100644 --- a/test/integration/network-e2e/instantiate-chaincode.js +++ b/test/integration/network-e2e/instantiate-chaincode.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E instantiate-chaincode'); logger.level = 'debug'; diff --git a/test/integration/network-e2e/updateAnchorPeers.js b/test/integration/network-e2e/updateAnchorPeers.js index 44d4446916..13786a098d 100644 --- a/test/integration/network-e2e/updateAnchorPeers.js +++ b/test/integration/network-e2e/updateAnchorPeers.js @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -const utils = require('fabric-client/lib/utils.js'); +const {Utils: utils} = require('fabric-common'); const logger = utils.getLogger('E2E setAnchorPeers'); const tape = require('tape'); @@ -59,10 +59,10 @@ async function updateChannel(t, file, channelName, client_org1, client_org2) { const request = { config: config, - signatures : signatures, - name : channelName, - orderer : 'orderer.example.com', - txId : tx_id + signatures: signatures, + name: channelName, + orderer: 'orderer.example.com', + txId: tx_id }; try { diff --git a/test/integration/nodechaincode/install-chaincode.js b/test/integration/nodechaincode/install-chaincode.js index 7822b86bc9..60e5d2d6d7 100644 --- a/test/integration/nodechaincode/install-chaincode.js +++ b/test/integration/nodechaincode/install-chaincode.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E install-chaincode'); const tape = require('tape'); diff --git a/test/integration/nodechaincode/instantiate-chaincode.js b/test/integration/nodechaincode/instantiate-chaincode.js index 8cc4b0fcb3..87cb3d9060 100644 --- a/test/integration/nodechaincode/instantiate-chaincode.js +++ b/test/integration/nodechaincode/instantiate-chaincode.js @@ -8,7 +8,7 @@ // in a happy-path scenario 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E instantiate-chaincode'); logger.level = 'debug'; diff --git a/test/integration/only-admin.js b/test/integration/only-admin.js index 43963534e0..fd341696c5 100644 --- a/test/integration/only-admin.js +++ b/test/integration/only-admin.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('ONLY-ADMIN'); const tape = require('tape'); diff --git a/test/integration/orderer-channel-tests.js b/test/integration/orderer-channel-tests.js index 1aa85d6bec..d72448bf35 100644 --- a/test/integration/orderer-channel-tests.js +++ b/test/integration/orderer-channel-tests.js @@ -5,7 +5,7 @@ */ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const tape = require('tape'); @@ -35,7 +35,7 @@ const org = 'org1'; // test('\n\n** TEST ** orderer via member missing orderer', async (t) => { testUtil.resetDefaults(); - utils.setConfigSetting('key-value-store', 'fabric-ca-client/lib/impl/FileKeyValueStore.js');// force for 'gulp test' + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js');// force for 'gulp test' Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); ORGS = Client.getConfigSetting('test-network'); const orgName = ORGS[org].name; diff --git a/test/integration/query.js b/test/integration/query.js index 37b492287a..ff4f805a4d 100644 --- a/test/integration/query.js +++ b/test/integration/query.js @@ -13,7 +13,7 @@ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('query'); const tape = require('tape'); @@ -56,7 +56,7 @@ test(' ---->>>>> Query channel working <<<<<-----', (t) => { let bcInfo = null; let tx_block = null; - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js'); const cryptoSuite = Client.newCryptoSuite(); cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); diff --git a/test/integration/token.js b/test/integration/token.js index f9813a3a4d..6e63e43d7f 100644 --- a/test/integration/token.js +++ b/test/integration/token.js @@ -11,7 +11,7 @@ const fs = require('fs'); const path = require('path'); const util = require('util'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const tokenUtils = require('fabric-client/lib/token-utils.js'); const logger = utils.getLogger('E2E token'); diff --git a/test/integration/upgrade.js b/test/integration/upgrade.js index 41fc6ca6b4..eff23ff6c3 100644 --- a/test/integration/upgrade.js +++ b/test/integration/upgrade.js @@ -14,7 +14,7 @@ const path = require('path'); const fs = require('fs'); const Client = require('fabric-client'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const testUtil = require('../unit/util.js'); const e2eUtils = require('./e2e/e2eUtils.js'); const logger = utils.getLogger('upgrade-chaincode'); diff --git a/test/typescript/test.ts b/test/typescript/test.ts index 367a3eec0c..4ec2779c5f 100644 --- a/test/typescript/test.ts +++ b/test/typescript/test.ts @@ -11,8 +11,8 @@ import * as util from 'util'; import FabricCAServices = require('fabric-ca-client'); import Client = require('fabric-client'); - -import utils = require('fabric-client/lib/utils'); +import FabricCommon = require('fabric-common'); +const {Utils: utils} = FabricCommon; const logger = utils.getLogger('connection profile'); import { IEnrollmentRequest } from 'fabric-ca-client'; diff --git a/test/unit/crypto-key-store.js b/test/unit/crypto-key-store.js index 007ec57fb7..5e6ac37063 100644 --- a/test/unit/crypto-key-store.js +++ b/test/unit/crypto-key-store.js @@ -17,7 +17,7 @@ const test = _test(tape); const util = require('util'); const testutil = require('./util.js'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const fs = require('fs-extra'); const path = require('path'); const os = require('os'); @@ -26,9 +26,9 @@ 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 ecdsaKey = require('fabric-common/lib/impl/ecdsa/key.js'); +const CKS = require('fabric-common/lib/impl/CryptoKeyStore.js'); +const CouchDBKeyValueStore = require('fabric-common/lib/impl/CouchDBKeyValueStore.js'); const TEST_KEY_PRIVATE_PEM = '-----BEGIN PRIVATE KEY-----' + 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgZYMvf3w5VkzzsTQY' + @@ -102,7 +102,7 @@ test('\n\n** CryptoKeyStore tests **\n\n', (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'); + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/CouchDBKeyValueStore.js'); const couchdb = CouchdbMock.createServer(); couchdb.listen(5985); @@ -217,7 +217,7 @@ function testKeyStore(store, 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' + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js');// force for 'gulp test' const keyValStorePath = 'tmp/keyValStore1'; const config = {path: keyValStorePath}; let cs = utils.newCryptoKeyStore(config); diff --git a/test/unit/cryptosuite-ecdsa-aes.js b/test/unit/cryptosuite-ecdsa-aes.js index e6ba633bc1..5c0652b743 100644 --- a/test/unit/cryptosuite-ecdsa-aes.js +++ b/test/unit/cryptosuite-ecdsa-aes.js @@ -11,7 +11,7 @@ const _test = require('tape-promise').default; const test = _test(tape); const testutil = require('./util.js'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils, User} = require('fabric-common'); const path = require('path'); const fs = require('fs-extra'); const util = require('util'); @@ -19,9 +19,8 @@ const util = require('util'); const jsrsa = require('jsrsasign'); const ECDSA = jsrsa.ECDSA; -const CryptoSuite_ECDSA_AES = require('fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js'); -const ecdsaKey = require('fabric-client/lib/impl/ecdsa/key.js'); -const User = require('fabric-client/lib/User.js'); +const CryptoSuite_ECDSA_AES = require('fabric-common/lib/impl/CryptoSuite_ECDSA_AES.js'); +const ecdsaKey = require('fabric-common/lib/impl/ecdsa/key.js'); const elliptic = require('elliptic'); const Signature = require('elliptic/lib/elliptic/ec/signature.js'); @@ -168,7 +167,7 @@ test('\n\n ** CryptoSuite_ECDSA_AES - function tests **\n\n', (t) => { // reset to default key size utils.setConfigSetting('crypto-keysize', 256); - utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js');// force for gulp test + utils.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js');// force for gulp test cryptoUtils = utils.newCryptoSuite(); cryptoUtils.setCryptoKeyStore(utils.newCryptoKeyStore()); diff --git a/test/unit/logger.js b/test/unit/logger.js index 01429c136e..b38d8ec1a5 100644 --- a/test/unit/logger.js +++ b/test/unit/logger.js @@ -12,7 +12,7 @@ const test = _test(tape); const hfc = require('fabric-client'); const testutil = require('./util.js'); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const bunyan = require('bunyan'); const log4js = require('log4js'); diff --git a/test/unit/network-config.js b/test/unit/network-config.js index a0aa6c47fc..767eb0daed 100644 --- a/test/unit/network-config.js +++ b/test/unit/network-config.js @@ -6,7 +6,7 @@ 'use strict'; -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils, User} = require('fabric-common'); const logger = utils.getLogger('unit.client'); const tape = require('tape'); @@ -18,7 +18,6 @@ const yaml = require('js-yaml'); const util = require('util'); const Client = require('fabric-client'); -const User = require('fabric-client/lib/User.js'); const Peer = require('fabric-client/lib/Peer.js'); const Orderer = require('fabric-client/lib/Orderer.js'); const Organization = require('fabric-client/lib/Organization.js'); diff --git a/test/unit/read-configtx.js b/test/unit/read-configtx.js index 40cd60df96..afb8f403b2 100644 --- a/test/unit/read-configtx.js +++ b/test/unit/read-configtx.js @@ -10,7 +10,7 @@ if (global && global.hfc) { } require('nconf').reset(); -const utils = require('fabric-client/lib/utils.js'); +const {Utils:utils} = require('fabric-common'); const logger = utils.getLogger('E2E create-channel'); const fs = require('fs'); const path = require('path'); diff --git a/test/unit/util.js b/test/unit/util.js index c28017c5f0..f99fe94c04 100644 --- a/test/unit/util.js +++ b/test/unit/util.js @@ -11,10 +11,9 @@ const util = require('util'); const Client = require('fabric-client'); const copService = require('fabric-ca-client/lib/FabricCAServices.js'); -const User = require('fabric-client/lib/User.js'); +const {Utils:utils, User} = require('fabric-common'); const Constants = require('./constants.js'); - -const logger = require('fabric-client/lib/utils.js').getLogger('TestUtil'); +const logger = utils.getLogger('TestUtil'); module.exports.CHAINCODE_PATH = 'github.com/example_cc'; module.exports.CHAINCODE_UPGRADE_PATH = 'github.com/example_cc1';