From f306afe75b9cf829fb30145973a3b5d773464833 Mon Sep 17 00:00:00 2001 From: Jim Zhang Date: Thu, 1 Jun 2017 19:50:44 -0400 Subject: [PATCH] [FAB-4131] Enhance FabricCAClientImpl with persistence The ability to construct KeyValueStore objects is missing from this package. as a result the application is not able to solely use fabric-ca-client to handle user object persistence (which requires a KeyValueStore instance) Also cleaned up logging in SDK and test code to use debug statements instead of info, and save debug logs in a file Change-Id: I2d908303bd8ec74058b689526894c79eab4144ae Signed-off-by: Jim Zhang --- .gitignore | 4 + build/tasks/ca.js | 8 +- build/tasks/doc.js | 31 +-- build/tasks/eslint.js | 1 + build/tasks/test.js | 25 ++- fabric-ca-client/lib/FabricCAClientImpl.js | 74 ++----- fabric-client/lib/BaseClient.js | 196 ++++++++++++++++ fabric-client/lib/Client.js | 209 ++---------------- fabric-client/lib/Peer.js | 1 + fabric-client/lib/TransactionID.js | 2 +- fabric-client/lib/User.js | 11 + .../lib/impl/CouchDBKeyValueStore.js | 22 +- fabric-client/lib/impl/CryptoKeyStore.js | 2 +- .../lib/impl/CryptoSuite_ECDSA_AES.js | 5 +- fabric-client/lib/impl/FileKeyValueStore.js | 14 +- fabric-client/lib/impl/bccsp_pkcs11.js | 1 + fabric-client/lib/impl/ecdsa/key.js | 18 +- fabric-client/lib/impl/ecdsa/pkcs11_key.js | 7 + fabric-client/lib/msp/identity.js | 8 + fabric-client/lib/msp/msp.js | 2 +- fabric-client/lib/utils.js | 6 +- package.json | 2 + test/fixtures/local.json | 4 - test/integration/client.js | 75 +++---- test/integration/cloudant-fabricca-tests.js | 37 ++-- test/integration/configtx-e2e.js | 35 --- test/integration/couchdb-fabricca-tests.js | 29 ++- test/integration/couchdb-util.js | 6 +- test/integration/create-configtx-channel.js | 9 +- test/integration/e2e/create-channel.js | 21 +- test/integration/e2e/e2eUtils.js | 59 +++-- test/integration/e2e/install-chaincode.js | 4 +- test/integration/e2e/instantiate-chaincode.js | 2 +- test/integration/e2e/invoke-transaction.js | 1 - test/integration/e2e/join-channel.js | 10 +- test/integration/e2e/update-channel.js | 7 +- test/integration/e2e/upgrade.js | 4 +- test/integration/events.js | 106 ++++----- test/integration/eventutil.js | 5 +- test/integration/fabric-ca-services-tests.js | 74 +++---- .../fileKeyValueStore-fabricca-tests.js | 31 +-- test/integration/get-config.js | 89 ++++---- test/integration/grpc.js | 17 +- test/integration/install.js | 41 +--- test/integration/marbles.js | 7 + test/integration/orderer-channel-tests.js | 31 +-- test/integration/query.js | 128 ++++++----- test/integration/upgrade.js | 12 +- test/unit/block.js | 17 -- test/unit/channel.js | 10 +- test/unit/client.js | 58 ++--- test/unit/crypto-key-store.js | 4 +- test/unit/cryptosuite-ecdsa-aes.js | 6 +- test/unit/ecdsa-key.js | 4 +- test/unit/event-hub.js | 4 +- test/unit/fabric-ca-client.js | 30 ++- test/unit/file-key-value-store.js | 3 +- test/unit/identity.js | 4 +- test/unit/logger.js | 13 +- test/unit/msp.js | 2 + test/unit/orderer.js | 7 +- test/unit/peer.js | 8 +- test/unit/pkcs11.js | 2 + test/unit/read-configtx.js | 9 +- test/unit/remote.js | 4 +- test/unit/transactionid.js | 3 + test/unit/user.js | 6 +- test/unit/util.js | 23 +- 68 files changed, 812 insertions(+), 898 deletions(-) create mode 100644 fabric-client/lib/BaseClient.js delete mode 100644 test/integration/configtx-e2e.js diff --git a/.gitignore b/.gitignore index 95efa1fa76..0ed97c8273 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,12 @@ fabric-ca-client/node_modules/* examples/balance-transfer/node_modules/* 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/* npm-shrinkwrap.json diff --git a/build/tasks/ca.js b/build/tasks/ca.js index c78f1b3267..ce17518376 100644 --- a/build/tasks/ca.js +++ b/build/tasks/ca.js @@ -7,13 +7,19 @@ const DEPS = [ 'fabric-client/lib/api.js', 'fabric-client/lib/hash.js', 'fabric-client/lib/utils.js', + 'fabric-client/lib/BaseClient.js', 'fabric-client/lib/Config.js', 'fabric-client/lib/Remote.js', + 'fabric-client/lib/User.js', 'fabric-client/lib/impl/CouchDBKeyValueStore.js', 'fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js', 'fabric-client/lib/impl/ecdsa/*', 'fabric-client/lib/impl/CryptoKeyStore.js', - 'fabric-client/lib/impl/FileKeyValueStore.js' + 'fabric-client/lib/impl/FileKeyValueStore.js', + 'fabric-client/lib/msp/identity.js', + 'fabric-client/lib/msp/msp.js', + 'fabric-client/lib/protos/msp/identities.proto', + 'fabric-client/lib/protos/msp/msp_config.proto' ]; gulp.task('ca', function() { diff --git a/build/tasks/doc.js b/build/tasks/doc.js index e6c79765b2..ebdfc7f5cb 100644 --- a/build/tasks/doc.js +++ b/build/tasks/doc.js @@ -16,31 +16,20 @@ var gulp = require('gulp'); var jsdoc = require('gulp-jsdoc3'); +var del = require('del'); -gulp.task('doc', function () { +gulp.task('clean', function(){ + return del('./docs/gen/**', {force:true}); +}); + +gulp.task('doc', ['clean'], function () { gulp.src([ 'docs/index.md', 'fabric-client/index.js', - 'fabric-client/lib/api.js', - 'fabric-client/lib/impl/FileKeyValueStore.js', - 'fabric-client/lib/impl/CouchDBKeyValueStore.js', - 'fabric-client/lib/impl/CryptoKeyStore.js', - 'fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js', - 'fabric-client/lib/impl/ecdsa/key.js', - 'fabric-client/lib/impl/bccsp_pkcs11.js', - 'fabric-client/lib/impl/ecdsa/*', - 'fabric-client/lib/impl/aes/*', - 'fabric-client/lib/BlockDecoder.js', - 'fabric-client/lib/msp/msp.js', - 'fabric-client/lib/Channel.js', - 'fabric-client/lib/Orderer.js', - 'fabric-client/lib/Peer.js', - 'fabric-client/lib/Policy.js', - 'fabric-client/lib/User.js', - 'fabric-client/lib/Client.js', - 'fabric-client/lib/EventHub.js', - 'fabric-client/lib/Remote.js', - 'fabric-client/lib/X509Certificate.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/FabricCAClientImpl.js' ], { read: false }) diff --git a/build/tasks/eslint.js b/build/tasks/eslint.js index c5f927c4a0..33922e5f03 100644 --- a/build/tasks/eslint.js +++ b/build/tasks/eslint.js @@ -7,6 +7,7 @@ gulp.task('lint', function () { 'fabric-client/**/*.js', 'fabric-ca-client/lib/*.js', 'examples/**/*.js', + '!examples/balance-transfer/node_modules/**', '!node_modules/**', '!fabric-client/node_modules/**', '!fabric-ca-client/node_modules/**', diff --git a/build/tasks/test.js b/build/tasks/test.js index 50f1539aa0..fd8cf9a462 100644 --- a/build/tasks/test.js +++ b/build/tasks/test.js @@ -4,12 +4,22 @@ var gulp = require('gulp'); var tape = require('gulp-tape'); var tapColorize = require('tap-colorize'); var istanbul = require('gulp-istanbul'); +var addsrc = require('gulp-add-src'); var fs = require('fs-extra'); +var path = require('path'); var os = require('os'); +var util = require('util'); var shell = require('gulp-shell'); var testConstants = require('../../test/unit/constants.js'); +// by default for running the tests print debug to a file +var debugPath = path.join(testConstants.tempdir, 'test-log/debug.log'); +process.env.HFC_LOGGING = util.format('{"debug":"%s"}', debugPath); +console.log('\n####################################################'); +console.log(util.format('# debug log: %s', debugPath)); +console.log('####################################################\n'); + gulp.task('pre-test', function() { return gulp.src([ 'node_modules/fabric-client/lib/**/*.js', @@ -21,7 +31,8 @@ gulp.task('pre-test', function() { gulp.task('clean-up', function() { // some tests create temporary files or directories // they are all created in the same temp folder - return fs.removeSync(testConstants.tempdir); + fs.removeSync(testConstants.tempdir); + return fs.ensureFileSync(debugPath); }); gulp.task('docker-clean', shell.task([ @@ -47,16 +58,17 @@ gulp.task('test', ['clean-up', 'lint', 'docker-clean', 'pre-test', 'ca'], functi 'test/unit/**/*.js', '!test/unit/constants.js', '!test/unit/util.js', + '!test/unit/logger.js', + 'test/integration/e2e.js', + 'test/integration/query.js', 'test/integration/fabric-ca-services-tests.js', 'test/integration/client.js', 'test/integration/orderer-channel-tests.js', 'test/integration/cloudant-fabricca-tests.js', 'test/integration/couchdb-fabricca-tests.js', 'test/integration/fileKeyValueStore-fabricca-tests.js', - 'test/integration/e2e.js', 'test/integration/install.js', 'test/integration/events.js', - 'test/integration/query.js', 'test/integration/upgrade.js', 'test/integration/get-config.js', 'test/integration/create-configtx-channel.js', @@ -66,6 +78,9 @@ gulp.task('test', ['clean-up', 'lint', 'docker-clean', 'pre-test', 'ca'], functi 'test/integration/e2e/query.js', 'test/integration/grpc.js' ])) + .pipe(addsrc.append( + 'test/unit/logger.js' // put this to the last so the debugging levels are not mixed up + )) .pipe(tape({ reporter: tapColorize() })) @@ -85,7 +100,11 @@ gulp.task('test-headless', ['clean-up', 'lint', 'pre-test', 'ca'], function() { 'test/unit/**/*.js', '!test/unit/constants.js', '!test/unit/util.js', + '!test/unit/logger.js' ])) + .pipe(addsrc.append( + 'test/unit/logger.js' // put this to the last so the debugging levels are not mixed up + )) .pipe(tape({ reporter: tapColorize() })) diff --git a/fabric-ca-client/lib/FabricCAClientImpl.js b/fabric-ca-client/lib/FabricCAClientImpl.js index 72f958a16f..a3c692c617 100644 --- a/fabric-ca-client/lib/FabricCAClientImpl.js +++ b/fabric-ca-client/lib/FabricCAClientImpl.js @@ -18,6 +18,7 @@ var api = require('./api.js'); var utils = require('./utils.js'); +var BaseClient = require('./BaseClient.js'); var util = require('util'); var path = require('path'); var http = require('http'); @@ -36,8 +37,9 @@ var logger = utils.getLogger('FabricCAClientImpl.js'); /** * This is an implementation of the member service client which communicates with the Fabric CA server. * @class + * @extends BaseClient */ -var FabricCAServices = class { +var FabricCAServices = class extends BaseClient { /** * constructor @@ -57,14 +59,15 @@ var FabricCAServices = class { * 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, tlsOptions, caName, cryptoSuite) { + super(); var endpoint = FabricCAServices._parseURL(url); if (!!cryptoSuite) { - this.cryptoPrimitives = cryptoSuite; + this.setCryptoSuite(cryptoSuite); } else { - this.cryptoPrimitives = utils.newCryptoSuite(); - this.cryptoPrimitives.setCryptoKeyStore(utils.newCryptoKeyStore()); + this.setCryptoSuite(utils.newCryptoSuite()); + this.getCryptoSuite().setCryptoKeyStore(utils.newCryptoKeyStore()); } this._fabricCAClient = new FabricCAClient({ @@ -73,63 +76,12 @@ var FabricCAServices = class { hostname: endpoint.hostname, port: endpoint.port, tlsOptions: tlsOptions - }, this.cryptoPrimitives); + }, this.getCryptoSuite()); - logger.info('Successfully constructed Fabric CA service client: endpoint - %j', endpoint); + logger.debug('Successfully constructed Fabric CA service client: endpoint - %j', endpoint); } - /** - * Returns a new instance of the CryptoSuite API implementation - * - * If not specified, an instance of {@link CryptoSuite} will be constructed based on the current configuration settings: - *
- crypto-hsm: use an implementation for Hardware Security Module (if set to true) or software-based key management (if set to false) - *
- crypto-keysize: security level, or key size, to use with the digital signature public key algorithm. Currently ECDSA - * is supported and the valid key sizes are 256 and 384 - *
- crypto-hash-algo: hashing algorithm - *
- key-value-store: some CryptoSuite implementation requires a key store to persist private keys. A {@link CryptoKeyStore} - * 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. - * - * @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' - *
- 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' - * @param {function} KVSImplClass Optional. The built-in key store saves private keys. The key store may be backed by different - * {@link KeyValueStore} implementations. If specified, the value of the argument must point to a module implementing the - * KeyValueStore interface. - * @param {object} opts Implementation-specific option object used in the constructor - * @returns a new instance of the CryptoSuite API implementation - */ - static newCryptoSuite(setting, KVSImplClass, opts) { - return utils.newCryptoSuite(setting, KVSImplClass, opts); - } - - getCrypto() { - return this.cryptoPrimitives; - } - - /** - * Returns a new instance of the CryptoKeyStore. - * - * When the application needs to use a key store other than the default, - * it should create a new CryptoKeyStore and set it on the CryptoSuite. - * - *

cryptosuite.setCryptoKeyStore(CAClient.newCryptoKeyStore(KVSImplClass, opts)) - * - * @param {function} KVSImplClass Optional. The built-in key store saves private keys. The key store may be backed by different - * {@link KeyValueStore} implementations. If specified, the value of the argument must point to a module implementing the - * KeyValueStore interface. - * @param {object} opts Implementation-specific option object used in the constructor - * @returns a new instance of the CryptoKeystore - */ - static newCryptoKeyStore (KVSImplClass, opts) { - return utils.newCryptoKeyStore(KVSImplClass, opts); - } - /** * Register the member and return an enrollment secret. * @param {Object} req Registration request with the following fields: @@ -193,12 +145,12 @@ var FabricCAServices = class { //generate enrollment certificate pair for signing var opts; - if (self.cryptoPrimitives._cryptoKeyStore) { + if (self.getCryptoSuite()._cryptoKeyStore) { opts = {ephemeral: false}; } else { opts = {ephemeral: true}; } - self.cryptoPrimitives.generateKey(opts) + self.getCryptoSuite().generateKey(opts) .then( function (privateKey) { //generate CSR using enrollmentID for the subject @@ -270,7 +222,7 @@ var FabricCAServices = class { return new Promise(function (resolve, reject) { //generate enrollment certificate pair for signing - self.cryptoPrimitives.generateKey() + self.getCryptoSuite().generateKey() .then( function (privateKey) { //generate CSR using the subject of the current user's certificate @@ -471,7 +423,7 @@ var FabricCAClient = class { this._cryptoPrimitives = cryptoPrimitives; - logger.info('Successfully constructed Fabric CA client from options - %j', connect_opts); + logger.debug('Successfully constructed Fabric CA client from options - %j', connect_opts); } /** diff --git a/fabric-client/lib/BaseClient.js b/fabric-client/lib/BaseClient.js new file mode 100644 index 0000000000..55d8e67275 --- /dev/null +++ b/fabric-client/lib/BaseClient.js @@ -0,0 +1,196 @@ +var sdkUtils = require('./utils.js'); + +/** + * Base class for a client that can use a {@link CryptoSuite} to sign and hash. + * It also contains utility methods for constructing new instances of {@link CryptoKeyStore}, + * [CryptoSuite]{@link module:api.CryptoSuite} and [KeyValueStore]{@link module:api.KeyValueStore} + */ +var BaseClient = class { + constructor() { + this._cryptoSuite = null; + } + + /** + * Returns a new instance of the CryptoSuite API implementation. + * + * @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' + *
- 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' + * @returns a new instance of the CryptoSuite API implementation + */ + static newCryptoSuite(setting) { + return sdkUtils.newCryptoSuite(setting); + } + + /** + * Sets the client instance to use the CryptoSuite object for signing and hashing + * + * Creating and setting a CryptoSuite is optional because the client will construct + * an instance based on default configuration settings: + *
- crypto-hsm: use an implementation for Hardware Security Module (if set to true) or software-based key management (if set to false) + *
- crypto-keysize: security level, or key size, to use with the digital signature public key algorithm. Currently ECDSA + * is supported and the valid key sizes are 256 and 384 + *
- crypto-hash-algo: hashing algorithm + *
- key-value-store: some CryptoSuite implementation requires a key store to persist private keys. A {@link CryptoKeyStore} + * 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. + * + * @param {CryptoSuite} cryptoSuite the CryptoSuite object + */ + setCryptoSuite(cryptoSuite) { + this._cryptoSuite = cryptoSuite; + } + + /** + * Returns the {@link CryptoSuite} object used by this client instance + * @returns {CryptoSuite} + */ + getCryptoSuite() { + return this._cryptoSuite; + } + + /** + * Returns a new instance of the CryptoKeyStore. + * + * When the application needs to use a key store other than the default, + * it should create a new CryptoKeyStore and set it on the CryptoSuite. + * + *

cryptosuite.setCryptoKeyStore(Client.newCryptoKeyStore(KVSImplClass, opts)) + * + * @param {function} KVSImplClass Optional. The built-in key store saves private keys. The key store may be backed by different + * {@link KeyValueStore} implementations. If specified, the value of the argument must point to a module implementing the + * KeyValueStore interface. + * @param {object} opts Implementation-specific option object used in the constructor + * @returns a new instance of the CryptoKeystore + */ + static newCryptoKeyStore(KVSImplClass, opts) { + return sdkUtils.newCryptoKeyStore(KVSImplClass, opts); + } + + /** + * Obtains an instance of the [KeyValueStore]{@link module:api.KeyValueStore} class. By default + * it returns the built-in implementation, which is based on files ([FileKeyValueStore]{@link module:api.FileKeyValueStore}). + * This can be overriden with an environment variable KEY_VALUE_STORE, the value of which is the + * full path of a CommonJS module for the alternative implementation. + * + * @param {Object} options is whatever the implementation requires for initializing the instance. For the built-in + * file-based implementation, this requires a single property "path" to the top-level folder for the store + * @returns [KeyValueStore]{@link module:api.KeyValueStore} an instance of the KeyValueStore implementation + */ + static newDefaultKeyValueStore(options) { + return sdkUtils.newKeyValueStore(options); + } + + /** + * Configures a logger for the entire HFC SDK to use and override the default logger. Unless this method is called, + * HFC uses a default logger (based on winston). When using the built-in "winston" based logger, use the environment + * variable HFC_LOGGING to pass in configurations in the following format: + * + * { + * 'error': 'error.log', // 'error' logs are printed to file 'error.log' relative of the current working dir for node.js + * 'debug': '/tmp/myapp/debug.log', // 'debug' and anything more critical ('info', 'warn', 'error') can also be an absolute path + * 'info': 'console' // 'console' is a keyword for logging to console + * } + * + * @param {Object} logger a logger instance that defines the following methods: debug(), info(), warn(), error() with + * string interpolation methods like [util.format]{@link https://nodejs.org/api/util.html#util_util_format_format}. + */ + static setLogger(logger) { + var err = ''; + + if (typeof logger.debug !== 'function') { + err += 'debug() '; + } + + if (typeof logger.info !== 'function') { + err += 'info() '; + } + + if (typeof logger.warn !== 'function') { + err += 'warn() '; + } + + if (typeof logger.error !== 'function' ) { + err += 'error()'; + } + + if (err !== '') { + throw new Error('The "logger" parameter must be an object that implements the following methods, which are missing: ' + err); + } + + if (global.hfc) { + global.hfc.logger = logger; + } else { + global.hfc = { + logger: logger + }; + } + } + + /** + * Adds a file to the top of the list of configuration setting files that are + * part of the hierarchical configuration. + * These files will override the default settings and be overriden by environment, + * command line arguments, and settings programmatically set into configuration settings. + * + * hierarchy search order: + * 1. memory - all settings added with sdkUtils.setConfigSetting(name,value) + * 2. Command-line arguments + * 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) + * 4. Custom Files - all files added with the addConfigFile(path) + * will be ordered by when added, were last one added will override previously added files + * 5. The file located at 'config/default.json' with default settings + * + * @param {String} path - The path to the file to be added to the top of list of configuration files + */ + static addConfigFile(path) { + + sdkUtils.addConfigFile(path); + } + + /** + * Adds a setting to override all settings that are + * part of the hierarchical configuration. + * + * hierarchy search order: + * 1. memory - settings added with this call + * 2. Command-line arguments + * 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) + * 4. Custom Files - all files added with the addConfigFile(path) + * will be ordered by when added, were last one added will override previously added files + * 5. The file located at 'config/default.json' with default settings + * + * @param {String} name - The name of a setting + * @param {Object} value - The value of a setting + */ + static setConfigSetting(name, value) { + + sdkUtils.setConfigSetting(name, value); + } + + /** + * Retrieves a setting from the hierarchical configuration and if not found + * will return the provided default value. + * + * hierarchy search order: + * 1. memory - settings added with sdkUtils.setConfigSetting(name,value) + * 2. Command-line arguments + * 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) + * 4. Custom Files - all files added with the addConfigFile(path) + * will be ordered by when added, were last one added will override previously added files + * 5. The file located at 'config/default.json' with default settings + * + * @param {String} name - The name of a setting + * @param {Object} default_value - The value of a setting if not found in the hierarchical configuration + */ + static getConfigSetting(name, default_value) { + + return sdkUtils.getConfigSetting(name, default_value); + } +}; + +module.exports = BaseClient; diff --git a/fabric-client/lib/Client.js b/fabric-client/lib/Client.js index 5d35823470..50f99b6647 100644 --- a/fabric-client/lib/Client.js +++ b/fabric-client/lib/Client.js @@ -20,6 +20,7 @@ var sdkUtils = require('./utils.js'); process.env.GRPC_SSL_CIPHER_SUITES = sdkUtils.getConfigSetting('grpc-ssl-cipher-suites'); var api = require('./api.js'); +var BaseClient = require('./BaseClient.js'); var User = require('./User.js'); var Channel = require('./Channel.js'); var ChannelConfig = require('./ChannelConfig.js'); @@ -56,15 +57,17 @@ var _queryProto = grpc.load(__dirname + '/protos/peer/query.proto').protos; * private ledgers. * * @class + * @extends BaseClient * */ -var Client = class { +var Client = class extends BaseClient { constructor() { + super(); + logger.debug('const - new Client'); this._channels = {}; this._stateStore = null; - this._cryptoSuite = null; this._userContext = null; // keep a collection of MSP's this._msps = new Map(); @@ -73,60 +76,6 @@ var Client = class { this._devMode = false; } - /** - * Returns a new instance of the CryptoSuite API implementation. - * - * Creating a new CryptoSuite is optional and should be used if options other than defaults are needed. - * - * If not specified, an instance of {@link CryptoSuite} will be constructed based on the current configuration settings: - *
- crypto-hsm: use an implementation for Hardware Security Module (if set to true) or software-based key management (if set to false) - *
- crypto-keysize: security level, or key size, to use with the digital signature public key algorithm. Currently ECDSA - * is supported and the valid key sizes are 256 and 384 - *
- crypto-hash-algo: hashing algorithm - *
- key-value-store: some CryptoSuite implementation requires a key store to persist private keys. A {@link CryptoKeyStore} - * 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. - * - * @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' - *
- 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' - * @returns a new instance of the CryptoSuite API implementation - */ - newCryptoSuite(setting) { - this._cryptoSuite = sdkUtils.newCryptoSuite(setting); - return this._cryptoSuite; - } - - setCryptoSuite(cryptoSuite) { - this._cryptoSuite = cryptoSuite; - } - - getCryptoSuite() { - return this._cryptoSuite; - } - - /** - * Returns a new instance of the CryptoKeyStore. - * - * When the application needs to use a key store other than the default, - * it should create a new CryptoKeyStore and set it on the CryptoSuite. - * - *

cryptosuite.setCryptoKeyStore(client.newCryptoKeyStore(KVSImplClass, opts)) - * - * @param {function} KVSImplClass Optional. The built-in key store saves private keys. The key store may be backed by different - * {@link KeyValueStore} implementations. If specified, the value of the argument must point to a module implementing the - * KeyValueStore interface. - * @param {object} opts Implementation-specific option object used in the constructor - * @returns a new instance of the CryptoKeystore - */ - newCryptoKeyStore (KVSImplClass, opts) { - return sdkUtils.newCryptoKeyStore(KVSImplClass, opts); - } - /** * Determine if dev mode is enabled. */ @@ -997,10 +946,10 @@ var Client = class { if (memberStr) { // The member was found in the key value store, so restore the state. var newUser = new User(name); - if (!self._cryptoSuite) { - logger.info('loadUserFromStateStore, cryptoSuite is not set, will load using defaults'); + if (!self.getCryptoSuite()) { + logger.debug('loadUserFromStateStore, cryptoSuite is not set, will load using defaults'); } - newUser.setCryptoSuite(self._cryptoSuite); + newUser.setCryptoSuite(self.getCryptoSuite()); return newUser.fromString(memberStr); } else { @@ -1009,10 +958,10 @@ var Client = class { }) .then(function(data) { if (data) { - logger.info('Successfully loaded user "%s" from local key value store', name); + logger.debug('Successfully loaded user "%s" from local key value store', name); return resolve(data); } else { - logger.info('Failed to load user "%s" from local key value store', name); + logger.debug('Failed to load user "%s" from local key value store', name); return resolve(null); } }).catch( @@ -1077,18 +1026,17 @@ var Client = class { return Promise.reject(new Error('Client.createUser parameter \'opts cryptoContent\' is required.')); } - if (this._cryptoSuite == null) { + if (this.getCryptoSuite() == null) { logger.debug('cryptoSuite is null, creating default cryptoSuite and cryptoKeyStore'); - this._cryptoSuite = sdkUtils.newCryptoSuite(); - this._cryptoSuite.setCryptoKeyStore(this.newCryptoKeyStore()); + this.setCryptoSuite(sdkUtils.newCryptoSuite()); + this.getCryptoSuite().setCryptoKeyStore(Client.newCryptoKeyStore()); } else { - if (this._cryptoSuite._cryptoKeyStore) logger.debug('cryptoSuite has a cryptoKeyStore'); - else logger.info('cryptoSuite does not have a cryptoKeyStore'); + if (this.getCryptoSuite()._cryptoKeyStore) logger.debug('cryptoSuite has a cryptoKeyStore'); + else logger.debug('cryptoSuite does not have a cryptoKeyStore'); } var self = this; return new Promise((resolve, reject) => { - logger.info('loading user from files'); // need to load private key and pre-enrolled certificate from files based on the MSP // root MSP config directory structure: // @@ -1109,12 +1057,12 @@ var Client = class { if (data) { logger.debug('then privateKeyPEM data'); var opt1; - if (self._cryptoSuite._cryptoKeyStore) { + if (self.getCryptoSuite()._cryptoKeyStore) { opt1 = {ephemeral: false}; } else { opt1 = {ephemeral: true}; } - return self._cryptoSuite.importKey(data.toString(), opt1); + return self.getCryptoSuite().importKey(data.toString(), opt1); } else { throw new Error('failed to load private key data'); } @@ -1131,7 +1079,7 @@ var Client = class { }).then((data) => { logger.debug('then signedCertPEM data'); member = new User(opts.username); - member.setCryptoSuite(self._cryptoSuite); + member.setCryptoSuite(self.getCryptoSuite()); return member.setEnrollment(importedKey, data.toString(), opts.mspid); }).then(() => { logger.debug('then setUserContext'); @@ -1149,127 +1097,6 @@ var Client = class { }); }); } - - /** - * Obtains an instance of the [KeyValueStore]{@link module:api.KeyValueStore} class. By default - * it returns the built-in implementation, which is based on files ([FileKeyValueStore]{@link module:api.FileKeyValueStore}). - * This can be overriden with an environment variable KEY_VALUE_STORE, the value of which is the - * full path of a CommonJS module for the alternative implementation. - * - * @param {Object} options is whatever the implementation requires for initializing the instance. For the built-in - * file-based implementation, this requires a single property "path" to the top-level folder for the store - * @returns [KeyValueStore]{@link module:api.KeyValueStore} an instance of the KeyValueStore implementation - */ - static newDefaultKeyValueStore(options) { - return sdkUtils.newKeyValueStore(options); - } - - /** - * Configures a logger for the entire HFC SDK to use and override the default logger. Unless this method is called, - * HFC uses a default logger (based on winston). When using the built-in "winston" based logger, use the environment - * variable HFC_LOGGING to pass in configurations in the following format: - * - * { - * 'error': 'error.log', // 'error' logs are printed to file 'error.log' relative of the current working dir for node.js - * 'debug': '/tmp/myapp/debug.log', // 'debug' and anything more critical ('info', 'warn', 'error') can also be an absolute path - * 'info': 'console' // 'console' is a keyword for logging to console - * } - * - * @param {Object} logger a logger instance that defines the following methods: debug(), info(), warn(), error() with - * string interpolation methods like [util.format]{@link https://nodejs.org/api/util.html#util_util_format_format}. - */ - static setLogger(logger) { - var err = ''; - - if (typeof logger.debug !== 'function') { - err += 'debug() '; - } - - if (typeof logger.info !== 'function') { - err += 'info() '; - } - - if (typeof logger.warn !== 'function') { - err += 'warn() '; - } - - if (typeof logger.error !== 'function' ) { - err += 'error()'; - } - - if (err !== '') { - throw new Error('The "logger" parameter must be an object that implements the following methods, which are missing: ' + err); - } - - if (global.hfc) { - global.hfc.logger = logger; - } else { - global.hfc = { - logger: logger - }; - } - } - - /** - * Adds a file to the top of the list of configuration setting files that are - * part of the hierarchical configuration. - * These files will override the default settings and be overriden by environment, - * command line arguments, and settings programmatically set into configuration settings. - * - * hierarchy search order: - * 1. memory - all settings added with sdkUtils.setConfigSetting(name,value) - * 2. Command-line arguments - * 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) - * 4. Custom Files - all files added with the addConfigFile(path) - * will be ordered by when added, were last one added will override previously added files - * 5. The file located at 'config/default.json' with default settings - * - * @param {String} path - The path to the file to be added to the top of list of configuration files - */ - static addConfigFile(path) { - - sdkUtils.addConfigFile(path); - } - - /** - * Adds a setting to override all settings that are - * part of the hierarchical configuration. - * - * hierarchy search order: - * 1. memory - settings added with this call - * 2. Command-line arguments - * 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) - * 4. Custom Files - all files added with the addConfigFile(path) - * will be ordered by when added, were last one added will override previously added files - * 5. The file located at 'config/default.json' with default settings - * - * @param {String} name - The name of a setting - * @param {Object} value - The value of a setting - */ - static setConfigSetting(name, value) { - - sdkUtils.setConfigSetting(name, value); - } - - /** - * Retrieves a setting from the hierarchical configuration and if not found - * will return the provided default value. - * - * hierarchy search order: - * 1. memory - settings added with sdkUtils.setConfigSetting(name,value) - * 2. Command-line arguments - * 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) - * 4. Custom Files - all files added with the addConfigFile(path) - * will be ordered by when added, were last one added will override previously added files - * 5. The file located at 'config/default.json' with default settings - * - * @param {String} name - The name of a setting - * @param {Object} default_value - The value of a setting if not found in the hierarchical configuration - */ - static getConfigSetting(name, default_value) { - - return sdkUtils.getConfigSetting(name, default_value); - } }; function readFile(path) { diff --git a/fabric-client/lib/Peer.js b/fabric-client/lib/Peer.js index 55d9d2a1e1..305c1dbacf 100644 --- a/fabric-client/lib/Peer.js +++ b/fabric-client/lib/Peer.js @@ -42,6 +42,7 @@ var logger = utils.getLogger('Peer.js'); * channel and chaincode levels. * * @class + * @extends Remote */ var Peer = class extends Remote { diff --git a/fabric-client/lib/TransactionID.js b/fabric-client/lib/TransactionID.js index 2302cfb944..d14eb65b26 100644 --- a/fabric-client/lib/TransactionID.js +++ b/fabric-client/lib/TransactionID.js @@ -42,7 +42,7 @@ var TransactionID = class { if (typeof userContext === 'undefined' || userContext === null) { throw new Error('Missing userContext parameter'); } - if(!(userContext instanceof User)) { + if(!(User.isInstance(userContext))) { throw new Error('Parameter "userContext" must be an instance of the "User" class'); } this._nonce = sdkUtils.getNonce(); //nonce is in bytes diff --git a/fabric-client/lib/User.js b/fabric-client/lib/User.js index 3d103eb4f1..8fd2d59815 100644 --- a/fabric-client/lib/User.js +++ b/fabric-client/lib/User.js @@ -280,6 +280,17 @@ var User = class { return JSON.stringify(state); } + + static isInstance(object) { + return (typeof object._name !== 'undefined' && + typeof object._roles !== 'undefined' && + typeof object._affiliation !== 'undefined' && + typeof object._enrollmentSecret !== 'undefined' && + typeof object._identity !== 'undefined' && + typeof object._signingIdentity !== 'undefined' && + typeof object._mspId !== 'undefined' && + typeof object._cryptoSuite !== 'undefined'); + } }; module.exports = User; diff --git a/fabric-client/lib/impl/CouchDBKeyValueStore.js b/fabric-client/lib/impl/CouchDBKeyValueStore.js index 323263bc2c..7027d8c76b 100644 --- a/fabric-client/lib/impl/CouchDBKeyValueStore.js +++ b/fabric-client/lib/impl/CouchDBKeyValueStore.js @@ -30,6 +30,7 @@ var logger = utils.getLogger('CouchDBKeyValueStore.js'); * It uses a local or remote CouchDB database instance to store the keys. * * @class + * @extends module:api.KeyValueStore */ var CouchDBKeyValueStore = class extends api.KeyValueStore { @@ -72,14 +73,14 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { if (err) { // Database doesn't exist if (err.error == 'not_found') { - logger.info(util.format('No %s found, creating %s', self._name, self._name)); + logger.debug(util.format('No %s found, creating %s', self._name, self._name)); dbClient.db.create(self._name, function(err, body) { if (err) { return reject(new Error(util.format('Failed to create %s database due to error: %s', self._name, err.stack ? err.stack : err))); } - logger.info(util.format('Created %s database', self._name)); + logger.debug(util.format('Created %s database', self._name)); // Specify it as the database to use self._database = dbClient.use(self._name); resolve(self); @@ -90,7 +91,7 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { } } else { // Database exists - logger.info(util.format('%s already exists', self._name)); + logger.debug(util.format('%s already exists', self._name)); // Specify it as the database to use self._database = dbClient.use(self._name); resolve(self); @@ -99,12 +100,6 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { }); } - /** - * Get the value associated with name. - * @param {string} name - * @returns Promise for the value - * @ignore - */ getValue(name) { logger.debug('getValue: ' + name); @@ -117,7 +112,7 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { logger.error('getValue: ' + name + ', ERROR: [member_db.get] - ', err.error); return reject(err.error); } else { - logger.info('getValue: ' + name + ', Entry does not exist'); + logger.debug('getValue: ' + name + ', Entry does not exist'); return resolve(null); } } else { @@ -128,13 +123,6 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { }); } - /** - * Set the value associated with name. - * @param {string} name - * @param {string} value - * @returns Promise for a 'true' value on successful completion - * @ignore - */ setValue(name, value) { logger.debug('setValue: ' + name); diff --git a/fabric-client/lib/impl/CryptoKeyStore.js b/fabric-client/lib/impl/CryptoKeyStore.js index 6892f6596f..288936506f 100644 --- a/fabric-client/lib/impl/CryptoKeyStore.js +++ b/fabric-client/lib/impl/CryptoKeyStore.js @@ -52,7 +52,7 @@ var CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { // next try the public key entry return self.getValue(_getKeyIndex(ski, false)); }).then((key) => { - if (key instanceof ECDSAKey) + if (ECDSAKey.isInstance(key)) return key; if (key !== null) { diff --git a/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js b/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js index 22d586d85d..ff81c865d4 100755 --- a/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js +++ b/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js @@ -251,13 +251,12 @@ var CryptoSuite_ECDSA_AES = class extends api.CryptoSuite { store = st; return store.getKey(ski); }).then((key) => { - if (key instanceof ECDSAKey) + if (ECDSAKey.isInstance(key)) return resolve(key); if (key !== null) { var pubKey = KEYUTIL.getKey(key); - return resolve(new ECDSAKey(pubKey)); - } + return resolve(new ECDSAKey(pubKey)); } }).catch((err) => { reject(err); }); diff --git a/fabric-client/lib/impl/FileKeyValueStore.js b/fabric-client/lib/impl/FileKeyValueStore.js index 0b0f619bb1..b0693b1094 100644 --- a/fabric-client/lib/impl/FileKeyValueStore.js +++ b/fabric-client/lib/impl/FileKeyValueStore.js @@ -28,6 +28,7 @@ var logger = utils.getLogger('FileKeyValueStore.js'); * It uses files to store the key values. * * @class + * @extends module:api.KeyValueStore */ var FileKeyValueStore = class extends api.KeyValueStore { @@ -64,12 +65,6 @@ var FileKeyValueStore = class extends api.KeyValueStore { }); } - /** - * Get the value associated with name. - * @param {string} name - * @returns Promise for the value - * @ignore - */ getValue(name) { logger.debug('FileKeyValueStore -- getValue'); @@ -90,13 +85,6 @@ var FileKeyValueStore = class extends api.KeyValueStore { }); } - /** - * Set the value associated with name. - * @param {string} name - * @param {string} value - * @returns Promise for a "true" value on successful completion - * @ignore - */ setValue(name, value) { logger.debug('FileKeyValueStore -- setValue'); diff --git a/fabric-client/lib/impl/bccsp_pkcs11.js b/fabric-client/lib/impl/bccsp_pkcs11.js index 087192c271..b87b94777d 100644 --- a/fabric-client/lib/impl/bccsp_pkcs11.js +++ b/fabric-client/lib/impl/bccsp_pkcs11.js @@ -46,6 +46,7 @@ var __func = function() { * PKCS#11-compliant implementation to support Hardware Security Modules. * * @class + * @extends module:api.CryptoSuite */ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { diff --git a/fabric-client/lib/impl/ecdsa/key.js b/fabric-client/lib/impl/ecdsa/key.js index 5595affeb2..19bb663ec7 100644 --- a/fabric-client/lib/impl/ecdsa/key.js +++ b/fabric-client/lib/impl/ecdsa/key.js @@ -25,12 +25,13 @@ var ECDSA = jsrsa.ECDSA; var logger = utils.getLogger('ecdsa/key.js'); -/* +/** * This module implements the {@link module:api.Key} interface, for ECDSA. - * @module ECDSA_KEY + * @class ECDSA_KEY + * @extends module:api.Key */ module.exports = class ECDSA_KEY { - /* + /** * this class represents the private or public key of an ECDSA key pair. * * @param {Object} key This must be the "privKeyObj" or "pubKeyObj" part of the object generated by jsrsasign.KEYUTIL.generateKeypair() @@ -147,4 +148,15 @@ module.exports = class ECDSA_KEY { return KEYUTIL.getPEM(this._key); } } + + static isInstance(object) { + if (typeof object._key === 'undefined') { + return false; + } + + let key = object._key; + return (key.type && key.type === 'EC' && + typeof key.prvKeyHex !== 'undefined' && // prvKeyHex value can be null for public keys, so need to check typeof here + typeof key.pubKeyHex === 'string'); // pubKeyHex must have a non-null value + } }; \ No newline at end of file diff --git a/fabric-client/lib/impl/ecdsa/pkcs11_key.js b/fabric-client/lib/impl/ecdsa/pkcs11_key.js index 2c9ab5743a..c60a36d5ab 100644 --- a/fabric-client/lib/impl/ecdsa/pkcs11_key.js +++ b/fabric-client/lib/impl/ecdsa/pkcs11_key.js @@ -22,6 +22,13 @@ const _spkiBase = { 256: '3059301306072A8648CE3D020106082A8648CE3D030107034200', 384: '', }; +/** + * This module implements the {@link module:api.Key} interface, for ECDSA key management + * by Hardware Security Module support via PKCS#11 interface. + * + * @class PKCS11_ECDSA_KEY + * @extends module:api.Key + */ var PKCS11_ECDSA_KEY = class extends api.Key { constructor(attr, size) { diff --git a/fabric-client/lib/msp/identity.js b/fabric-client/lib/msp/identity.js index 809562d58f..e94c0f6bba 100755 --- a/fabric-client/lib/msp/identity.js +++ b/fabric-client/lib/msp/identity.js @@ -212,6 +212,14 @@ var SigningIdentity = class extends Identity { var digest = hashFunction(msg); return this._signer.sign(Buffer.from(digest, 'hex'), null); } + + static isInstance(object) { + return object._certificate && + object._publicKey && + object._mspId && + object._cryptoSuite && + object._signer; + } }; module.exports.Identity = Identity; diff --git a/fabric-client/lib/msp/msp.js b/fabric-client/lib/msp/msp.js index 23460adf56..ac6f465bbf 100755 --- a/fabric-client/lib/msp/msp.js +++ b/fabric-client/lib/msp/msp.js @@ -47,7 +47,7 @@ var MSP = class { if (typeof config.signer !== 'undefined') { // when constructing local msp, a signer property is required and it must be an instance of SigningIdentity - if (!(config.signer instanceof SigningIdentity)) { + if (!(SigningIdentity.isInstance(config.signer))) { throw new Error('Parameter "signer" must be an instance of SigningIdentity'); } } diff --git a/fabric-client/lib/utils.js b/fabric-client/lib/utils.js index 28552a2fe9..2abc683366 100644 --- a/fabric-client/lib/utils.js +++ b/fabric-client/lib/utils.js @@ -210,7 +210,7 @@ module.exports.getLogger = function(name) { } var logger = new winston.Logger(options); - logger.info('Successfully constructed a winston logger with configurations', config); + logger.debug('Successfully constructed a winston logger with configurations', config); saveLogger(logger); return insertLoggerName(logger, name); } catch(err) { @@ -225,7 +225,7 @@ module.exports.getLogger = function(name) { var logger = newDefaultLogger(); saveLogger(logger); - logger.info('Returning a new winston logger with default configurations'); + logger.debug('Returning a new winston logger with default configurations'); return insertLoggerName(logger, name); }; @@ -446,7 +446,7 @@ var CryptoKeyStore = function(KVSImplClass, opts) { var self = this; return new Promise((resolve, reject) => { if (self._store === null) { - self.logger.info(util.format('This class requires a CryptoKeyStore to save keys, using the store: %j', self._storeConfig)); + self.logger.debug(util.format('This class requires a CryptoKeyStore to save keys, using the store: %j', self._storeConfig)); CKS(self._storeConfig.superClass, self._storeConfig.opts) .then((ks) => { diff --git a/package.json b/package.json index 1e7b0a6f0b..3a6be5aaed 100644 --- a/package.json +++ b/package.json @@ -19,11 +19,13 @@ "bn.js": "^4.11.6", "bunyan": "^1.8.10", "cloudant": "^1.7.0", + "del": "^2.2.2", "elliptic": "^6.3.2", "fabric-ca-client": "file:./fabric-ca-client", "fabric-client": "file:./fabric-client", "fs-extra": "^2.0.0", "gulp": "^3.9.1", + "gulp-add-src": "^0.2.0", "gulp-debug": "^3.0.0", "gulp-eslint": "^3.0.1", "gulp-istanbul": "^1.1.1", diff --git a/test/fixtures/local.json b/test/fixtures/local.json index 93c5a106ee..c7e9e6f42a 100644 --- a/test/fixtures/local.json +++ b/test/fixtures/local.json @@ -1,8 +1,4 @@ { - "request-timeout" : 7000, - "tcert-batch-size" : 30, - "ssl-target-name-override" : "localca", - "default-authority" : "localca", "test-1": "local", "test-2": "local", "test-3": "local", diff --git a/test/integration/client.js b/test/integration/client.js index 977396b3ea..d722d3da8f 100644 --- a/test/integration/client.js +++ b/test/integration/client.js @@ -16,10 +16,7 @@ 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('integration.client'); var tape = require('tape'); @@ -29,18 +26,20 @@ var util = require('util'); var path = require('path'); var fs = require('fs-extra'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var User = require('fabric-client/lib/User.js'); -var Client = require('fabric-client/lib/Client.js'); var testUtil = require('../unit/util.js'); var couchdbUtil = require('./couchdb-util.js'); var tag = 'integration.client: '; -hfc.addConfigFile(path.join(__dirname, '../fixtures/caimport.json')); -var caImport = utils.getConfigSetting('ca-import', 'notfound'); +var caImport; logger.debug('caImport = %s', JSON.stringify(caImport)); test('\n\n ** createUser happy path - file store **\n\n', function (t) { + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, '../fixtures/caimport.json')); + caImport = utils.getConfigSetting('ca-import', 'notfound'); + utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); utils.setConfigSetting('crypto-keysize', 256); var userOrg = 'org1'; @@ -50,20 +49,20 @@ test('\n\n ** createUser happy path - file store **\n\n', function (t) { var keyStoreOpts = {path: path.join(testUtil.getTempDir(), caImport.orgs[userOrg].storePath)}; var client = new Client(); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore(keyStoreOpts)); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); - logger.info('try to cleanup kvs Path: '+keyStoreOpts.path); + logger.debug('try to cleanup kvs Path: '+keyStoreOpts.path); // clean up if (testUtil.existsSync(keyStoreOpts.path)) { fs.removeSync(keyStoreOpts.path); - logger.info('removed kvsPath: '+keyStoreOpts.path); + logger.debug('removed kvsPath: '+keyStoreOpts.path); } return utils.newKeyValueStore(keyStoreOpts) .then((store) => { - logger.info('store: %s',store); + logger.debug('store: %s',store); client.setStateStore(store); return ''; }).then(() => { @@ -92,34 +91,32 @@ test('\n\n ** createUser happy path - file store **\n\n', function (t) { test('\n\n ** createUser happy path - CouchDB **\n\n', function (t) { // Use the CouchDB specific config file - hfc.addConfigFile('test/fixtures/couchdb.json'); + Client.addConfigFile('test/fixtures/couchdb.json'); utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js');//override - var couchdbIPAddr = hfc.getConfigSetting('couchdb-ip-addr', 'notfound'); - var couchdbPort = hfc.getConfigSetting('couchdb-port', 'notfound'); + var couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); + var couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); var keyValStorePath = couchdbIPAddr + ':' + couchdbPort; // Clean up the couchdb test database var userOrg = 'org1'; var dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); var keyStoreOpts = {name: dbname, url: keyValStorePath}; - logger.info('couch keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); + logger.debug('couch keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); var prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); var sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); var client = new Client(); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore(keyStoreOpts)); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); couchdbUtil.destroy(dbname, keyValStorePath) .then((status) => { - t.comment(tag+'Cleanup of existing ' + dbname + ' returned '+status); - t.comment(tag+'Initialize the CouchDB KeyValueStore'); return utils.newKeyValueStore(keyStoreOpts); }).then((store) => { - logger.info('store: %s',store); + logger.debug('store: %s',store); client.setStateStore(store); return true; }).then((status) => { @@ -146,35 +143,33 @@ test('\n\n ** createUser happy path - CouchDB **\n\n', function (t) { test('\n\n ** createUser happy path - Cloudant **\n\n', function (t) { // Use the Cloudant specific config file - hfc.addConfigFile('test/fixtures/cloudant.json'); + Client.addConfigFile('test/fixtures/cloudant.json'); utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js');//override - var cloudantUsername = hfc.getConfigSetting('cloudant-username', 'notfound'); - var cloudantPassword = hfc.getConfigSetting('cloudant-password', 'notfound'); - var cloudantBluemix = hfc.getConfigSetting('cloudant-bluemix', 'notfound'); + var cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); + var cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); + var cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); var cloudantUrl = 'https://' + cloudantUsername + ':' + cloudantPassword + cloudantBluemix; // Clean up the cloudant test database var userOrg = 'org1'; var dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); var keyStoreOpts = {name: dbname, url: cloudantUrl}; - logger.info('cloudant keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); + logger.debug('cloudant keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); var prvKey = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.privateKey); var sgnCert = path.join(__dirname, caImport.orgs[userOrg].cryptoContent.signedCert); var client = new Client(); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore(keyStoreOpts)); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); couchdbUtil.destroy(dbname, cloudantUrl) .then((status) => { - t.comment(tag+'Cleanup of existing ' + dbname + ' returned '+status); - t.comment(tag+'Initialize the CouchDB KeyValueStore'); return utils.newKeyValueStore(keyStoreOpts); }).then((store) => { - logger.info('store: %s',store); + logger.debug('store: %s',store); client.setStateStore(store); return true; }).then((status) => { @@ -200,32 +195,30 @@ test('\n\n ** createUser happy path - Cloudant **\n\n', function (t) { test('\n\n ** createUser happy path - Cloudant - PEM Strings **\n\n', function (t) { // Use the Cloudant specific config file - hfc.addConfigFile('test/fixtures/cloudant.json'); + Client.addConfigFile('test/fixtures/cloudant.json'); utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/CouchDBKeyValueStore.js');//override - var cloudantUsername = hfc.getConfigSetting('cloudant-username', 'notfound'); - var cloudantPassword = hfc.getConfigSetting('cloudant-password', 'notfound'); - var cloudantBluemix = hfc.getConfigSetting('cloudant-bluemix', 'notfound'); + var cloudantUsername = Client.getConfigSetting('cloudant-username', 'notfound'); + var cloudantPassword = Client.getConfigSetting('cloudant-password', 'notfound'); + var cloudantBluemix = Client.getConfigSetting('cloudant-bluemix', 'notfound'); var cloudantUrl = 'https://' + cloudantUsername + ':' + cloudantPassword + cloudantBluemix; // Clean up the cloudant test database var userOrg = 'org2'; var dbname = (caImport.orgs[userOrg].name+'_db').toLowerCase(); var keyStoreOpts = {name: dbname, url: cloudantUrl}; - logger.info('cloudant keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); + logger.debug('cloudant keyStoreOpts: '+ JSON.stringify(keyStoreOpts)); var client = new Client(); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore(keyStoreOpts)); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(keyStoreOpts)); client.setCryptoSuite(cryptoSuite); couchdbUtil.destroy(dbname, cloudantUrl) .then((status) => { - t.comment(tag+'Cleanup of existing ' + dbname + ' returned '+status); - t.comment(tag+'Initialize the CouchDB KeyValueStore'); return utils.newKeyValueStore(keyStoreOpts); }).then((store) => { - logger.info('store: %s',store); + logger.debug('store: %s',store); client.setStateStore(store); return true; }).then((status) => { diff --git a/test/integration/cloudant-fabricca-tests.js b/test/integration/cloudant-fabricca-tests.js index a559bc26b8..8f9a26fae0 100644 --- a/test/integration/cloudant-fabricca-tests.js +++ b/test/integration/cloudant-fabricca-tests.js @@ -14,10 +14,7 @@ * limitations under the License. */ -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('cloudant-fabricca'); var tape = require('tape'); @@ -25,26 +22,23 @@ var _test = require('tape-promise'); var test = _test(tape); var path = require('path'); -var hfc = require('fabric-client'); -var Client = hfc; +var Client = require('fabric-client'); var User = require('fabric-client/lib/User.js'); var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl'); var CouchDBKeyValueStore = require('fabric-client/lib/impl/CouchDBKeyValueStore'); - +var testUtil = require('../unit/util.js'); var couchdbUtil = require('./couchdb-util.js'); var cloudantUrl = 'https://1421acc7-6faa-491a-8e10-951e2e190684-bluemix:7179ef7a72602189243deeabe207889bde1c2fada173ae1022b5592e5a79dacc@1421acc7-6faa-491a-8e10-951e2e190684-bluemix.cloudant.com'; -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); +var ORGS; var userOrg = 'org1'; var tlsOptions = { trustedRoots: [], verify: false }; -var fabricCAEndpoint = ORGS[userOrg].ca.url; // This test first checks to see if a user has already been enrolled. If so, // the test terminates. If the user is not yet enrolled, the test uses the @@ -52,9 +46,14 @@ var fabricCAEndpoint = ORGS[userOrg].ca.url; // CouchDB KeyValueStore. Then the test uses the Chain class to load the member // from the key value store. test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { - hfc.addConfigFile('test/fixtures/cloudant.json'); - var keyValueStore = hfc.getConfigSetting('key-value-store'); - logger.info('cloudant Key Value Store = ' + keyValueStore); + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + var fabricCAEndpoint = ORGS[userOrg].ca.url; + + Client.addConfigFile('test/fixtures/cloudant.json'); + var keyValueStore = Client.getConfigSetting('key-value-store'); + logger.debug('cloudant Key Value Store = ' + keyValueStore); // override t.end function so it'll always clear the config settings t.end = ((context, f) => { @@ -79,20 +78,16 @@ test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { var cryptoSuite, member, options; couchdbUtil.destroy(dbname, cloudantUrl) .then( function(status) { - t.comment('Cleanup of existing ' + dbname + ' returned '+status); - t.comment('Initilize the Cloudant CouchDB KeyValueStore'); options = {name: dbname, url: cloudantUrl}; utils.newKeyValueStore(options) .then( function(kvs) { - t.comment('Setting client keyValueStore to: ' + kvs); member = new User('admin2'); - cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore(options)); + cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(options)); client.setCryptoSuite(cryptoSuite); member.setCryptoSuite(cryptoSuite); - t.comment('Setting client keyValueStore to: ' +kvs); client.setStateStore(kvs); if (client.getStateStore() === kvs) { t.pass('Successfully set Cloudant CouchDB KeyValueStore for client'); @@ -101,7 +96,6 @@ test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { t.end(); process.exit(1); } - t.comment('Initialize the CA server connection and KeyValueStore'); return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, cryptoSuite); }, function(err) { @@ -112,10 +106,9 @@ test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { }) .then( function(caService) { - logger.info('ADD: caService - ' + caService); + logger.debug('ADD: caService - ' + caService); t.pass('Successfully initialized the Fabric CA service.'); - t.comment('Begin caService.enroll'); return caService.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' @@ -155,12 +148,10 @@ test('Use FabricCAServices wih a Cloudant CouchDB KeyValueStore', function(t) { }) .then( function(user) { - t.comment('setting UserContext to different user to clear out previous user'); return client.setUserContext(new User('userx')); }) .then( function(user) { - t.comment('getUserContext, loading user admin2 from StateStore...'); client.setCryptoSuite(cryptoSuite); return client.getUserContext('admin2', true); } diff --git a/test/integration/configtx-e2e.js b/test/integration/configtx-e2e.js deleted file mode 100644 index fc453e5bbc..0000000000 --- a/test/integration/configtx-e2e.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2017 IBM All Rights Reserved. - * - * 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. - */ -// end to end using a configtx built configuration - -'use strict'; - -// create done in it's own file so that it can be a live test setting -// environment settings - -delete require.cache[require.resolve('./e2e/join-channel.js')]; -require('./e2e/join-channel.js'); -// no need to install... code is already installed from last run -//delete require.cache[require.resolve('./e2e/install-chaincode.js')]; -//require('./e2e/install-chaincode.js'); -//delete require.cache[require.resolve('./e2e/instantiate-chaincode.js')]; -//require('./e2e/instantiate-chaincode.js'); -//delete require.cache[require.resolve('./e2e/invoke-transaction.js')]; -//require('./e2e/invoke-transaction.js'); -//delete require.cache[require.resolve('./e2e/query.js')]; -//require('./e2e/query.js'); -//delete require.cache[require.resolve('./e2e/upgrade.js')]; -//require('./e2e/upgrade.js'); diff --git a/test/integration/couchdb-fabricca-tests.js b/test/integration/couchdb-fabricca-tests.js index 6a32db6ad3..0f563778dc 100644 --- a/test/integration/couchdb-fabricca-tests.js +++ b/test/integration/couchdb-fabricca-tests.js @@ -14,10 +14,7 @@ * limitations under the License. */ -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('couchdb-fabricca'); var tape = require('tape'); @@ -25,23 +22,21 @@ var _test = require('tape-promise'); var test = _test(tape); var path = require('path'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); -var Client = hfc; var User = require('fabric-client/lib/User.js'); var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl'); +var testUtil = require('../unit/util.js'); var couchdbUtil = require('./couchdb-util.js'); -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); +var ORGS; var userOrg = 'org1'; var tlsOptions = { trustedRoots: [], verify: false }; -var fabricCAEndpoint = ORGS[userOrg].ca.url; // This test first checks to see if a user has already been enrolled. If so, // the test terminates. If the user is not yet enrolled, the test uses the @@ -49,14 +44,19 @@ var fabricCAEndpoint = ORGS[userOrg].ca.url; // CouchDB KeyValueStore. Then the test uses the Client class to load the member // from the key value store. test('Use FabricCAServices with a CouchDB KeyValueStore', function(t) { + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + // Use the CouchDB specific config file - hfc.addConfigFile('test/fixtures/couchdb.json'); + Client.addConfigFile('test/fixtures/couchdb.json'); - var keyValueStore = hfc.getConfigSetting('key-value-store'); + var fabricCAEndpoint = ORGS[userOrg].ca.url; + var keyValueStore = Client.getConfigSetting('key-value-store'); logger.info('couchdb Key Value Store = ' + keyValueStore); - var couchdbIPAddr = hfc.getConfigSetting('couchdb-ip-addr', 'notfound'); - var couchdbPort = hfc.getConfigSetting('couchdb-port', 'notfound'); + var couchdbIPAddr = Client.getConfigSetting('couchdb-ip-addr', 'notfound'); + var couchdbPort = Client.getConfigSetting('couchdb-port', 'notfound'); var keyValStorePath = couchdbIPAddr + ':' + couchdbPort; logger.info('couch keyValStorePath: '+keyValStorePath); @@ -90,8 +90,8 @@ test('Use FabricCAServices with a CouchDB KeyValueStore', function(t) { function(kvs) { member = new User('admin2'); - cryptoSuite = client.newCryptoSuite(options); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore(options)); + cryptoSuite = Client.newCryptoSuite(options); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore(options)); client.setCryptoSuite(cryptoSuite); member.setCryptoSuite(cryptoSuite); @@ -165,7 +165,6 @@ test('Use FabricCAServices with a CouchDB KeyValueStore', function(t) { }) .then( function(user) { - t.comment('getUserContext, loading user admin2 from StateStore...'); client.setCryptoSuite(cryptoSuite); return client.getUserContext('admin2', true); }) diff --git a/test/integration/couchdb-util.js b/test/integration/couchdb-util.js index d067a84543..976f98d38a 100644 --- a/test/integration/couchdb-util.js +++ b/test/integration/couchdb-util.js @@ -14,13 +14,13 @@ * limitations under the License. */ -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var nano = require('nano'); var Cloudant = require('cloudant'); module.exports.getCloudantClient = function(configFile) { - var username = hfc.getConfigSetting('cloudant-username', 'notfound'); - var password = hfc.getConfigSetting('cloudant-password', 'notfound'); + var username = Client.getConfigSetting('cloudant-username', 'notfound'); + var password = Client.getConfigSetting('cloudant-password', 'notfound'); console.log('CloudantClient username = ' + username + ', password: ' + password); return Cloudant({account: username, password: password}); }; diff --git a/test/integration/create-configtx-channel.js b/test/integration/create-configtx-channel.js index 614603ec06..85be525e77 100644 --- a/test/integration/create-configtx-channel.js +++ b/test/integration/create-configtx-channel.js @@ -31,17 +31,18 @@ var testUtil = require('../unit/util.js'); var e2eUtils = require('./e2e/e2eUtils.js'); var the_user = null; - -Client.addConfigFile(path.join(__dirname, './config.json')); -var ORGS = Client.getConfigSetting('test-network'); +var ORGS; // //Attempt to send a request to the orderer with the createChannel method // test('\n\n***** Configtx Built config create flow *****\n\n', function(t) { + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + var channel_name = 'mychanneltx'; Client.setConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', channel_name); - logger.info('\n\n >>>>>> Will create new channel with name :: %s <<<<<<< \n\n',channel_name); // // Create and configure the test channel diff --git a/test/integration/e2e/create-channel.js b/test/integration/e2e/create-channel.js index 43789fba0a..314c56365e 100644 --- a/test/integration/e2e/create-channel.js +++ b/test/integration/e2e/create-channel.js @@ -15,8 +15,6 @@ */ 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); var logger = utils.getLogger('E2E create-channel'); @@ -38,8 +36,7 @@ var e2eUtils = require('./e2eUtils.js'); var the_user = null; -Client.addConfigFile(path.join(__dirname, './config.json')); -var ORGS = Client.getConfigSetting('test-network'); +var ORGS; var channel_name = 'mychannel'; // can use "channel=" to control the channel name from command line @@ -49,11 +46,14 @@ if (process.argv.length > 2) { } } -logger.info('\n\n >>>>>> Will create new channel with name :: %s <<<<<<< \n\n',channel_name); // //Attempt to send a request to the orderer with the createChannel method // test('\n\n***** SDK Built config update create flow *****\n\n', function(t) { + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, './config.json')); + ORGS = Client.getConfigSetting('test-network'); + // // Create and configure the test channel // @@ -105,13 +105,6 @@ test('\n\n***** SDK Built config update create flow *****\n\n', function(t) { var config = null; var signatures = []; - var msps = []; - - msps.push(client.newMSP( e2eUtils.loadMSPConfig('OrdererMSP', '../../fixtures/channel/crypto-config/ordererOrganizations/example.com/msp/'))); - - msps.push(client.newMSP( e2eUtils.loadMSPConfig('Org1MSP', '../../fixtures/channel/crypto-config/peerOrganizations/org1.example.com/msp/'))); - - msps.push(client.newMSP( e2eUtils.loadMSPConfig('Org2MSP', '../../fixtures/channel/crypto-config/peerOrganizations/org2.example.com/msp/'))); // Acting as a client in org1 when creating the channel var org = ORGS.org1.name; @@ -122,8 +115,8 @@ test('\n\n***** SDK Built config update create flow *****\n\n', function(t) { path: testUtil.storePathForOrg(org) }).then((store) => { client.setStateStore(store); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(org)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(org)})); client.setCryptoSuite(cryptoSuite); return testUtil.getOrderAdminSubmitter(client, t); diff --git a/test/integration/e2e/e2eUtils.js b/test/integration/e2e/e2eUtils.js index 9bee512809..7350402dca 100644 --- a/test/integration/e2e/e2eUtils.js +++ b/test/integration/e2e/e2eUtils.js @@ -32,24 +32,33 @@ var Client = require('fabric-client'); var testUtil = require('../../unit/util.js'); var e2e = testUtil.END2END; -Client.addConfigFile(path.join(__dirname, './config.json')); -var ORGS = Client.getConfigSetting('test-network'); +var ORGS; var grpc = require('grpc'); var tx_id = null; var the_user = null; +function init() { + if (!ORGS) { + Client.addConfigFile(path.join(__dirname, './config.json')); + ORGS = Client.getConfigSetting('test-network'); + } +} + function installChaincode(org, chaincode_path, version, t) { + init(); + Client.setConfigSetting('request-timeout', 60000); var channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); var client = new Client(); + // client.setDevMode(true); var channel = client.newChannel(channel_name); var orgName = ORGS[org].name; - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); var caRootsPath = ORGS.orderer.tls_cacerts; @@ -143,6 +152,8 @@ module.exports.installChaincode = installChaincode; function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ + init(); + Client.setConfigSetting('request-timeout', 60000); var channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); @@ -156,7 +167,7 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ for(var key in ehs) { var eventhub = ehs[key]; if (eventhub && eventhub.isconnected()) { - logger.info('Disconnecting the event hub'); + logger.debug('Disconnecting the event hub'); eventhub.disconnect(); } } @@ -169,8 +180,8 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ var channel = client.newChannel(channel_name); var orgName = ORGS[userOrg].name; - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); var caRootsPath = ORGS.orderer.tls_cacerts; @@ -207,7 +218,7 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ if (ORGS[org].hasOwnProperty('peer1')) { let key = 'peer1'; let data = fs.readFileSync(path.join(__dirname, ORGS[org][key]['tls_cacerts'])); - logger.info(' create new peer %s', ORGS[org][key].requests); + logger.debug(' create new peer %s', ORGS[org][key].requests); let peer = client.newPeer( ORGS[org][key].requests, { @@ -222,7 +233,7 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ } // an event listener can only register with a peer in its own org - logger.info(' create new eventhub %s', ORGS[userOrg]['peer1'].events); + logger.debug(' create new eventhub %s', ORGS[userOrg]['peer1'].events); let data = fs.readFileSync(path.join(__dirname, ORGS[userOrg]['peer1']['tls_cacerts'])); let eh = client.newEventHub(); eh.setPeerAddr( @@ -252,7 +263,7 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ let request = buildChaincodeProposal(client, the_user, chaincode_path, version, upgrade, badTransientMap); tx_id = request.txId; - t.comment(util.format( + logger.debug(util.format( 'Upgrading chaincode "%s" at path "%s" to version "%s" by passing args "%s" to method "%s" in transaction "%s"', request.chaincodeId, request.chaincodePath, @@ -321,7 +332,8 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ all_good = all_good & one_good; } if (all_good) { - t.pass(util.format('Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', proposalResponses[0].response.status, proposalResponses[0].response.message, proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature)); + t.pass('Successfully sent Proposal and received ProposalResponse'); + logger.debug(util.format('Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', proposalResponses[0].response.status, proposalResponses[0].response.message, proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature)); var request = { proposalResponses: proposalResponses, proposal: proposal, @@ -352,7 +364,7 @@ function instantiateChaincode(userOrg, chaincode_path, version, upgrade, t){ } }); }); - logger.info('register eventhub %s with tx=%s',eh.getPeerAddr(),deployId); + logger.debug('register eventhub %s with tx=%s',eh.getPeerAddr(),deployId); eventPromises.push(txPromise); }); @@ -437,6 +449,8 @@ module.exports.instantiateChaincode = instantiateChaincode; function invokeChaincode(userOrg, version, t, useStore){ + init(); + logger.debug('invokeChaincode begin'); Client.setConfigSetting('request-timeout', 60000); var channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); @@ -451,7 +465,7 @@ function invokeChaincode(userOrg, version, t, useStore){ for(var key in ehs) { var eventhub = ehs[key]; if (eventhub && eventhub.isconnected()) { - logger.info('Disconnecting the event hub'); + logger.debug('Disconnecting the event hub'); eventhub.disconnect(); } } @@ -468,9 +482,9 @@ function invokeChaincode(userOrg, version, t, useStore){ var channel = client.newChannel(channel_name); var orgName = ORGS[userOrg].name; - var cryptoSuite = client.newCryptoSuite(); + var cryptoSuite = Client.newCryptoSuite(); if (useStore) { - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); } @@ -541,8 +555,7 @@ function invokeChaincode(userOrg, version, t, useStore){ }).then((nothing) => { tx_id = client.newTransactionID(the_user); utils.setConfigSetting('E2E_TX_ID', tx_id.getTransactionID()); - logger.info('setConfigSetting("E2E_TX_ID") = %s', tx_id.getTransactionID()); - t.comment(util.format('Sending transaction "%s"', tx_id.getTransactionID())); + logger.debug('setConfigSetting("E2E_TX_ID") = %s', tx_id.getTransactionID()); // send proposal to endorser var request = { @@ -606,7 +619,8 @@ function invokeChaincode(userOrg, version, t, useStore){ } if (all_good) { // check to see if all the results match - t.pass(util.format('Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', proposalResponses[0].response.status, proposalResponses[0].response.message, proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature)); + t.pass('Successfully sent Proposal and received ProposalResponse'); + logger.debug(util.format('Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s', proposalResponses[0].response.status, proposalResponses[0].response.message, proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature)); var request = { proposalResponses: proposalResponses, proposal: proposal, @@ -695,6 +709,8 @@ function invokeChaincode(userOrg, version, t, useStore){ module.exports.invokeChaincode = invokeChaincode; function queryChaincode(org, version, value, t, transientMap) { + init(); + Client.setConfigSetting('request-timeout', 60000); var channel_name = Client.getConfigSetting('E2E_CONFIGTX_CHANNEL_NAME', testUtil.END2END.channel); @@ -706,8 +722,8 @@ function queryChaincode(org, version, value, t, transientMap) { var channel = client.newChannel(channel_name); var orgName = ORGS[org].name; - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); var targets = []; @@ -752,7 +768,6 @@ function queryChaincode(org, version, value, t, transientMap) { return channel.queryByChaincode(request); }, (err) => { - t.comment('Failed to get submitter \'admin\''); t.fail('Failed to get submitter \'admin\'. Error: ' + err.stack ? err.stack : err ); throw new Error('Failed to get submitter'); }).then((response_payloads) => { @@ -803,7 +818,7 @@ function readAllFiles(dir) { var certs = []; files.forEach((file_name) => { let file_path = path.join(dir,file_name); - console.log(' looking at file ::'+file_path); + console.debug(' looking at file ::'+file_path); let data = fs.readFileSync(file_path); certs.push(data); }); diff --git a/test/integration/e2e/install-chaincode.js b/test/integration/e2e/install-chaincode.js index 18f75f9a82..0d95fb71f2 100644 --- a/test/integration/e2e/install-chaincode.js +++ b/test/integration/e2e/install-chaincode.js @@ -28,9 +28,9 @@ var test = _test(tape); var e2eUtils = require('./e2eUtils.js'); var testUtil = require('../../unit/util.js'); -testUtil.setupChaincodeDeploy(); - test('\n\n***** End-to-end flow: chaincode install *****\n\n', (t) => { + testUtil.setupChaincodeDeploy(); + e2eUtils.installChaincode('org1', testUtil.CHAINCODE_PATH, 'v0', t) .then(() => { t.pass('Successfully installed chaincode in peers of organization "org1"'); diff --git a/test/integration/e2e/instantiate-chaincode.js b/test/integration/e2e/instantiate-chaincode.js index 272a7e5337..0e9cd50421 100644 --- a/test/integration/e2e/instantiate-chaincode.js +++ b/test/integration/e2e/instantiate-chaincode.js @@ -44,7 +44,7 @@ test('\n\n***** End-to-end flow: instantiate chaincode *****', (t) => { t.fail('Failed to instantiate chaincode on the channel. ' + err.stack ? err.stack : err); t.end(); }).then(() => { - t.comment('Successfully slept 5s to wait for chaincode instantiate to be completed and committed in all peers'); + logger.debug('Successfully slept 5s to wait for chaincode instantiate to be completed and committed in all peers'); t.end(); }).catch((err) => { t.fail('Test failed due to unexpected reasons. ' + err.stack ? err.stack : err); diff --git a/test/integration/e2e/invoke-transaction.js b/test/integration/e2e/invoke-transaction.js index d272a37053..115bd1a7c6 100755 --- a/test/integration/e2e/invoke-transaction.js +++ b/test/integration/e2e/invoke-transaction.js @@ -38,7 +38,6 @@ test('\n\n***** End-to-end flow: invoke transaction to move money *****', (t) => t.fail('Failed to invoke transaction chaincode on channel. ' + err.stack ? err.stack : err); t.end(); }).then(() => { - t.comment('Successfully slept for 5s to wait for the transaction to be committed in all peers'); t.end(); }).catch((err) => { t.fail('Test failed due to unexpected reasons. ' + err.stack ? err.stack : err); diff --git a/test/integration/e2e/join-channel.js b/test/integration/e2e/join-channel.js index d07ec13875..bb335f6808 100644 --- a/test/integration/e2e/join-channel.js +++ b/test/integration/e2e/join-channel.js @@ -33,8 +33,7 @@ var testUtil = require('../../unit/util.js'); var the_user = null; var tx_id = null; -Client.addConfigFile(path.join(__dirname, './config.json')); -var ORGS = Client.getConfigSetting('test-network'); +var ORGS; var allEventhubs = []; @@ -42,13 +41,16 @@ var allEventhubs = []; //Attempt to send a request to the orderer with the createChannel method // test('\n\n***** End-to-end flow: join channel *****\n\n', function(t) { + Client.addConfigFile(path.join(__dirname, './config.json')); + ORGS = Client.getConfigSetting('test-network'); + // override t.end function so it'll always disconnect the event hub t.end = ((context, ehs, f) => { return function() { for(var key in ehs) { var eventhub = ehs[key]; if (eventhub && eventhub.isconnected()) { - t.comment('Disconnecting the event hub'); + logger.debug('Disconnecting the event hub'); eventhub.disconnect(); } } @@ -203,7 +205,7 @@ function joinChannel(org, t) { throw new Error('Failed to enroll user \'admin\' due to error: ' + err.stack ? err.stack : err); }) .then((results) => { - t.comment(util.format('Join Channel R E S P O N S E : %j', results)); + logger.debug(util.format('Join Channel R E S P O N S E : %j', results)); if(results[0] && results[0][0] && results[0][0].response && results[0][0].response.status == 200) { t.pass(util.format('Successfully joined peers in organization %s to join the channel', orgName)); diff --git a/test/integration/e2e/update-channel.js b/test/integration/e2e/update-channel.js index b0ef7c5c0c..2792dddbaf 100644 --- a/test/integration/e2e/update-channel.js +++ b/test/integration/e2e/update-channel.js @@ -32,11 +32,14 @@ var logger = utils.getLogger('End to End'); var the_user = null; -Client.addConfigFile(path.join(__dirname, './config.json')); -var ORGS = Client.getConfigSetting('test-network'); +var ORGS; test('\n\n***** U P D A T E C H A N N E L flow: update channel *****\n\n', (t) => { + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, './config.json')); + ORGS = Client.getConfigSetting('test-network'); + // // Create and configure the test channel // diff --git a/test/integration/e2e/upgrade.js b/test/integration/e2e/upgrade.js index e453832cda..0539be827d 100644 --- a/test/integration/e2e/upgrade.js +++ b/test/integration/e2e/upgrade.js @@ -24,9 +24,9 @@ var test = _test(tape); var e2eUtils = require('./e2eUtils.js'); var testUtil = require('../../unit/util.js'); -testUtil.setupChaincodeDeploy(); - test('\n\n***** U P G R A D E flow: chaincode install *****\n\n', (t) => { + testUtil.setupChaincodeDeploy(); + e2eUtils.installChaincode('org1', testUtil.CHAINCODE_UPGRADE_PATH, 'v1', t) .then(() => { t.pass('Successfully installed chaincode in peers of organization "org1"'); diff --git a/test/integration/events.js b/test/integration/events.js index 254ac23bca..c5f946e384 100644 --- a/test/integration/events.js +++ b/test/integration/events.js @@ -16,8 +16,6 @@ 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); var logger = utils.getLogger('events'); @@ -29,68 +27,60 @@ var path = require('path'); var util = require('util'); var fs = require('fs'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var testUtil = require('../unit/util.js'); var eputil = require('./eventutil.js'); -var client = new hfc(); +var client = new Client(); var channel = client.newChannel(testUtil.END2END.channel); -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); +var ORGS; -var caRootsPath = ORGS.orderer.tls_cacerts; -let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); -let caroots = Buffer.from(data).toString(); - -channel.addOrderer( - client.newOrderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) -); - -var org = 'org1'; -var orgName = ORGS[org].name; -var targets = []; -for (let key in ORGS[org]) { - if (ORGS[org].hasOwnProperty(key)) { - if (key.indexOf('peer') === 0) { - let data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); - let peer = client.newPeer( - ORGS[org][key].requests, - { - pem: Buffer.from(data).toString(), - 'ssl-target-name-override': ORGS[org][key]['server-hostname'] - }); - channel.addPeer(peer); - targets.push(peer); - break; //just add one - } - } -} var chaincode_id = testUtil.getUniqueVersion('events_unit_test'); var chaincode_version = testUtil.getUniqueVersion(); var request = null; var the_user = null; -var steps = []; -if (process.argv.length > 2) { - for (let i = 2; i < process.argv.length; i++) { - steps.push(process.argv[i]); - } -} -var useSteps = false; -if (steps.length > 0 && - (steps.indexOf('step1') > -1 || steps.indexOf('step2') > -1 || steps.indexOf('step3') > -1 || steps.indexOf('step4') > -1 )) - useSteps = true; -logger.info('Found steps: %s', steps); +test('Test chaincode instantiate with event, transaction invocation with chaincode event, and query number of chaincode events', (t) => { + testUtil.resetDefaults(); + testUtil.setupChaincodeDeploy(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + var ORGS = Client.getConfigSetting('test-network'); + Client.setConfigSetting('request-timeout', 30000); -testUtil.setupChaincodeDeploy(); + var caRootsPath = ORGS.orderer.tls_cacerts; + let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + let caroots = Buffer.from(data).toString(); + + channel.addOrderer( + client.newOrderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); + + var org = 'org1'; + var orgName = ORGS[org].name; + var targets = []; + for (let key in ORGS[org]) { + if (ORGS[org].hasOwnProperty(key)) { + if (key.indexOf('peer') === 0) { + let data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); + let peer = client.newPeer( + ORGS[org][key].requests, + { + pem: Buffer.from(data).toString(), + 'ssl-target-name-override': ORGS[org][key]['server-hostname'] + }); + channel.addPeer(peer); + targets.push(peer); + break; //just add one + } + } + } -test('Test chaincode instantiate with event, transaction invocation with chaincode event, and query number of chaincode events', (t) => { // must use an array to track the event hub instances so that when this gets // passed into the overriden t.end() closure below it will get properly updated // later when the eventhub instances are created @@ -106,7 +96,7 @@ test('Test chaincode instantiate with event, transaction invocation with chainco for(var key in ehs) { var eventhub = ehs[key]; if (eventhub && eventhub.isconnected()) { - logger.info('Disconnecting the event hub'); + logger.debug('Disconnecting the event hub'); eventhub.disconnect(); } } @@ -115,7 +105,7 @@ test('Test chaincode instantiate with event, transaction invocation with chainco }; })(t, eventhubs, t.end); - hfc.newDefaultKeyValueStore({ + Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then((store) => { client.setStateStore(store); @@ -158,14 +148,12 @@ test('Test chaincode instantiate with event, transaction invocation with chainco catch(err) { t.fail('this catch should not have been called'); } - t.comment(' ------ test about to sleep'); return sleep(5000); }, (err) => { t.fail('Failed to enroll user \'admin\'. ' + err); t.end(); }).then(() =>{ - t.comment(' ------ test is awake'); // now one that fails but not wait for it fail eh.setPeerAddr( @@ -229,8 +217,7 @@ test('Test chaincode instantiate with event, transaction invocation with chainco request.chaincodeVersion = chaincode_version; return channel.sendInstantiateProposal(request); }, (err) => { - t.comment('Failed to send instantiate proposal due to error: '); - t.fail(err.stack ? err.stack : err); + t.fail('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); t.end(); }).then((results) => { var tmo = 50000; @@ -247,7 +234,7 @@ test('Test chaincode instantiate with event, transaction invocation with chainco return channel.sendTransactionProposal(request); }, (err) => { - t.fail('Failed instantiate due to error: ' + err); + t.fail('Failed instantiate due to error: ' + err.stack ? err.stack : err); t.end(); }).then((results) => { var tmo = 20000; @@ -285,7 +272,6 @@ test('Test chaincode instantiate with event, transaction invocation with chainco t.fail('Failed to send query due to error: ' + err.stack ? err.stack : err); t.end(); }).then(([results1, results2]) => { - t.comment('sendTransactionProposal received [results1, results2]'); var tmo = 20000; return Promise.all([eputil.registerTxEvent(eh, req1.txId.getTransactionID().toString(), tmo), eputil.registerTxEvent(eh, req2.txId.getTransactionID().toString(), tmo), diff --git a/test/integration/eventutil.js b/test/integration/eventutil.js index 703f51ef01..d257ae67e4 100644 --- a/test/integration/eventutil.js +++ b/test/integration/eventutil.js @@ -16,8 +16,8 @@ 'use strict'; -var hfc = require('fabric-client'); var utils = require('fabric-client/lib/utils.js'); +var util = require('util'); module.exports.registerTxEvent = function(eh, txid, timeout) { return new Promise((resolve, reject) => { @@ -101,6 +101,7 @@ module.exports.sendTransaction = function(channel, results) { }; return channel.sendTransaction(request); } else { - return Promise.reject('bad result:' + results); + utils.getLogger('eventutil.js').error(util.format('bad result: %j', results)); + return Promise.reject('Proposal responses returned unsuccessful status'); } }; diff --git a/test/integration/fabric-ca-services-tests.js b/test/integration/fabric-ca-services-tests.js index 7dc4f84366..02ea801d8f 100644 --- a/test/integration/fabric-ca-services-tests.js +++ b/test/integration/fabric-ca-services-tests.js @@ -15,48 +15,47 @@ */ 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); -var utils = require('fabric-client/lib/utils.js'); -var logger = utils.getLogger('fabric-ca-services'); +///////////////////////////////////////////////////////////////// +// ---------------------- IMPORTANT ---------------------------- +// this test is meant to test the fabric-ca-client +// package ALONE! do not require anything from the fabric-client +// package. If anything is required but missing, add them to +// the fabric-ca-client package by editing build/tasks/ca.js +///////////////////////////////////////////////////////////////// var tape = require('tape'); var _test = require('tape-promise'); var test = _test(tape); - -var hfc = require('fabric-client'); - var X509 = require('x509'); var util = require('util'); var fs = require('fs-extra'); var path = require('path'); var testUtil = require('../unit/util.js'); -var LocalMSP = require('fabric-client/lib/msp/msp.js'); -var idModule = require('fabric-client/lib/msp/identity.js'); + +var LocalMSP = require('fabric-ca-client/lib/msp/msp.js'); +var idModule = require('fabric-ca-client/lib/msp/identity.js'); var SigningIdentity = idModule.SigningIdentity; var Signer = idModule.Signer; -var User = require('fabric-client/lib/User.js'); +var User = require('fabric-ca-client/lib/User.js'); var keyValStorePath = testUtil.KVS; -var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl'); +var FabricCAServices = require('fabric-ca-client'); var FabricCAClient = FabricCAServices.FabricCAClient; var enrollmentID = 'testUser'; var enrollmentSecret; var csr = fs.readFileSync(path.resolve(__dirname, '../fixtures/fabricca/enroll-csr.pem')); -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); var userOrg = 'org1'; +var ORGS, fabricCAEndpoint; var tlsOptions = { trustedRoots: [], verify: false }; -var fabricCAEndpoint = ORGS[userOrg].ca.url; /** * FabricCAServices class tests @@ -65,9 +64,13 @@ var fabricCAEndpoint = ORGS[userOrg].ca.url; //run the enroll test test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', function (t) { + testUtil.resetDefaults(); + FabricCAServices.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = FabricCAServices.getConfigSetting('test-network'); + fabricCAEndpoint = ORGS[userOrg].ca.url; - utils.getConfigSetting('crypto-keysize', '256');//force for gulp test - utils.setConfigSetting('crypto-hash-algo', 'SHA2');//force for gulp test + FabricCAServices.getConfigSetting('crypto-keysize', '256');//force for gulp test + FabricCAServices.setConfigSetting('crypto-hash-algo', 'SHA2');//force for gulp test var caService = new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name); @@ -90,10 +93,9 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', function t.fail(util.format('Failed to parse enrollment cert\n%s\n. Error: %s', enrollment.certificate, err)); } - t.comment(util.format('Parsed subject: %j', subject)); t.equal(subject.commonName, req.enrollmentID, 'Subject should be /CN=' + req.enrollmentID); - return caService.cryptoPrimitives.importKey(enrollment.certificate); + return caService.getCryptoSuite().importKey(enrollment.certificate); },(err) => { t.fail('Failed to enroll the admin. Can not progress any further. Exiting. ' + err.stack ? err.stack : err); @@ -103,42 +105,44 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', function var msp = new LocalMSP({ id: ORGS[userOrg].mspid, - cryptoSuite: caService.cryptoPrimitives + cryptoSuite: caService.getCryptoSuite() }); var signingIdentity = new SigningIdentity(eResult.certificate, pubKey, msp.getId(), msp.cryptoSuite, new Signer(msp.cryptoSuite, eResult.key)); - t.comment('Registering '+enrollmentID); return caService._fabricCAClient.register(enrollmentID, null, 'client', userOrg, 1, [], signingIdentity); },(err) => { t.fail('Failed to import the public key from the enrollment certificate. ' + err.stack ? err.stack : err); t.end(); }).then((secret) => { console.log('secret: ' + JSON.stringify(secret)); - t.comment(secret); enrollmentSecret = secret; // to be used in the next test case t.pass('testUser \'' + enrollmentID + '\''); - return hfc.newDefaultKeyValueStore({ - path: testUtil.KVS - }); + member = new User('adminX'); + return member.setEnrollment(eResult.key, eResult.certificate, 'Org1MSP'); },(err) => { t.fail(util.format('Failed to register "%s". %s', enrollmentID, err.stack ? err.stack : err)); t.end(); - }).then((store) => { - t.comment('Successfully constructed a state store'); - - client = new hfc(); - client.setStateStore(store); - member = new User('adminX'); - return member.setEnrollment(eResult.key, eResult.certificate, 'Org1MSP'); }).then(() => { - t.comment('Successfully constructed a user object based on the enrollment'); - return caService.register({enrollmentID: 'testUserX', affiliation: 'bank_X'}, member); + + // now test being able to save user to persistence store + return FabricCAServices.newDefaultKeyValueStore({ + path: testUtil.KVS + }); },(err) => { t.fail('Failed to configure the user with proper enrollment materials.'); t.end(); + }).then((store) => { + return store.setValue(member.getName(), member.toString()); + }, (err) => { + t.fail('Failed to obtain a state store from the fabric-ca-client'); + t.end(); + }).then(() => { + t.pass('Successfully saved user to state store'); + + return caService.register({enrollmentID: 'testUserX', affiliation: 'bank_X'}, member); }).then((secret) => { t.fail('Should not have been able to register user of a affiliation "bank_X" because "admin" does not belong to that affiliation'); t.end(); @@ -165,7 +169,6 @@ test('\n\n ** FabricCAServices: Test enroll() With Dynamic CSR **\n\n', function return caService.enroll({enrollmentID: 'testUserY', enrollmentSecret: secret}); }).then((enrollment) => { - t.comment('Successfully enrolled "testUserY"'); var cert; try { @@ -248,10 +251,8 @@ test('\n\n ** FabricCAClient: Test enroll With Static CSR **\n\n', function (t) caname: ORGS[userOrg].ca.name }); - t.comment(util.format('Sending enroll request for user %s with enrollment secret %s', enrollmentID, enrollmentSecret)); return client.enroll(enrollmentID, enrollmentSecret, csr.toString()) .then(function (enrollResponse) { - t.comment(enrollResponse.enrollmentCert); t.pass('Successfully invoked enroll API with enrollmentID \'' + enrollmentID + '\''); //check that we got back the expected certificate var subject; @@ -260,7 +261,6 @@ test('\n\n ** FabricCAClient: Test enroll With Static CSR **\n\n', function (t) } catch(err) { t.fail(util.format('Failed to parse enrollment cert\n%s\n. Error: %s', enrollResponse.enrollmentCert, err)); } - t.comment(subject); t.equal(subject.commonName, enrollmentID, 'Subject should be /CN=' + enrollmentID); t.end(); }) diff --git a/test/integration/fileKeyValueStore-fabricca-tests.js b/test/integration/fileKeyValueStore-fabricca-tests.js index 5b22934b7b..97718d4d9a 100644 --- a/test/integration/fileKeyValueStore-fabricca-tests.js +++ b/test/integration/fileKeyValueStore-fabricca-tests.js @@ -14,10 +14,7 @@ * limitations under the License. */ -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('fileKeyValStore-fabricca'); var tape = require('tape'); @@ -28,17 +25,14 @@ var testUtil = require('../unit/util.js'); var fs = require('fs-extra'); var path = require('path'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); -var Client = hfc; var User = require('fabric-client/lib/User.js'); var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl'); -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); var userOrg = 'org1'; +var ORGS; -var fabricCAEndpoint = ORGS[userOrg].ca.url; // This test first checks to see if a user has already been enrolled. If so, // the test terminates. If the user is not yet enrolled, the test uses the @@ -46,15 +40,17 @@ var fabricCAEndpoint = ORGS[userOrg].ca.url; // File KeyValueStore. Then the test uses the Client class to load the member // from the key value store. test('Use FabricCAServices with a File KeyValueStore', function(t) { + testUtil.resetDefaults(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + var fabricCAEndpoint = ORGS[userOrg].ca.url; // Set the relevant configuration values utils.setConfigSetting('crypto-keysize', 256); utils.setConfigSetting('key-value-store','fabric-client/lib/impl/FileKeyValueStore.js'); - var keyValueStore = hfc.getConfigSetting('key-value-store'); - logger.info('File Key Value Store = ' + keyValueStore); + var keyValueStore = Client.getConfigSetting('key-value-store'); var keyValStorePath = path.join(testUtil.getTempDir(), 'customKeyValStorePath'); - logger.info('keyValStorePath: '+keyValStorePath); var client = new Client(); var cryptoSuite, member, opts; @@ -69,17 +65,15 @@ test('Use FabricCAServices with a File KeyValueStore', function(t) { verify: false }; - t.comment('Initialize the File KeyValueStore'); utils.newKeyValueStore({path: keyValStorePath}) .then( function(kvs) { member = new User('admin2'); - cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: keyValStorePath})); + cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: keyValStorePath})); member.setCryptoSuite(cryptoSuite); - t.comment('Setting client keyValueStore to: ' +kvs); client.setStateStore(kvs); if (client.getStateStore() === kvs) { t.pass('Successfully set File KeyValueStore for client'); @@ -88,8 +82,6 @@ test('Use FabricCAServices with a File KeyValueStore', function(t) { t.end(); process.exit(1); } - t.comment('Initialize the CA server connection and KeyValueStore'); - t.comment('Test optional parameters passed into FabricCAServices of cryptoSettings and KVSImplClass'); return new FabricCAServices(fabricCAEndpoint, tlsOptions, ORGS[userOrg].ca.name, cryptoSuite); }, @@ -101,10 +93,8 @@ test('Use FabricCAServices with a File KeyValueStore', function(t) { }) .then( function(caService) { - logger.info('ADD: caService - ' + caService); t.pass('Successfully initialized the Fabric CA service.'); - t.comment('Begin caService.enroll'); return caService.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' @@ -135,7 +125,6 @@ test('Use FabricCAServices with a File KeyValueStore', function(t) { } else { t.fail('Member isEnrolled failed.'); } - t.comment('setting UserContext...'); return client.setUserContext(member); }, function(err) { @@ -145,12 +134,10 @@ test('Use FabricCAServices with a File KeyValueStore', function(t) { }) .then( function(user) { - t.comment('setting UserContext to different user to clear out previous user'); return client.setUserContext(new User('userx')); }) .then( function(user) { - t.comment('getUserContext, loading user admin2 from StateStore...'); client.setCryptoSuite(cryptoSuite); return client.getUserContext('admin2', true); }) diff --git a/test/integration/get-config.js b/test/integration/get-config.js index 65559689c5..ea81cd053f 100644 --- a/test/integration/get-config.js +++ b/test/integration/get-config.js @@ -18,10 +18,7 @@ // in a happy-path scenario 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('get-config'); var tape = require('tape'); @@ -32,7 +29,7 @@ var path = require('path'); var fs = require('fs'); var util = require('util'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var testUtil = require('../unit/util.js'); var Peer = require('fabric-client/lib/Peer.js'); var Orderer = require('fabric-client/lib/Orderer.js'); @@ -48,42 +45,10 @@ var _responseProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/peer var _ccProposalProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/peer/proposal.proto').protos; var _ccEventProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/peer/chaincode_event.proto').protos; -var client = new hfc(); +var client = new Client(); // IMPORTANT ------>>>>> MUST RUN e2e/create-channel.js FIRST var channel = client.newChannel(testUtil.END2END.channel); -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); - -var caRootsPath = ORGS.orderer.tls_cacerts; -let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); -let caroots = Buffer.from(data).toString(); - -channel.addOrderer( - new Orderer( - ORGS.orderer.url, - { - 'pem': caroots, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) -); - -var org = 'org1'; -var orgName = ORGS[org].name; -for (let key in ORGS[org]) { - if (ORGS[org].hasOwnProperty(key)) { - if (key.indexOf('peer') === 0) { - let data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); - let peer = new Peer( - ORGS[org][key].requests, - { - pem: Buffer.from(data).toString(), - 'ssl-target-name-override': ORGS[org][key]['server-hostname'] - }); - channel.addPeer(peer); - } - } -} +var ORGS; var the_user = null; @@ -95,21 +60,55 @@ if (process.argv.length > 2) { } logger.info('Found query: %s', querys); -testUtil.setupChaincodeDeploy(); - test(' ---->>>>> get config <<<<<-----', function(t) { - hfc.newDefaultKeyValueStore({ + testUtil.resetDefaults(); + testUtil.setupChaincodeDeploy(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + + var caRootsPath = ORGS.orderer.tls_cacerts; + let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + let caroots = Buffer.from(data).toString(); + + channel.addOrderer( + new Orderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); + + var org = 'org1'; + var orgName = ORGS[org].name; + for (let key in ORGS[org]) { + if (ORGS[org].hasOwnProperty(key)) { + if (key.indexOf('peer') === 0) { + let data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org][key]['tls_cacerts'])); + let peer = new Peer( + ORGS[org][key].requests, + { + pem: Buffer.from(data).toString(), + 'ssl-target-name-override': ORGS[org][key]['server-hostname'] + }); + channel.addPeer(peer); + } + } + } + + Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function (store) { client.setStateStore(store); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); testUtil.getSubmitter(client, t, org) .then( function(admin) { - t.pass('Successfully enrolled user ' + admin); + t.pass('Successfully enrolled user'); the_user = admin; // use default primary peer @@ -125,7 +124,7 @@ test(' ---->>>>> get config <<<<<-----', function(t) { function(result) { t.pass('channel was successfully initialized'); let orgs = channel.getOrganizations(); - logger.info(' Got the following orgs back %j', orgs); + logger.debug(' Got the following orgs back %j', orgs); t.equals(orgs.length, 3, 'Checking the that we got back the right number of orgs'); if(orgs[0].id.indexOf('Or') == 0) { t.pass('Found the org name '+ orgs[0].id); diff --git a/test/integration/grpc.js b/test/integration/grpc.js index 9811a68ab8..5350a8d219 100644 --- a/test/integration/grpc.js +++ b/test/integration/grpc.js @@ -30,7 +30,7 @@ var crypto = require('crypto'); var e2eUtils = require('./e2e/e2eUtils.js'); var testUtil = require('../unit/util.js'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var e2e = testUtil.END2END; @@ -38,16 +38,18 @@ var e2e = testUtil.END2END; * The test depends on an existing channel 'mychannel' */ test('\n\n*** GRPC communication tests ***\n\n', (t) => { + testUtil.resetDefaults(); + // test grpc message size limit - var client = new hfc(); + var client = new Client(); var channel = client.newChannel(e2e.channel); - var ORGS = hfc.getConfigSetting('test-network'); + var ORGS = Client.getConfigSetting('test-network'); var userOrg = 'org1'; var orgName = ORGS[userOrg].name; var submitter; - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); var junkpath = path.join(__dirname, '../fixtures/src/github.com/example_cc/junk.go'); @@ -85,9 +87,9 @@ test('\n\n*** GRPC communication tests ***\n\n', (t) => { }).then(() => { t.pass('Successfully tested setting grpc send limit'); - hfc.addConfigFile(path.join(__dirname, './e2e/config.json')); + Client.addConfigFile(path.join(__dirname, './e2e/config.json')); - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }); }, (err) => { @@ -100,7 +102,6 @@ test('\n\n*** GRPC communication tests ***\n\n', (t) => { }).then((admin) => { - t.comment('Successfully enrolled user \'admin\''); submitter = admin; // now dial the receive limit back down to reproduce the message size error diff --git a/test/integration/install.js b/test/integration/install.js index 4611798eda..969823d94e 100644 --- a/test/integration/install.js +++ b/test/integration/install.js @@ -18,10 +18,7 @@ // in a happy-path scenario 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('install'); var tape = require('tape'); @@ -32,20 +29,22 @@ var path = require('path'); var fs = require('fs'); var util = require('util'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var Packager = require('fabric-client/lib/Packager.js'); var testUtil = require('../unit/util.js'); var e2e = testUtil.END2END; -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); +var ORGS; var tx_id = null; var the_user = null; -testUtil.setupChaincodeDeploy(); - test('\n\n** Test chaincode install using chaincodePath to create chaincodePackage **\n\n', (t) => { + testUtil.resetDefaults(); + testUtil.setupChaincodeDeploy(); + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + var params = { org: 'org1', testDesc: 'using chaincodePath', @@ -70,18 +69,13 @@ test('\n\n** Test chaincode install using chaincodePath to create chaincodePacka t.fail('install reject: '+err); t.end(); }).catch((err) => { - t.fail('install error'); - t.comment(err.stack ? err.stack : err); + t.fail('install error. ' + err.stack ? err.stack : err); t.end(); }).then ((success) => { - t.comment('#########################################'); - t.comment('install same chaincode again, should fail'); - t.comment('#########################################'); params.channelName = params.channelName+'0'; params.testDesc = params.testDesc+'0'; installChaincode(params, t) .then((info) => { - t.comment('Checking for \'install-package.'+params.chaincodeVersion+' exists\''); if (info && info.toString().indexOf('install.'+params.chaincodeVersion+' exists') > 0) { t.pass('passed check for exists on install again'); t.end(); @@ -94,8 +88,7 @@ test('\n\n** Test chaincode install using chaincodePath to create chaincodePacka t.fail('install reject: '+err); t.end(); }).catch((err) => { - t.fail('install error'); - t.comment(err.stack ? err.stack : err); + t.fail('install error. ' + err.stack ? err.stack : err); t.end(); }); }); @@ -113,7 +106,6 @@ test('\n\n** Test chaincode install using chaincodePackage[byte] **\n\n', (t) => Packager.package(testUtil.CHAINCODE_PATH, null, false) //use good path here to get data .then((data) => { - t.comment(params.testDesc+' - Packager.package data: '+data); params.chaincodePackage = data; installChaincode(params, t) @@ -130,18 +122,13 @@ test('\n\n** Test chaincode install using chaincodePackage[byte] **\n\n', (t) => t.fail(params.testDesc+' - install reject: '+err); t.end(); }).catch((err) => { - t.fail(params.testDesc+' - install error'); - t.comment(err.stack ? err.stack : err); + t.fail(params.testDesc+' - install error. ' + err.stack ? err.stack : err); t.end(); }).then ((success) => { - t.comment('################################################'); - t.comment('install same chaincodePackage again, should fail'); - t.comment('################################################'); params.channelName = params.channelName+'0'; params.testDesc = params.testDesc+'0'; installChaincode(params, t) .then((info) => { - t.comment('Checking for \'install-package.'+params.chaincodeVersion+' exists\''); if (info && info.toString().indexOf('install-package.'+params.chaincodeVersion+' exists') > 0) { t.pass('passed check for exists same code again'); t.end(); @@ -166,7 +153,7 @@ test('\n\n** Test chaincode install using chaincodePackage[byte] **\n\n', (t) => function installChaincode(params, t) { try { var org = params.org; - var client = new hfc(); + var client = new Client(); var channel = client.newChannel(params.channelName); var caRootsPath = ORGS.orderer.tls_cacerts; @@ -202,7 +189,7 @@ function installChaincode(params, t) { } } - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then((store) => { client.setStateStore(store); @@ -246,10 +233,8 @@ function installChaincode(params, t) { all_good = all_good & one_good; } if (all_good) { - t.comment(params.testDesc+' - Successfully sent install Proposal and received ProposalResponse'); return 'success'; } else { - t.comment(params.testDesc+' - Failed to send install Proposal or receive valid response. Response null or status is not 200.'); if (error) { if (typeof error === 'Error') return new Error(error.stack ? error.stack : error); return error; @@ -258,11 +243,9 @@ function installChaincode(params, t) { } }, (err) => { - t.comment(params.testDesc+' - Error in installChaincode'); return new Error(err.stack ? err.stack : err); }); } catch (err) { - t.comment(params.testDesc+' - Error in install function'); return Promise.reject(new Error(err.stack ? err.stack : err)); }; } diff --git a/test/integration/marbles.js b/test/integration/marbles.js index f6d330ede7..6bb65d0afb 100644 --- a/test/integration/marbles.js +++ b/test/integration/marbles.js @@ -18,6 +18,13 @@ // in a happy-path scenario 'use strict'; +/////////////////////////////////////////////////////// +// +// DO NOT USE - needs to be ported to v1.0 +// +/////////////////////////////////////////////////////// + + if (global && global.hfc) global.hfc.config = undefined; require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); diff --git a/test/integration/orderer-channel-tests.js b/test/integration/orderer-channel-tests.js index 96f7c20856..1e5714de56 100644 --- a/test/integration/orderer-channel-tests.js +++ b/test/integration/orderer-channel-tests.js @@ -15,10 +15,7 @@ */ 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); -utils.setConfigSetting('hfc-logging', '{"debug":"console"}'); var logger = utils.getLogger('orderer-channel'); @@ -32,15 +29,15 @@ var path = require('path'); var testUtil = require('../unit/util.js'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var Orderer = require('fabric-client/lib/Orderer.js'); var Channel = require('fabric-client/lib/Channel.js'); var keyValStorePath = testUtil.KVS; -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); +var ORGS; -var client = new hfc(); +var client = new Client(); +var org = 'org1'; // // Orderer via member missing orderer @@ -52,18 +49,24 @@ var client = new hfc(); test('\n\n** TEST ** orderer via member missing orderer', function(t) { testUtil.resetDefaults(); utils.setConfigSetting('key-value-store', 'fabric-ca-client/lib/impl/FileKeyValueStore.js');//force for 'gulp test' + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + let orgName = ORGS[org].name; + // // Create and configure the test channel // - var channel = client.newChannel('testChannel-orderer-member2'); + let channel = client.newChannel('testChannel-orderer-member2'); + let cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + client.setCryptoSuite(cryptoSuite); - hfc.newDefaultKeyValueStore({ + Client.newDefaultKeyValueStore({ path: testUtil.KVS }).then((store) => { client.setStateStore(store); - return testUtil.getSubmitter(client, t); - } - ).then( + return testUtil.getSubmitter(client, t, org); + }).then( function(admin) { t.pass('Successfully enrolled user \'admin\''); @@ -122,7 +125,7 @@ test('\n\n** TEST ** orderer via member null data', function(t) { ) ); - testUtil.getSubmitter(client, t) + testUtil.getSubmitter(client, t, org) .then( function(admin) { t.pass('Successfully enrolled user \'admin\''); @@ -197,7 +200,7 @@ test('\n\n** TEST ** orderer via member bad request', function(t) { ) ); - testUtil.getSubmitter(client, t) + testUtil.getSubmitter(client, t, org) .then( function(admin) { t.pass('Successfully enrolled user \'admin\''); diff --git a/test/integration/query.js b/test/integration/query.js index d05a4a7c94..ff77e9d04b 100644 --- a/test/integration/query.js +++ b/test/integration/query.js @@ -35,20 +35,19 @@ var util = require('util'); var fs = require('fs'); var testUtil = require('../unit/util.js'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var Peer = require('fabric-client/lib/Peer.js'); var Orderer = require('fabric-client/lib/Orderer.js'); -var client = new hfc(); +var client = new Client(); var channel_id = testUtil.END2END.channel; var channel = client.newChannel(channel_id); -hfc.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); -var ORGS = hfc.getConfigSetting('test-network'); var org = 'org1'; -var orgName = ORGS[org].name; +var orgName; var e2e = testUtil.END2END; +var ORGS, peer0; var the_user = null; var tx_id = null; @@ -59,7 +58,7 @@ if (process.argv.length > 2) { querys.push(process.argv[i]); } } -logger.info('Found query: %s', querys); +logger.debug('Found query: %s', querys); // Second test in query.js has optional parameters; have they been specified? var queryParameters = false; // false = do all queries; true = do some queries @@ -76,46 +75,51 @@ if (querys.length > 0 ) { } } -testUtil.setupChaincodeDeploy(); +var data; -var caRootsPath = ORGS.orderer.tls_cacerts; -let data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); -let caroots = Buffer.from(data).toString(); +test(' ---->>>>> Query channel working <<<<<-----', function(t) { + Client.addConfigFile(path.join(__dirname, 'e2e', 'config.json')); + ORGS = Client.getConfigSetting('test-network'); + orgName = ORGS[org].name; + var caRootsPath = ORGS.orderer.tls_cacerts; + data = fs.readFileSync(path.join(__dirname, 'e2e', caRootsPath)); + + let caroots = Buffer.from(data).toString(); + + channel.addOrderer( + new Orderer( + ORGS.orderer.url, + { + 'pem': caroots, + 'ssl-target-name-override': ORGS.orderer['server-hostname'] + } + ) + ); -channel.addOrderer( - new Orderer( - ORGS.orderer.url, + data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org].peer1['tls_cacerts'])); + peer0 = new Peer( + ORGS[org].peer1.requests, { - 'pem': caroots, - 'ssl-target-name-override': ORGS.orderer['server-hostname'] - } - ) -); -data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS[org].peer1['tls_cacerts'])); -var peer0 = new Peer( - ORGS[org].peer1.requests, - { - pem: Buffer.from(data).toString(), - 'ssl-target-name-override': ORGS[org].peer1['server-hostname'] - }); -data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS['org2'].peer1['tls_cacerts'])); -var peer1 = new Peer( - ORGS['org2'].peer1.requests, - { - pem: Buffer.from(data).toString(), - 'ssl-target-name-override': ORGS['org2'].peer1['server-hostname'] - }); + pem: Buffer.from(data).toString(), + 'ssl-target-name-override': ORGS[org].peer1['server-hostname'] + }); + data = fs.readFileSync(path.join(__dirname, 'e2e', ORGS['org2'].peer1['tls_cacerts'])); + var peer1 = new Peer( + ORGS['org2'].peer1.requests, + { + pem: Buffer.from(data).toString(), + 'ssl-target-name-override': ORGS['org2'].peer1['server-hostname'] + }); -channel.addPeer(peer0); -channel.addPeer(peer1); + channel.addPeer(peer0); + channel.addPeer(peer1); -test(' ---->>>>> Query channel working <<<<<-----', function(t) { utils.setConfigSetting('key-value-store','fabric-client/lib/impl/FileKeyValueStore.js'); - var cryptoSuite = client.newCryptoSuite(); - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); + var cryptoSuite = Client.newCryptoSuite(); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(orgName)})); client.setCryptoSuite(cryptoSuite); - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function (store) { client.setStateStore(store); @@ -134,25 +138,22 @@ test(' ---->>>>> Query channel working <<<<<-----', function(t) { // send query return channel.queryBlock(0); }).then((block) => { - logger.info(' Channel getBlock() returned block %j',block); - logger.info(' Channel getBlock() returned block number=%s',block.header.number); + logger.debug(' Channel getBlock() returned block number=%s',block.header.number); t.equal(block.header.number.toString(),'0','checking query results are correct that we got zero block back'); t.equal(block.data.data[0].payload.data.config.channel_group.groups.Orderer.groups.OrdererMSP.values.MSP.value.config.name,'OrdererMSP','checking query results are correct that we got the correct orderer MSP name'); t.equal(block.data.data[0].payload.data.config.channel_group.groups.Application.groups.Org2MSP.policies.Writers.policy.type,'SIGNATURE','checking query results are correct that we got the correct policy type'); t.equal(block.data.data[0].payload.data.config.channel_group.groups.Application.policies.Writers.policy.policy.rule,'ANY','checking query results are correct that we got the correct policy rule'); t.equal(block.data.data[0].payload.data.config.channel_group.policies.Admins.mod_policy,'Admins','checking query results are correct that we got the correct mod policy name'); - logger.info('%j',block); return channel.queryBlock(1); }).then((block) => { - logger.info(' Channel getBlock() returned block number=%s',block.header.number); + logger.debug(' Channel getBlock() returned block number=%s',block.header.number); t.equal(block.header.number.toString(),'1','checking query results are correct that we got a transaction block back'); t.equal(block.data.data[0].payload.data.actions[0].payload.action.endorsements[0].endorser.Mspid,'Org1MSP','checking query results are correct that we got a transaction block back with correct endorsement MSP id'); - logger.info('%j',block); tx_id = utils.getConfigSetting('E2E_TX_ID', 'notfound'); - logger.info('getConfigSetting("E2E_TX_ID") = %s', tx_id); + logger.debug('getConfigSetting("E2E_TX_ID") = %s', tx_id); if (tx_id === 'notfound') { - t.comment(' Did you set the E2E_TX_ID environment variable after running invoke-transaction.js ?'); + logger.error(' Did you set the E2E_TX_ID environment variable after running invoke-transaction.js ?'); throw new Error('Could not get tx_id from ConfigSetting "E2E_TX_ID"'); } else { t.pass('Got tx_id from ConfigSetting "E2E_TX_ID"'); @@ -160,7 +161,6 @@ test(' ---->>>>> Query channel working <<<<<-----', function(t) { return channel.queryTransaction(tx_id, peer0); //assumes the end-to-end has run first } }).then((processed_transaction) => { - logger.info(' processed_transaction :: %j',processed_transaction); t.equals('mychannel', processed_transaction.transactionEnvelope.payload.header.channel_header.channel_id, 'test for header channel name'); t.equals('Org2MSP', processed_transaction.transactionEnvelope.payload.header.signature_header.creator.Mspid, @@ -191,27 +191,25 @@ test(' ---->>>>> Query channel working <<<<<-----', function(t) { return channel.queryInfo(peer0); }).then((blockchainInfo) => { t.pass('got back blockchain info '); - logger.info(' Channel queryInfo() returned block height='+blockchainInfo.height); - logger.info(' Channel queryInfo() returned block previousBlockHash='+blockchainInfo.previousBlockHash); - logger.info(' Channel queryInfo() returned block currentBlockHash='+blockchainInfo.currentBlockHash); + logger.debug(' Channel queryInfo() returned block height='+blockchainInfo.height); + logger.debug(' Channel queryInfo() returned block previousBlockHash='+blockchainInfo.previousBlockHash); + logger.debug(' Channel queryInfo() returned block currentBlockHash='+blockchainInfo.currentBlockHash); var block_hash = blockchainInfo.currentBlockHash; // send query return channel.queryBlockByHash(block_hash, peer0); }).then((block) => { - logger.info(' Channel queryBlockByHash() returned block number=%s',block.header.number); + logger.debug(' Channel queryBlockByHash() returned block number=%s',block.header.number); t.pass('got back block number '+ block.header.number); t.end(); }).catch((err) => { - t.comment('Failed \'Query channel working\' with error:'); throw new Error(err.stack ? err.stack : err); }); }); test(' ---->>>>> Query channel failing: GetBlockByNumber <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetBlockByNumber') >= 0) { - logger.info('Executing GetBlockByNumber'); - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function(store) { @@ -249,7 +247,7 @@ test(' ---->>>>> Query channel failing: GetBlockByNumber <<<<<-----', function( test(' ---->>>>> Query channel failing: GetTransactionByID <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetTransactionByID') >= 0) { - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function(store) { @@ -288,7 +286,7 @@ test(' ---->>>>> Query channel failing: GetTransactionByID <<<<<-----', functio test(' ---->>>>> Query channel failing: GetChannelInfo <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetChannelInfo') >= 0) { - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function(store) { @@ -327,7 +325,7 @@ test(' ---->>>>> Query channel failing: GetChannelInfo <<<<<-----', function(t) test(' ---->>>>> Query channel failing: GetBlockByHash <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetBlockByHash') >= 0) { - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function (store) { @@ -366,7 +364,7 @@ test(' ---->>>>> Query channel failing: GetBlockByHash <<<<<-----', function(t) test(' ---->>>>> Query Installed Chaincodes working <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetInstalledChaincodes') >= 0) { - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function (store) { client.setStateStore(store); @@ -385,11 +383,11 @@ test(' ---->>>>> Query Installed Chaincodes working <<<<<-----', function(t) { } ).then( function(response) { - t.comment('<<< installed chaincodes >>>'); + logger.debug('<<< installed chaincodes >>>'); let found = false; for (let i=0; i>>>> Query Installed Chaincodes working <<<<<-----', function(t) { test(' ---->>>>> Query Instantiated Chaincodes working <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetInstantiatedChaincodes') >= 0) { - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function (store) { client.setStateStore(store); @@ -441,10 +439,10 @@ test(' ---->>>>> Query Instantiated Chaincodes working <<<<<-----', function(t) } ).then( function(response) { - t.comment('<<< instantiated chaincodes >>>'); + logger.debug('<<< instantiated chaincodes >>>'); let found = false; for (let i=0; i>>>> Query Instantiated Chaincodes working <<<<<-----', function(t) test(' ---->>>>> Query Channels working <<<<<-----', function(t) { if (!queryParameters || querys.indexOf('GetChannels') >= 0) { - return hfc.newDefaultKeyValueStore({ + return Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }).then( function (store) { client.setStateStore(store); @@ -497,9 +495,9 @@ test(' ---->>>>> Query Channels working <<<<<-----', function(t) { } ).then( function(response) { - t.comment('<<< channels >>>'); + logger.debug('<<< channels >>>'); for (let i=0; i { + testUtil.resetDefaults(); var e2e = testUtil.END2END; - hfc.addConfigFile(path.join(__dirname, './e2e/config.json')); - var ORGS = hfc.getConfigSetting('test-network'); + Client.addConfigFile(path.join(__dirname, './e2e/config.json')); + var ORGS = Client.getConfigSetting('test-network'); var caRootsPath = ORGS.orderer.tls_cacerts; let data = fs.readFileSync(path.join(__dirname, '/test', caRootsPath)); @@ -50,7 +50,7 @@ test('\n\n **** E R R O R T E S T I N G on upgrade call', (t) => { var version = 'v1'; var org = 'org1'; - var client = new hfc(); + var client = new Client(); var channel = client.newChannel(e2e.channel); var orgName = ORGS[org].name; channel.addOrderer( @@ -81,7 +81,7 @@ test('\n\n **** E R R O R T E S T I N G on upgrade call', (t) => { } } - hfc.newDefaultKeyValueStore({ + Client.newDefaultKeyValueStore({ path: testUtil.storePathForOrg(orgName) }) .then((store) => { diff --git a/test/unit/block.js b/test/unit/block.js index 6337e416ad..47d8444834 100644 --- a/test/unit/block.js +++ b/test/unit/block.js @@ -22,7 +22,6 @@ var test = _test(tape); var fs = require('fs'); var path = require('path'); -var intercept = require('intercept-stdout'); var grpc = require('grpc'); var configtxProto = grpc.load(path.join(__dirname, '../../fabric-client/lib/protos/common/configtx.proto')).common; @@ -52,14 +51,6 @@ test('\n\n*** BlockDecoder.js tests ***\n\n', (t) => { 'IMPLICIT_META', 'Test parsing of channel\'s Writers policy is of IMPLICIT_META type'); - // test that the SDK spits out a warning of the "MSP" policy type - // during decode because it's not supported in v1.0 yet - var output = ''; - - let unhook = intercept(function (txt) { - output += txt; - }); - var decodeConfigPolicy = BlockDecoder.__get__('decodeConfigPolicy'); var mockPolicy = new policiesProto.Policy(); mockPolicy.setType(policiesProto.Policy.PolicyType.SIGNATURE); @@ -74,14 +65,6 @@ test('\n\n*** BlockDecoder.js tests ***\n\n', (t) => { } }); - unhook(); - - if (output.indexOf('warn') >= 0 && output.indexOf('[BlockDecoder.js]: decodeConfigPolicy - found a PolicyType of MSP') >= 0) { - t.pass('Successfully tested warn logging message about using the "MSP" policy type'); - } else { - t.fail('Failed to warn logging message about using the "MSP" policy type'); - } - var mockPolicy = new policiesProto.Policy(); mockPolicy.setType(policiesProto.Policy.PolicyType.SIGNATURE); t.throws( diff --git a/test/unit/channel.js b/test/unit/channel.js index 71f77e0596..1d7d8b193b 100644 --- a/test/unit/channel.js +++ b/test/unit/channel.js @@ -28,7 +28,7 @@ var grpc = require('grpc'); var _policiesProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/policies.proto').common; var _mspPrProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/msp/msp_principal.proto').common; -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var testutil = require('./util.js'); var Peer = require('fabric-client/lib/Peer.js'); var Channel = require('fabric-client/lib/Channel.js'); @@ -42,15 +42,15 @@ var SigningIdentity = idModule.SigningIdentity; var _channel = null; var channelName = 'testChannel'; -var Client = hfc; var client = new Client(); -testutil.resetDefaults(); var utils = require('fabric-client/lib/utils.js'); var logger = utils.getLogger('channel'); // Channel tests ///////////// test('\n\n ** Channel - constructor test **\n\n', function (t) { + testutil.resetDefaults(); + _channel = new Channel(channelName, client); if (_channel.getName() === channelName) t.pass('Channel constructor test: getName successful'); @@ -828,7 +828,7 @@ test('\n\n ** Channel queryByChaincode() tests **\n\n', function (t) { // do some setup for following test utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); - hfc.newDefaultKeyValueStore({ + Client.newDefaultKeyValueStore({ path: testutil.KVS }).then ( function (store) { client.setStateStore(store); @@ -1004,7 +1004,7 @@ test('\n\n** TEST ** orderer via channel setOrderer/getOrderer', function(t) { // Create and configure the test channel // utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); - hfc.newDefaultKeyValueStore({ + Client.newDefaultKeyValueStore({ path: testutil.KVS }) .then ( function (store) { diff --git a/test/unit/client.js b/test/unit/client.js index 8fc140157a..423177f600 100644 --- a/test/unit/client.js +++ b/test/unit/client.js @@ -16,8 +16,6 @@ 'use strict'; -if (global && global.hfc) global.hfc.config = undefined; -require('nconf').reset(); var utils = require('fabric-client/lib/utils.js'); var logger = utils.getLogger('unit.client'); @@ -27,7 +25,7 @@ var test = _test(tape); var path = require('path'); var util = require('util'); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var utils = require('fabric-client/lib/utils.js'); var User = require('fabric-client/lib/User.js'); var testutil = require('./util.js'); @@ -35,22 +33,24 @@ var testutil = require('./util.js'); var caImport; test('\n\n ** index.js **\n\n', function (t) { - t.equals(typeof hfc, 'function'); + testutil.resetDefaults(); + + t.equals(typeof Client, 'function'); t.doesNotThrow( function() { - var c = new hfc(); + var c = new Client(); }, null, - 'Should be able to instantiate a new instance of "hfc" require'); + 'Should be able to instantiate a new instance of "Client" require'); t.doesNotThrow( function() { - var c = new hfc(); + var c = new Client(); var channel = c.newChannel('test'); }, null, - 'Should be able to call "newChannel" on the new instance of "hfc"'); + 'Should be able to call "newChannel" on the new instance of "Client"'); t.end(); }); @@ -58,7 +58,7 @@ test('\n\n ** index.js **\n\n', function (t) { test('\n\n ** eventhub **\n\n', function (t) { t.doesNotThrow( function() { - var c = new hfc(); + var c = new Client(); c._userContext = new User('name'); var event_hub = c.newEventHub(); }, @@ -68,7 +68,6 @@ test('\n\n ** eventhub **\n\n', function (t) { t.end(); }); -var Client = hfc; var client = new Client(); var channelKeyValStorePath = path.join(testutil.getTempDir(), 'channelKeyValStorePath'); var testKey = 'keyValFileStoreName'; @@ -77,7 +76,8 @@ var testValue = 'secretKeyValue'; test('\n\n ** Client.js Tests: CryptoSuite() methods **\n\n', function (t) { t.equals(client.getCryptoSuite(), null, 'Should return null when CryptoSuite has not been set'); - var crypto = client.newCryptoSuite(); + var crypto = Client.newCryptoSuite(); + client.setCryptoSuite(crypto); if (crypto) { t.pass('Successfully called newCryptoSuite()'); } @@ -270,7 +270,7 @@ test('\n\n ** Client.js Tests: user persistence and loading **\n\n', function (t }); test('\n\n ** testing devmode set and get calls on client **\n\n', function (t) { - t.equals(typeof hfc, 'function'); + t.equals(typeof Client, 'function'); var client = new Client(); t.doesNotThrow( function () { @@ -284,7 +284,7 @@ test('\n\n ** testing devmode set and get calls on client **\n\n', function (t) }); test('\n\n ** testing query calls fail without correct parameters on client **\n\n', function (t) { - t.equals(typeof hfc, 'function'); + t.equals(typeof Client, 'function'); var client = new Client(); var p1 = client.queryInstalledChaincodes().then(function () { @@ -322,7 +322,7 @@ test('\n\n ** testing query calls fail without correct parameters on client **\n }); test('\n\n ** testing get and new peer calls on client **\n\n', function (t) { - t.equals(typeof hfc, 'function'); + t.equals(typeof Client, 'function'); var client = new Client(); t.doesNotThrow( @@ -336,7 +336,7 @@ test('\n\n ** testing get and new peer calls on client **\n\n', function (t) { }); test('\n\n ** testing get and new orderer calls on client **\n\n', function (t) { - t.equals(typeof hfc, 'function'); + t.equals(typeof Client, 'function'); var client = new Client(); t.doesNotThrow( @@ -350,7 +350,7 @@ test('\n\n ** testing get and new orderer calls on client **\n\n', function (t) }); test('\n\n ** testing get transaction ID call on client **\n\n', function (t) { - t.equals(typeof hfc, 'function'); + t.equals(typeof Client, 'function'); var client = new Client(); t.throws(function() { @@ -373,16 +373,18 @@ test('\n\n ** Config **\n\n', function (t) { process.env.TEST_3 = 'env'; process.env.test_6 = 'mapped'; // internal call. clearing the cached config. - global.hfc.config = undefined; - t.equals(hfc.getConfigSetting('request-timeout', 'notfound'), 45000, 'checking that able to get "request-timeout" value from an additional configuration file'); + if (global && global.hfc) global.hfc.config = undefined; + require('nconf').reset(); + + t.equals(Client.getConfigSetting('request-timeout', 'notfound'), 45000, 'checking that able to get "request-timeout" value from an additional configuration file'); //try adding another config file - hfc.addConfigFile(path.join(__dirname, '../fixtures/local.json')); - t.equals(hfc.getConfigSetting('test-2', 'notfound'), 'local', 'checking that able to test-2 value from an additional configuration file'); - t.equals(hfc.getConfigSetting('test-3', 'notfound'), 'env', 'checking that test-3 environment values are used'); - t.equals(hfc.getConfigSetting('test-4', 'notfound'), 'argv', 'checking that test-4 argument values are used'); - hfc.setConfigSetting('test-5', 'program'); - t.equals(hfc.getConfigSetting('test-5', 'notfound'), 'program', 'checking that test-5 program values are used'); - t.equals(hfc.getConfigSetting('test-6', 'notfound'), 'mapped', 'checking that test-6 is enviroment mapped value'); + Client.addConfigFile(path.join(__dirname, '../fixtures/local.json')); + t.equals(Client.getConfigSetting('test-2', 'notfound'), 'local', 'checking that able to test-2 value from an additional configuration file'); + t.equals(Client.getConfigSetting('test-3', 'notfound'), 'env', 'checking that test-3 environment values are used'); + t.equals(Client.getConfigSetting('test-4', 'notfound'), 'argv', 'checking that test-4 argument values are used'); + Client.setConfigSetting('test-5', 'program'); + t.equals(Client.getConfigSetting('test-5', 'notfound'), 'program', 'checking that test-5 program values are used'); + t.equals(Client.getConfigSetting('test-6', 'notfound'), 'mapped', 'checking that test-6 is enviroment mapped value'); t.end(); }); @@ -575,7 +577,7 @@ test('\n\n ** Client createChannel() tests **\n\n', function (t) { }); test('\n\n ** createUser error path - missing required opt parameter **\n\n', function (t) { - hfc.addConfigFile(path.join(__dirname, '../fixtures/caimport.json')); + Client.addConfigFile(path.join(__dirname, '../fixtures/caimport.json')); caImport = utils.getConfigSetting('ca-import', 'notfound'); logger.debug('caImport = %s', JSON.stringify(caImport)); @@ -859,7 +861,7 @@ test('\n\n ** createUser error path - no keyValueStore **\n\n', function (t) { utils.setConfigSetting('crypto-keysize', 256); var client = new Client(); - var cryptoSuite = client.newCryptoSuite(); + var cryptoSuite = Client.newCryptoSuite(); client.createUser( {username: caImport.orgs[userOrg].username, @@ -897,7 +899,7 @@ test('\n\n ** createUser success path - no cryptoKeyStore **\n\n', function (t) var keyStoreOpts = {path: path.join(testutil.getTempDir(), caImport.orgs[userOrg].storePath)}; var client = new Client(); - var cryptoSuite = client.newCryptoSuite(); + var cryptoSuite = Client.newCryptoSuite(); return utils.newKeyValueStore(keyStoreOpts) .then((store) => { diff --git a/test/unit/crypto-key-store.js b/test/unit/crypto-key-store.js index 3c0ba72aa5..819e580624 100644 --- a/test/unit/crypto-key-store.js +++ b/test/unit/crypto-key-store.js @@ -34,8 +34,6 @@ var KEYUTIL = jsrsa.KEYUTIL; var CouchdbMock = require('mock-couch'); var nano = require('nano'); -testutil.resetDefaults(); - var ecdsaKey = require('fabric-client/lib/impl/ecdsa/key.js'); var CKS = require('fabric-client/lib/impl/CryptoKeyStore.js'); var CouchDBKeyValueStore = require('fabric-client/lib/impl/CouchDBKeyValueStore.js'); @@ -69,6 +67,8 @@ var f2 = KEYUTIL.getKey(TEST_KEY_PRIVATE_CERT_PEM); var testPubKey = new ecdsaKey(f2); test('\n\n** CryptoKeyStore tests **\n\n', function(t) { + testutil.resetDefaults(); + var keystorePath = path.join(testutil.getTempDir(), 'crypto-key-store'); t.throws( diff --git a/test/unit/cryptosuite-ecdsa-aes.js b/test/unit/cryptosuite-ecdsa-aes.js index a3b5679ec6..003ad48d26 100644 --- a/test/unit/cryptosuite-ecdsa-aes.js +++ b/test/unit/cryptosuite-ecdsa-aes.js @@ -20,7 +20,7 @@ var tape = require('tape'); var _test = require('tape-promise'); var test = _test(tape); -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var testutil = require('./util.js'); var utils = require('fabric-client/lib/utils.js'); var path = require('path'); @@ -130,7 +130,7 @@ const halfOrdersForCurve = { 'secp384r1': elliptic.curves['p384'].n.shrn(1) }; -var _client = new hfc(); +var _client = new Client(); test('\n\n** utils.newCryptoSuite tests **\n\n', (t) => { testutil.resetDefaults(); @@ -477,7 +477,7 @@ test('\n\n ** CryptoSuite_ECDSA_AES - function tests **\n\n', function (t) { t.pass('Successfully caught missing private key expected from a user enrollment object'); t.end(); } else { - t.fail('Unexpected message. Expecting "'+msg+'"'); + t.fail(util.format('Unexpected message. Expecting "%s" but got "%s"', msg, err)); t.end(); } }).catch((err) => { diff --git a/test/unit/ecdsa-key.js b/test/unit/ecdsa-key.js index c2117ce6d8..3875b8c5ff 100644 --- a/test/unit/ecdsa-key.js +++ b/test/unit/ecdsa-key.js @@ -28,9 +28,9 @@ var jsrsa = require('jsrsasign'); var KEYUTIL = jsrsa.KEYUTIL; var asn1 = jsrsa.asn1; -testutil.resetDefaults(); - test('\n\n ** ECDSA Key Impl tests **\n\n', function (t) { + testutil.resetDefaults(); + t.throws( function () { var k = new ecdsaKey(); diff --git a/test/unit/event-hub.js b/test/unit/event-hub.js index e2fa62bd15..039e094598 100644 --- a/test/unit/event-hub.js +++ b/test/unit/event-hub.js @@ -22,11 +22,11 @@ var test = _test(tape); var testutil = require('./util.js'); -testutil.resetDefaults(); - var EventHub = require('fabric-client/lib/EventHub.js'); test('\n\n** EventHub tests\n\n', (t) => { + testutil.resetDefaults(); + var eh; t.throws( diff --git a/test/unit/fabric-ca-client.js b/test/unit/fabric-ca-client.js index 95532a5c8e..c6593a8776 100644 --- a/test/unit/fabric-ca-client.js +++ b/test/unit/fabric-ca-client.js @@ -26,8 +26,6 @@ var fs = require('fs'); var path = require('path'); var util = require('util'); -testutil.resetDefaults(); - var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl'); var FabricCAClient = FabricCAServices.FabricCAClient; @@ -47,6 +45,7 @@ const SAMPLE_PEM_ENCODED_CERTIFICATE = '-----BEGIN CERTIFICATE-----' + */ //test constructor test('FabricCAClient: Test constructor', function (t) { + testutil.resetDefaults(); var connectOpts = {}; @@ -136,7 +135,6 @@ test('FabricCAClient: Test constructor', function (t) { t.doesNotThrow( function () { client = new FabricCAClient(connectOpts); - t.comment('client: ' + util.inspect(client, {depth: null})); }, /Invalid connection options. /, 'Add tlsOptions to client connect_opts -- all default values' @@ -153,7 +151,6 @@ test('FabricCAClient: Test constructor', function (t) { t.doesNotThrow( function () { client = new FabricCAClient(connectOpts); - t.comment('client: ' + util.inspect(client, {depth: null})); }, /Invalid connection options. /, 'Add tlsOptions to client connect_opts -- non default values' @@ -222,14 +219,15 @@ test('FabricCAServices: Test newCryptoSuite() function', function(t) { var crypto = CAClient.newCryptoSuite({software: true, keysize: 384}); var client = new CAClient('http://localhost:7054', tlsOptions, 'peerOrg1', crypto); + client.setCryptoSuite(crypto); - var crypto = client.getCrypto(); + var crypto = client.getCryptoSuite(); if (crypto) { - t.pass('Successfully called getCrypto()'); + t.pass('Successfully called getCryptoSuite()'); } else { - t.fail('getCrypto() did not return an object'); + t.fail('getCryptoSuite() did not return an object'); } t.end(); }); @@ -254,32 +252,33 @@ test('FabricCAServices: Test newCryptoKeyStore() function', function(t) { crypto.setCryptoKeyStore(cks); var client = new CAClient('http://localhost:7054', tlsOptions, 'peerOrg1', crypto); + client.setCryptoSuite(crypto); - var crypto = client.getCrypto(); + var crypto = client.getCryptoSuite(); if (crypto && crypto._cryptoKeyStore) { - t.pass('Successfully called getCrypto() with cryptoKeyStore set'); + t.pass('Successfully called getCryptoSuite() with cryptoKeyStore set'); } else { if (!crypto) { - t.fail('getCrypto() did not return an object'); + t.fail('getCryptoSuite() did not return an object'); } else { - t.fail('getCrypto() should contain a cryptoKeyStore'); + t.fail('getCryptoSuite() should contain a cryptoKeyStore'); } } t.end(); }); -// Test getCrypto() function -test('FabricCAServices: Test getCrypto() function', function(t) { +// Test getCryptoSuite() function +test('FabricCAServices: Test getCryptoSuite() function', function(t) { var ca = new FabricCAServices('http://localhost:7054'); - var crypto = ca.getCrypto(); + var crypto = ca.getCryptoSuite(); if (crypto) { t.pass('Successfully called getCrypto()'); } else { - t.fail('getCrypto() did not return an object'); + t.fail('getCryptoSuite() did not return an object'); } t.end(); }); @@ -688,7 +687,6 @@ test('FabricCAServices: Test toString() function', function(t) { var ca = new FabricCAServices('http://localhost:7054'); var printableCa = ca.toString(); - t.comment('printableCa = ' + printableCa); if ((typeof printableCa == 'string') && (printableCa.length > 1)) { t.pass('toString() returned a string of length ' + printableCa.length); } diff --git a/test/unit/file-key-value-store.js b/test/unit/file-key-value-store.js index 8f4be5478d..883e14c43b 100644 --- a/test/unit/file-key-value-store.js +++ b/test/unit/file-key-value-store.js @@ -28,7 +28,6 @@ var fs = require('fs-extra'); var utils = require('fabric-client/lib/utils.js'); var FileKeyValueStore = require('fabric-client/lib/impl/FileKeyValueStore.js'); -testUtil.resetDefaults(); var keyValStorePath = path.join(testUtil.getTempDir(), 'kvsTemp'); var testKey = 'keyValFileStoreName'; @@ -36,6 +35,8 @@ var testValue = 'secretKeyValue'; var store1 = ''; test('\n\n ** FileKeyValueStore - read and write test **\n\n', function (t) { + testUtil.resetDefaults(); + // clean up if (testUtil.existsSync(keyValStorePath)) { fs.removeSync(keyValStorePath); diff --git a/test/unit/identity.js b/test/unit/identity.js index a3ea0f141d..69b53e83ef 100644 --- a/test/unit/identity.js +++ b/test/unit/identity.js @@ -26,8 +26,6 @@ var api = require('fabric-client/lib/api.js'); var fs = require('fs'); var path = require('path'); -testutil.resetDefaults(); - var jsrsa = require('jsrsasign'); var KEYUTIL = jsrsa.KEYUTIL; var idModule = require('fabric-client/lib/msp/identity.js'); @@ -81,6 +79,8 @@ var TEST_KEY_PRIVATE_CERT_PEM = '-----BEGIN CERTIFICATE-----' + '-----END CERTIFICATE-----'; test('\n\n ** Identity class tests **\n\n', function (t) { + testutil.resetDefaults(); + t.throws( function() { new Identity(); diff --git a/test/unit/logger.js b/test/unit/logger.js index 5c53be1c61..9892354128 100644 --- a/test/unit/logger.js +++ b/test/unit/logger.js @@ -24,8 +24,6 @@ var hfc = require('fabric-client'); var testutil = require('./util.js'); var utils = require('fabric-client/lib/utils.js'); -testutil.resetDefaults(); - var bunyan = require('bunyan'); var log4js = require('log4js'); var intercept = require('intercept-stdout'); @@ -63,8 +61,15 @@ function testLogger(t, ignoreLevels) { } test('\n\n ** Logging utility tests - built-in logger **\n\n', function (t) { - // test 1: default logging levels for console logging - testLogger(t); + if (!!process.env.HFC_LOGGING) { + delete process.env['HFC_LOGGING']; + } + + if (!!global.hfc.logger) { + global.hfc.logger = undefined; + } + + testutil.resetDefaults(); // test 2: custom logging levels for console logging var output = ''; diff --git a/test/unit/msp.js b/test/unit/msp.js index f267e7394c..436372db0d 100644 --- a/test/unit/msp.js +++ b/test/unit/msp.js @@ -55,6 +55,8 @@ const TEST_CERT_PEM = '-----BEGIN CERTIFICATE-----' + '-----END CERTIFICATE-----'; test('\n\n** MSP Tests **\n\n', (t) => { + testutil.resetDefaults(); + // construct MSP config objects for org0 and org1 var configs = []; var mspm = new MSPM(); diff --git a/test/unit/orderer.js b/test/unit/orderer.js index fbba516e54..d2bce3309c 100644 --- a/test/unit/orderer.js +++ b/test/unit/orderer.js @@ -42,12 +42,13 @@ var keyValStorePath = testUtil.KVS; // test('orderer bad address test', function(t) { + testUtil.resetDefaults(); + try { var client = new Orderer('xxxxx'); t.fail('Orderer allowed setting a bad URL.'); } catch(err) { - console.log('Caught Error: ' + err); t.pass('Orderer did not allow setting bad URL.'); } t.end(); @@ -66,7 +67,6 @@ test('orderer missing address test', function(t) { t.fail('Orderer allowed setting a missing address.'); } catch(err) { - console.log('Caught Error: ' + err); t.pass('Orderer did not allow setting a missing address.'); } t.end(); @@ -85,12 +85,10 @@ test('orderer missing data test', function(t) { client.sendBroadcast() .then( function(status) { - console.log('response status: ' + JSON.stringify(status)); t.fail('Should have noticed missing data.'); t.end(); }, function(err) { - console.log('Caught Error: ' + err); t.pass('Successfully found missing data: ' + err); t.end(); } @@ -113,7 +111,6 @@ test('orderer unknown address test', function(t) { client.sendBroadcast('some data') .then( function(status) { - console.log('response status: ' + JSON.stringify(status)); t.fail('Should have noticed a bad address.'); t.end(); }, diff --git a/test/unit/peer.js b/test/unit/peer.js index 4005233cc5..7be0b0bc1d 100644 --- a/test/unit/peer.js +++ b/test/unit/peer.js @@ -40,12 +40,13 @@ var Peer = require('fabric-client/lib/Peer.js'); // test('Peer bad address test', function(t) { + testUtil.resetDefaults(); + try { var client = new Peer('xxxxx'); t.fail('Peer allowed setting a bad URL.'); } catch(err) { - console.log('Caught Error: ' + err); t.pass('peer did not allow setting bad URL.'); } t.end(); @@ -64,7 +65,6 @@ test('Peer missing address test', function(t) { t.fail('Peer allowed setting a missing address.'); } catch(err) { - console.log('Caught Error: ' + err); t.pass('Peer did not allow setting a missing address.'); } t.end(); @@ -83,12 +83,10 @@ test('Peer missing data test', function(t) { client.sendProposal() .then( function(status) { - console.log('response status: ' + JSON.stringify(status)); t.fail('Should have noticed missing data.'); t.end(); }, function(err) { - console.log('Caught Error: ' + err); t.pass('Successfully found missing data: ' + err); t.end(); } @@ -111,7 +109,6 @@ test('Peer unknown address test', function(t) { client.sendProposal('some data') .then( function(status) { - console.log('response status: ' + JSON.stringify(status)); t.fail('Should have noticed a bad address.'); t.end(); }, @@ -142,7 +139,6 @@ test('Peer timeout test', function(t) { client.sendProposal('some data') .then( function(status) { - console.log('response status: ' + JSON.stringify(status)); t.fail('Should have noticed a timeout.'); t.end(); }, diff --git a/test/unit/pkcs11.js b/test/unit/pkcs11.js index 125d0576d3..5bb48b61ad 100644 --- a/test/unit/pkcs11.js +++ b/test/unit/pkcs11.js @@ -34,6 +34,7 @@ var util = require('util'); var path = require('path'); var utils = require('fabric-client/lib/utils.js'); +var testutil = require('./util.js'); var libpath; var pin = '98765432'; // user pin not SO pin @@ -52,6 +53,7 @@ var common_pkcs_pathnames = [ ]; test('\n\n**PKCS11 - locate PKCS11 libpath\n\n', (t) => { + testutil.resetDefaults(); if (typeof process.env.PKCS11_LIB === 'string' && process.env.PKCS11_LIB !== '') { libpath = process.env.PKCS11_LIB; diff --git a/test/unit/read-configtx.js b/test/unit/read-configtx.js index ad2ddfb7e3..45c4e239c5 100644 --- a/test/unit/read-configtx.js +++ b/test/unit/read-configtx.js @@ -27,7 +27,6 @@ var tape = require('tape'); var _test = require('tape-promise'); var test = _test(tape); -var hfc = require('fabric-client'); var Channel = require('fabric-client/lib/Channel.js'); var grpc = require('grpc'); @@ -37,9 +36,10 @@ var _configtxProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/comm var testUtil = require('../unit/util.js'); test('\n\n***** READ in the genesis block *****\n\n', function(t) { -// readin the envelope to send to the orderer + testUtil.resetDefaults(); + + // readin the envelope to send to the orderer let normalPath = path.normalize(path.join(__dirname, '../fixtures/channel/twoorgs.genesis.block')); - logger.info('normalPath=' + normalPath); var data = fs.readFileSync(normalPath); var channel = new Channel('test', 'fake'); @@ -55,7 +55,6 @@ test('\n\n***** READ in the genesis block *****\n\n', function(t) { var config_envelope = _configtxProto.ConfigEnvelope.decode(payload.data); channel.loadConfigEnvelope(config_envelope); t.pass(' Loaded the geneisis block from the configtx tool'); - logger.info(' test end'); t.end(); }); @@ -63,13 +62,11 @@ test('\n\n***** READ in the genesis block *****\n\n', function(t) { test('\n\n***** READ in the configtx *****\n\n', function(t) { // readin the envelope to send to the orderer let normalPath = path.normalize(path.join(__dirname, '../fixtures/channel/mychannel.tx')); - logger.info('normalPath=' + normalPath); var data = fs.readFileSync(normalPath); var channel = new Channel('test', 'fake'); channel.loadConfigUpdateEnvelope(data); t.pass(' Loaded the channel config from the configtx tool'); - logger.info(' test end'); t.end(); }); \ No newline at end of file diff --git a/test/unit/remote.js b/test/unit/remote.js index 91d952daa9..45dc8d931c 100644 --- a/test/unit/remote.js +++ b/test/unit/remote.js @@ -23,8 +23,6 @@ var test = _test(tape); var testutil = require('./util.js'); var utils = require('fabric-client/lib/utils.js'); -testutil.resetDefaults(); - var Remote = require('fabric-client/lib/Remote.js'); var Peer = require('fabric-client/lib/Peer.js'); var Orderer = require('fabric-client/lib/Orderer.js'); @@ -49,6 +47,8 @@ var aHostname = 'atesthostname'; var aHostnameOverride = 'atesthostnameoverride'; test('\n\n ** Remote node tests **\n\n', function (t) { + testutil.resetDefaults(); + console.log('\n * REMOTE *'); //Peer: secure grpcs, requires opts.pem var url = 'grpcs://' + aHostname + ':aport'; diff --git a/test/unit/transactionid.js b/test/unit/transactionid.js index 5dd261dcfa..114b859aaa 100644 --- a/test/unit/transactionid.js +++ b/test/unit/transactionid.js @@ -23,6 +23,7 @@ var test = _test(tape); var TransactionID = require('fabric-client/lib/TransactionID.js'); var User = require('fabric-client/lib/User.js'); var utils = require('fabric-client/lib/utils.js'); +var testutil = require('./util.js'); var enrollmentID = 123454321; var roles = ['admin', 'user']; @@ -34,6 +35,8 @@ var memberCfg = { var TEST_CERT_PEM = require('./user.js').TEST_CERT_PEM; test('\n\n ** Transaction - constructor set get tests **\n\n', function (t) { + testutil.resetDefaults(); + t.throws(function() { new TransactionID(); }, diff --git a/test/unit/user.js b/test/unit/user.js index 720cf7408a..cec609f6a9 100644 --- a/test/unit/user.js +++ b/test/unit/user.js @@ -20,7 +20,6 @@ var tape = require('tape'); var _test = require('tape-promise'); var test = _test(tape); -var hfc = require('fabric-client'); var testutil = require('./util.js'); var User = require('fabric-client/lib/User.js'); var utils = require('fabric-client/lib/utils.js'); @@ -32,9 +31,6 @@ var memberCfg = { 'enrollmentID': enrollmentID, 'roles': roles }; -var Client = hfc; - -testutil.resetDefaults(); var TEST_CERT_PEM = '-----BEGIN CERTIFICATE-----' + 'MIIDVDCCAvqgAwIBAgIBATAKBggqhkjOPQQDAjBOMRMwEQYDVQQKDArOoyBBY21l' + @@ -60,6 +56,8 @@ var TEST_CERT_PEM = '-----BEGIN CERTIFICATE-----' + module.exports.TEST_CERT_PEM = TEST_CERT_PEM; test('\n\n ** User - constructor set get tests **\n\n', function (t) { + testutil.resetDefaults(); + utils.setConfigSetting('crypto-hsm', false); var member1 = new User(memberName); diff --git a/test/unit/util.js b/test/unit/util.js index 670f503c2b..b39a643ccf 100644 --- a/test/unit/util.js +++ b/test/unit/util.js @@ -22,7 +22,7 @@ var util = require('util'); var jsrsa = require('jsrsasign'); var KEYUTIL = jsrsa.KEYUTIL; -var hfc = require('fabric-client'); +var Client = require('fabric-client'); var copService = require('fabric-ca-client/lib/FabricCAClientImpl.js'); var User = require('fabric-client/lib/User.js'); var CryptoSuite = require('fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js'); @@ -106,8 +106,8 @@ module.exports.existsSync = function(absolutePath /*string*/) { module.exports.readFile = readFile; -hfc.addConfigFile(path.join(__dirname, '../integration/e2e/config.json')); -var ORGS = hfc.getConfigSetting('test-network'); +Client.addConfigFile(path.join(__dirname, '../integration/e2e/config.json')); +var ORGS = Client.getConfigSetting('test-network'); var tlsOptions = { trustedRoots: [], @@ -117,8 +117,6 @@ var tlsOptions = { function getMember(username, password, client, t, userOrg) { var caUrl = ORGS[userOrg].ca.url; - t.comment('getMember, name: '+username+', client.getUserContext('+username+', true)'); - return client.getUserContext(username, true) .then((user) => { return new Promise((resolve, reject) => { @@ -128,11 +126,11 @@ function getMember(username, password, client, t, userOrg) { } var member = new User(username); - var cryptoSuite = client._cryptoSuite; + var cryptoSuite = client.getCryptoSuite(); if (!cryptoSuite) { - cryptoSuite = client.newCryptoSuite(); + cryptoSuite = Client.newCryptoSuite(); if (userOrg) { - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: module.exports.storePathForOrg(ORGS[userOrg].name)})); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: module.exports.storePathForOrg(ORGS[userOrg].name)})); client.setCryptoSuite(cryptoSuite); } } @@ -150,7 +148,7 @@ function getMember(username, password, client, t, userOrg) { return member.setEnrollment(enrollment.key, enrollment.certificate, ORGS[userOrg].mspid); }).then(() => { var skipPersistence = false; - if (client._cryptoSuite && !client._cryptoSuite._cryptoKeyStore) { + if (!client.getStateStore()) { skipPersistence = true; } return client.setUserContext(member, skipPersistence); @@ -170,9 +168,9 @@ function getAdmin(client, t, userOrg) { var certPath = path.join(__dirname, util.format('../fixtures/channel/crypto-config/peerOrganizations/%s.example.com/users/Admin@%s.example.com/signcerts', userOrg, userOrg)); var certPEM = readAllFiles(certPath)[0]; - var cryptoSuite = client.newCryptoSuite(); + var cryptoSuite = Client.newCryptoSuite(); if (userOrg) { - cryptoSuite.setCryptoKeyStore(client.newCryptoKeyStore({path: module.exports.storePathForOrg(ORGS[userOrg].name)})); + cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: module.exports.storePathForOrg(ORGS[userOrg].name)})); client.setCryptoSuite(cryptoSuite); } @@ -218,7 +216,7 @@ function readAllFiles(dir) { var certs = []; files.forEach((file_name) => { let file_path = path.join(dir,file_name); - console.log(' looking at file ::'+file_path); + logger.debug(' looking at file ::'+file_path); let data = fs.readFileSync(file_path); certs.push(data); }); @@ -251,7 +249,6 @@ module.exports.getSubmitter = function(client, test, peerOrgAdmin, org) { } if (peerAdmin) { - console.log(' >>>> getting the org admin'); return getAdmin(client, test, userOrg); } else { return getMember('admin', 'adminpw', client, test, userOrg);