From b020de2d0b047a37f2a5e13d6f1e0f91513242b0 Mon Sep 17 00:00:00 2001 From: Atsushin Date: Mon, 24 Aug 2020 15:59:50 +1000 Subject: [PATCH] BE-814 Fix inconsistency of network key (#172) Unified to use only network ID (network Name is used only for showing network name on Login view) Signed-off-by: Atsushi Neki --- app/persistence/fabric/CRUDService.js | 1 + app/platform/fabric/FabricClient.js | 71 +++++++--------- app/platform/fabric/FabricConfig.js | 10 ++- app/platform/fabric/Platform.js | 77 ++++++++---------- app/platform/fabric/Proxy.js | 44 +++++----- app/platform/fabric/config.json | 2 +- .../connection-profile/first-network.json | 10 +-- .../fabric/e2e-test/configs/config_multi.json | 4 +- .../fabric/e2e-test/specs/apitest_def_test.go | 1 + .../fabric/e2e-test/specs/apitest_test.go | 24 ++++-- app/platform/fabric/gateway/FabricGateway.js | 21 +++-- app/platform/fabric/service/NetworkService.js | 7 +- app/platform/fabric/sync/SyncPlatform.js | 41 +++++----- app/platform/fabric/sync/SyncService.js | 80 ++++++++----------- app/platform/fabric/utils/FabricUtils.js | 73 +---------------- client/src/components/Login/Login.js | 48 +++++++---- 16 files changed, 217 insertions(+), 297 deletions(-) diff --git a/app/persistence/fabric/CRUDService.js b/app/persistence/fabric/CRUDService.js index fd0ce3100..741c9e4fe 100644 --- a/app/persistence/fabric/CRUDService.js +++ b/app/persistence/fabric/CRUDService.js @@ -236,6 +236,7 @@ class CRUDService { ); if (isValidRow(c)) { + transaction.network_name = network_name; await this.sql.saveRow('transactions', transaction); await this.sql.updateBySql( `update chaincodes set txcount =txcount+1 where channel_genesis_hash='${transaction.channel_genesis_hash}' and network_name = '${network_name}' and name='${transaction.chaincodename}'` diff --git a/app/platform/fabric/FabricClient.js b/app/platform/fabric/FabricClient.js index 1e3e6cd8c..547383052 100644 --- a/app/platform/fabric/FabricClient.js +++ b/app/platform/fabric/FabricClient.js @@ -2,12 +2,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -const path = require('path'); const includes = require('lodash/includes'); const ExplorerError = require('../../common/ExplorerError'); const FabricUtils = require('./utils/FabricUtils.js'); const FabricGateway = require('../../platform/fabric/gateway/FabricGateway'); -const FabricConfig = require('../fabric/FabricConfig'); const helper = require('../../common/helper'); const logger = helper.getLogger('FabricClient'); @@ -22,15 +20,14 @@ const explorer_mess = require('../../common/ExplorerMessage').explorer; class FabricClient { /** * Creates an instance of FabricClient. - * @param {*} client_name + * @param {FabricConfig} config * @memberof FabricClient */ - constructor(network_name, client_name) { - this.network_name = network_name; - this.client_name = client_name; + constructor(config) { + this.network_id = config.getNetworkId(); this.fabricGateway = null; this.channelsGenHash = new Map(); - this.client_config = null; + this.config = config; this.status = false; this.channels = []; } @@ -38,28 +35,18 @@ class FabricClient { /** * * - * @param {*} client_config * @param {*} persistence * @memberof FabricClient */ - async initialize(client_config, persistence) { - this.client_config = client_config; - + async initialize(persistence) { // Before initializing a channel // Loading client from network configuration file - logger.debug( - 'Client configuration [%s] ...', - this.client_name, - ' this.client_config ', - this.client_config - ); + logger.debug('Client configuration [%s] ...', this.config.getNetworkId()); - const profileConnection = this.client_config.profile; - const configPath = path.resolve(__dirname, profileConnection); try { // Use Gateway to connect to fabric network - this.fabricGateway = new FabricGateway(configPath); + this.fabricGateway = new FabricGateway(this.config); await this.fabricGateway.initialize(); } catch (error) { // TODO in case of the failure, should terminate explorer? @@ -90,7 +77,7 @@ class FabricClient { } } else if (persistence) { logger.info('********* call to initializeDetachClient **********'); - this.initializeDetachClient(this.client_config, persistence); + this.initializeDetachClient(persistence); } else { logger.error('Not found any channels'); } @@ -99,27 +86,15 @@ class FabricClient { /** * * - * @param {*} client_config * @param {*} persistence * @memberof FabricClient */ - async initializeDetachClient(client_config, persistence) { - const name = client_config.name; - logger.debug( - 'initializeDetachClient --> client_config ', - client_config, - ' name ', - name - ); - const profileConnection = client_config.profile; - const configPath = path.resolve(__dirname, profileConnection); - const fabricConfig = new FabricConfig(); - fabricConfig.initialize(configPath); - const config = fabricConfig.getConfig(); - this.userName = fabricConfig.getAdminUser(); - const peers = fabricConfig.getPeersConfig(); + async initializeDetachClient(persistence) { + logger.debug('initializeDetachClient', this.config.getNetworkId()); + const network_config = this.config.getConfig(); + const peers = this.config.getPeersConfig(); - logger.info('initializeDetachClient, network config) ', config); + logger.info('initializeDetachClient, network config) ', network_config); logger.info( '************************************* initializeDetachClient *************************************************' ); @@ -130,7 +105,7 @@ class FabricClient { ); const channels = await persistence .getCrudService() - .getChannelsInfo(this.network_name); + .getChannelsInfo(this.network_id); if (channels.length === 0) { throw new ExplorerError(explorer_mess.error.ERROR_2003); @@ -140,7 +115,7 @@ class FabricClient { this.setChannelGenHash(channel.channelname, channel.channel_genesis_hash); const nodes = await persistence .getMetricService() - .getPeerList(this.network_name, channel.channel_genesis_hash); + .getPeerList(this.network_id, channel.channel_genesis_hash); for (const node of nodes) { const peer_config = peers[node.server_hostname]; let pem; @@ -170,7 +145,7 @@ class FabricClient { async initializeNewChannel(channel_name) { // Get genesis block for the channel const block = await this.getGenesisBlock(channel_name); - logger.debug('Genesis Block for client [%s]', this.client_name); + logger.debug('Genesis Block for client [%s]', this.network_id); const channel_genesis_hash = await FabricUtils.generateBlockHash( block.header @@ -284,8 +259,8 @@ class FabricClient { * @returns * @memberof FabricClient */ - getClientName() { - return this.client_name; + getNetworkId() { + return this.network_id; } /** @@ -312,6 +287,16 @@ class FabricClient { getStatus() { return this.status; } + + /** + * + * + * @returns + * @memberof FabricClient + */ + getNetworkConfig() { + return this.config.getConfig(); + } } module.exports = FabricClient; diff --git a/app/platform/fabric/FabricConfig.js b/app/platform/fabric/FabricConfig.js index 9be469b9d..d4cfc170b 100644 --- a/app/platform/fabric/FabricConfig.js +++ b/app/platform/fabric/FabricConfig.js @@ -32,8 +32,10 @@ class FabricConfig { * @memberof FabricConfig */ - initialize(configPath) { - const configJson = fs.readFileSync(configPath, 'utf8'); + initialize(network_id, network_config) { + this.network_id = network_id; + const profile_path = path.resolve(__dirname, network_config.profile); + const configJson = fs.readFileSync(profile_path, 'utf8'); this.config = JSON.parse(configJson); } @@ -175,8 +177,8 @@ class FabricConfig { * @returns * @memberof FabricConfig */ - getNetworkName() { - return this.config.name; + getNetworkId() { + return this.network_id; } /** diff --git a/app/platform/fabric/Platform.js b/app/platform/fabric/Platform.js index 828b9762e..9e5111134 100644 --- a/app/platform/fabric/Platform.js +++ b/app/platform/fabric/Platform.js @@ -78,10 +78,7 @@ class Platform { ); await this.buildClients(network_configs); - if ( - this.networks.size === 0 && - this.networks.get(this.defaultNetwork).size === 0 - ) { + if (this.networks.size === 0) { logger.error( '************* There is no client found for Hyperledger fabric platform *************' ); @@ -104,12 +101,10 @@ class Platform { logger.debug('Setting admin organization enrolment files'); this.network_configs = network_configs; - for (const network_name in this.network_configs) { - // this.networks.set(network_name, new Map()); - const client_configs = this.network_configs[network_name]; - // Console.log('network_name ', network_name, ' client_configs ', client_configs) + for (const network_id in this.network_configs) { + const network_config = this.network_configs[network_id]; if (!this.defaultNetwork) { - this.defaultNetwork = network_name; + this.defaultNetwork = network_id; } /* @@ -117,45 +112,38 @@ class Platform { * Each client is connected to only a single peer and monitor that particular peer only */ logger.info( - ' client_configs.name ', - client_configs.name, - ' client_configs.profile ', - client_configs.profile + ' network_config.id ', + network_id, + ' network_config.profile ', + network_config.profile ); - const client_name = client_configs.name; // Create client instance - logger.debug('Creating client [%s] >> ', client_name, client_configs); + logger.debug('Creating network client [%s] >> ', network_id, network_config); - const signupResult = await this.registerAdmin( - client_configs.name, - client_configs.profile - ); + const config = new FabricConfig(); + config.initialize(network_id, network_config); + + const signupResult = await this.registerAdmin(config); if (!signupResult) { - logger.error(`Failed to register admin user : ${network_name}`); + logger.error(`Failed to register admin user : ${network_id}`); continue; } const client = await FabricUtils.createFabricClient( - client_configs, - network_name, - client_name, + config, this.persistence ); if (client) { // Set client into clients map - const clientObj = { name: client_name, instance: client }; - this.networks.set(network_name, clientObj); + const clientObj = { name: network_config.name, instance: client }; + this.networks.set(network_id, clientObj); } // } } } - async registerAdmin(network, network_profile_path) { - const configPath = path.resolve(__dirname, network_profile_path); - const config = new FabricConfig(); - config.initialize(configPath); - + async registerAdmin(config) { if (!config.getEnableAuthentication()) { logger.info('Disabled authentication'); return true; @@ -168,13 +156,14 @@ class Platform { return false; } + const network_id = config.getNetworkId(); const reqUser = await User.createInstanceWithParam( user, password, - network, + network_id, 'admin' ).asJson(); - if (await this.userService.isExist(user, network)) { + if (await this.userService.isExist(user, network_id)) { logger.info('Already registered : admin'); return true; } @@ -194,17 +183,17 @@ class Platform { */ initializeListener(syncconfig) { /* eslint-disable */ - for (const [network_name, clientObj] of this.networks.entries()) { - const client_name = clientObj.name; - const client = clientObj.instance; + for (const [network_id, clientObj] of this.networks.entries()) { + const network_name = clientObj.name; + const network_client = clientObj.instance; logger.info( - 'initializeListener, client_name, client ', - client_name, - client.client_config + 'initializeListener, network_id, network_client ', + network_id, + network_client.getNetworkConfig() ); - if (this.getClient(network_name).getStatus()) { + if (network_client.getStatus()) { const explorerListener = new ExplorerListener(this, syncconfig); - explorerListener.initialize([network_name, client_name, '1']); + explorerListener.initialize([network_id, network_name, '1']); explorerListener.send('Successfully send a message to child process'); this.explorerListeners.push(explorerListener); } @@ -243,13 +232,13 @@ class Platform { /** * * - * @param {*} network_name - * @param {*} client_name + * @param {*} network_id * @returns * @memberof Platform */ - getClient(network_name) { - const clientObj = this.networks.get(network_name || this.defaultNetwork); + getClient(network_id) { + logger.info(`getClient (id:${network_id})`); + const clientObj = this.networks.get(network_id || this.defaultNetwork); return clientObj.instance; } diff --git a/app/platform/fabric/Proxy.js b/app/platform/fabric/Proxy.js index 567abab26..42710559a 100644 --- a/app/platform/fabric/Proxy.js +++ b/app/platform/fabric/Proxy.js @@ -68,10 +68,10 @@ class Proxy { * @returns * @memberof Proxy */ - async getCurrentChannel(network_name) { - logger.debug('getCurrentChannel: network_name', network_name); + async getCurrentChannel(network_id) { + logger.debug('getCurrentChannel: network_id', network_id); - const client = await this.platform.getClient(network_name); + const client = await this.platform.getClient(network_id); const channel_name = Object.keys(client.fabricGateway.config.channels)[0]; const channel_genesis_hash = client.getChannelGenHash(channel_name); let respose; @@ -97,12 +97,12 @@ class Proxy { * @returns * @memberof Proxy */ - async getPeersStatus(network_name, channel_genesis_hash) { - const client = await this.platform.getClient(network_name); + async getPeersStatus(network_id, channel_genesis_hash) { + const client = await this.platform.getClient(network_id); const channel_name = client.getChannelNameByHash(channel_genesis_hash); const nodes = await this.persistence .getMetricService() - .getPeerList(network_name, channel_genesis_hash); + .getPeerList(network_id, channel_genesis_hash); let discover_results; if (client.status) { try { @@ -158,7 +158,7 @@ class Proxy { * @returns * @memberof Proxy */ - async changeChannel(network_name, channel_genesis_hash) { + async changeChannel(network_id, channel_genesis_hash) { return channel_genesis_hash; } @@ -168,11 +168,11 @@ class Proxy { * @returns * @memberof Proxy */ - async getChannelsInfo(network_name) { - const client = this.platform.getClient(network_name); + async getChannelsInfo(network_id) { + const client = this.platform.getClient(network_id); const channels = await this.persistence .getCrudService() - .getChannelsInfo(network_name); + .getChannelsInfo(network_id); const currentchannels = []; for (const channel of channels) { const channel_genesis_hash = client.getChannelGenHash(channel.channelname); @@ -194,13 +194,13 @@ class Proxy { * @returns * @memberof Proxy */ - async getTxByOrgs(network_name, channel_genesis_hash) { + async getTxByOrgs(network_id, channel_genesis_hash) { const rows = await this.persistence .getMetricService() - .getTxByOrgs(network_name, channel_genesis_hash); + .getTxByOrgs(network_id, channel_genesis_hash); const organizations = await this.persistence .getMetricService() - .getOrgsData(network_name, channel_genesis_hash); + .getOrgsData(network_id, channel_genesis_hash); for (const organization of rows) { const index = organizations.indexOf(organization.creator_msp_id); @@ -225,8 +225,8 @@ class Proxy { * @returns * @memberof Proxy */ - async getBlockByNumber(network_name, channel_genesis_hash, number) { - const client = this.platform.getClient(network_name); + async getBlockByNumber(network_id, channel_genesis_hash, number) { + const client = this.platform.getClient(network_id); const channelName = client.getChannelNameByHash(channel_genesis_hash); let block; @@ -260,12 +260,12 @@ class Proxy { * @returns * @memberof Proxy */ - async getChannels(network_name) { - const client = this.platform.getClient(network_name); + async getChannels(network_id) { + const client = this.platform.getClient(network_id); const client_channels = client.getChannelNames(); const channels = await this.persistence .getCrudService() - .getChannelsInfo(network_name); + .getChannelsInfo(network_id); const respose = []; for (let i = 0; i < channels.length; i++) { @@ -328,8 +328,8 @@ class Proxy { logger.debug('Message from child %j', msg); if (fabric_const.NOTITY_TYPE_NEWCHANNEL === msg.notify_type) { // Initialize new channel instance in parent - if (msg.network_name && msg.client_name) { - const client = this.platform.getClient(msg.network_name); + if (msg.network_id) { + const client = this.platform.getClient(msg.network_id); if (msg.channel_name) { client.initializeNewChannel(msg.channel_name); } else { @@ -347,8 +347,8 @@ class Proxy { fabric_const.NOTITY_TYPE_CHAINCODE === msg.notify_type ) { // Update channel details in parent - if (msg.network_name && msg.client_name) { - const client = this.platform.getClient(msg.network_name); + if (msg.network_id) { + const client = this.platform.getClient(msg.network_id); if (msg.channel_name) { client.initializeChannelFromDiscover(msg.channel_name); } else { diff --git a/app/platform/fabric/config.json b/app/platform/fabric/config.json index 29b9812cb..b607e8771 100644 --- a/app/platform/fabric/config.json +++ b/app/platform/fabric/config.json @@ -1,7 +1,7 @@ { "network-configs": { "first-network": { - "name": "first-network", + "name": "My first network", "profile": "./connection-profile/first-network.json" } }, diff --git a/app/platform/fabric/connection-profile/first-network.json b/app/platform/fabric/connection-profile/first-network.json index 3dd3efec5..3848d981a 100644 --- a/app/platform/fabric/connection-profile/first-network.json +++ b/app/platform/fabric/connection-profile/first-network.json @@ -1,5 +1,5 @@ { - "name": "first-network", + "name": "first network (ignored)", "version": "1.0.0", "license": "Apache-2.0", "client": { @@ -44,18 +44,18 @@ "Org1MSP": { "mspid": "Org1MSP", "adminPrivateKey": { - "path": "/fabric-path/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/priv_sk" + "path": "/home/atsushi/dev/hyperledger/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/priv_sk" }, "peers": ["peer0.org1.example.com"], "signedCert": { - "path": "/fabric-path/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem" + "path": "/home/atsushi/dev/hyperledger/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem" } } }, "peers": { "peer0.org1.example.com": { "tlsCACerts": { - "path": "/fabric-path/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" + "path": "/home/atsushi/dev/hyperledger/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt" }, "url": "grpcs://localhost:7051", "grpcOptions": { @@ -70,7 +70,7 @@ "verify": false }, "tlsCACerts": { - "path": "/fabric-path/fabric-samples/first-network/crypto-config/peerOrganizations/org1/ca/ca.org1-cert.pem" + "path": "/home/atsushi/dev/hyperledger/fabric-samples/first-network/crypto-config/peerOrganizations/org1/ca/ca.org1-cert.pem" }, "caName": "ca0-org1" } diff --git a/app/platform/fabric/e2e-test/configs/config_multi.json b/app/platform/fabric/e2e-test/configs/config_multi.json index 859f7afc9..ceb8cfbb8 100644 --- a/app/platform/fabric/e2e-test/configs/config_multi.json +++ b/app/platform/fabric/e2e-test/configs/config_multi.json @@ -1,11 +1,11 @@ { "network-configs": { "org1-network": { - "name": "org1-network", + "name": "org1 network", "profile": "./e2e-test/configs/connection-profile/org1-network.json" }, "org2-network": { - "name": "org2-network", + "name": "org2 network", "profile": "./e2e-test/configs/connection-profile/org2-network.json" } }, diff --git a/app/platform/fabric/e2e-test/specs/apitest_def_test.go b/app/platform/fabric/e2e-test/specs/apitest_def_test.go index f741f73c0..72e60a801 100644 --- a/app/platform/fabric/e2e-test/specs/apitest_def_test.go +++ b/app/platform/fabric/e2e-test/specs/apitest_def_test.go @@ -125,6 +125,7 @@ type PeersStatusResp struct { type Network struct { Name string `json:"name"` + Id string `json:"id"` Instance interface{} `json:"instance"` } diff --git a/app/platform/fabric/e2e-test/specs/apitest_test.go b/app/platform/fabric/e2e-test/specs/apitest_test.go index dfa29faee..57b8b3253 100644 --- a/app/platform/fabric/e2e-test/specs/apitest_test.go +++ b/app/platform/fabric/e2e-test/specs/apitest_test.go @@ -42,12 +42,16 @@ func basicCheck(loginId string) { resp := restGet("/auth/networklist", &NetworklistInfo{}) result := resp.Result().(*NetworklistInfo) - list := []string{} + nameList := []string{} + idList := []string{} for _, val := range result.NetworkList { - list = append(list, val.Name) + nameList = append(nameList, val.Name) + idList = append(idList, val.Id) } - Expect(list).Should(HaveLen(1)) - Expect(list).Should(ContainElements([]string{"org1-network"})) + Expect(nameList).Should(HaveLen(1)) + Expect(nameList).Should(ContainElements([]string{"org1-network"})) + Expect(idList).Should(HaveLen(1)) + Expect(idList).Should(ContainElements([]string{"org1-network"})) }) It("login to org1-network", func() { @@ -466,12 +470,16 @@ var _ = Describe("REST API Test Suite - Multiple profile", func() { It("get network list", func() { resp := restGet("/auth/networklist", &NetworklistInfo{}) result := resp.Result().(*NetworklistInfo) - list := []string{} + nameList := []string{} + idList := []string{} for _, val := range result.NetworkList { - list = append(list, val.Name) + nameList = append(nameList, val.Name) + idList = append(idList, val.Id) } - Expect(list).Should(HaveLen(2)) - Expect(list).Should(ContainElements([]string{"org1-network", "org2-network"})) + Expect(nameList).Should(HaveLen(2)) + Expect(nameList).Should(ContainElements([]string{"org1 network", "org2 network"})) + Expect(idList).Should(HaveLen(2)) + Expect(idList).Should(ContainElements([]string{"org1-network", "org2-network"})) }) }) diff --git a/app/platform/fabric/gateway/FabricGateway.js b/app/platform/fabric/gateway/FabricGateway.js index f10ae0c25..93aac74ef 100644 --- a/app/platform/fabric/gateway/FabricGateway.js +++ b/app/platform/fabric/gateway/FabricGateway.js @@ -21,20 +21,22 @@ const helper = require('../../../common/helper'); const logger = helper.getLogger('FabricGateway'); const explorer_mess = require('../../../common/ExplorerMessage').explorer; const ExplorerError = require('../../../common/ExplorerError'); -const FabricConfig = require('../FabricConfig'); class FabricGateway { - constructor(networkConfig) { - this.networkConfig = networkConfig; - this.config = null; + /** + * Creates an instance of FabricGateway. + * @param {FabricConfig} config + * @memberof FabricGateway + */ + constructor(fabricConfig) { + this.fabricConfig = fabricConfig; + this.config = this.fabricConfig.getConfig(); this.gateway = null; this.wallet = null; this.tlsEnable = false; this.defaultChannelName = null; this.gateway = new Gateway(); - this.fabricConfig = new FabricConfig(); this.fabricCaEnabled = false; - this.networkName = null; this.client = null; this.FSWALLET = null; this.enableAuthentication = false; @@ -42,15 +44,10 @@ class FabricGateway { } async initialize() { - const configPath = path.resolve(__dirname, this.networkConfig); - this.fabricConfig = new FabricConfig(); - this.fabricConfig.initialize(configPath); - this.config = this.fabricConfig.getConfig(); this.fabricCaEnabled = this.fabricConfig.isFabricCaEnabled(); this.tlsEnable = this.fabricConfig.getTls(); this.enableAuthentication = this.fabricConfig.getEnableAuthentication(); - this.networkName = this.fabricConfig.getNetworkName(); - this.FSWALLET = 'wallet/' + this.networkName; + this.FSWALLET = 'wallet/' + this.fabricConfig.getNetworkId(); const explorerAdminId = this.fabricConfig.getAdminUser(); if (!explorerAdminId) { diff --git a/app/platform/fabric/service/NetworkService.js b/app/platform/fabric/service/NetworkService.js index 797f8d383..477e7f785 100644 --- a/app/platform/fabric/service/NetworkService.js +++ b/app/platform/fabric/service/NetworkService.js @@ -32,10 +32,11 @@ class NetworkService { const networklist = []; const networks = this.platform.getNetworks(); logger.debug('Network list ', networks); - for (const [networkName, clientObj] of networks.entries()) { - logger.debug('Network list ', networkName); + for (const [network_id, clientObj] of networks.entries()) { + logger.debug('Network list ', clientObj.name); networklist.push({ - name: networkName, + id: network_id, + name: clientObj.name, authEnabled: clientObj.instance.fabricGateway.getEnableAuthentication() }); } diff --git a/app/platform/fabric/sync/SyncPlatform.js b/app/platform/fabric/sync/SyncPlatform.js index 3ec610f6d..766343f8a 100644 --- a/app/platform/fabric/sync/SyncPlatform.js +++ b/app/platform/fabric/sync/SyncPlatform.js @@ -8,6 +8,7 @@ const fs = require('fs-extra'); const SyncService = require('../sync/SyncService'); const FabricUtils = require('../utils/FabricUtils'); const FabricEvent = require('./FabricEvent'); +const FabricConfig = require('../FabricConfig'); const helper = require('../../../common/helper'); @@ -35,15 +36,15 @@ class SyncPlatform { * @memberof SyncPlatform */ constructor(persistence, sender) { + this.network_id = null; this.network_name = null; - this.client_name = null; this.client = null; this.eventHub = null; this.sender = sender; this.persistence = persistence; this.syncService = new SyncService(this, this.persistence); this.blocksSyncTime = 60000; - this.client_configs = null; + this.network_config = null; } /** @@ -57,8 +58,8 @@ class SyncPlatform { const _self = this; logger.debug( - '******* Initialization started for child client process %s ******', - this.client_name + '******* Initialization started for child client process ******', + args ); // Loading the config.json @@ -67,23 +68,21 @@ class SyncPlatform { if (args.length === 0) { // Get the first network and first client - this.network_name = Object.keys(network_configs)[0]; - this.client_name = network_configs[this.network_name].name; + this.network_id = Object.keys(network_configs)[0]; + this.network_name = network_configs[this.network_id].name; } else if (args.length === 1) { // Get the first client with respect to the passed network name - this.network_name = args[0]; - this.client_name = Object.keys( - network_configs[this.network_name].clients - )[0]; + this.network_id = args[0]; + this.network_name = Object.keys(network_configs[this.network_id].clients)[0]; } else { - this.network_name = args[0]; - this.client_name = args[1]; + this.network_id = args[0]; + this.network_name = args[1]; } logger.info( explorer_mess.message.MESSAGE_1002, - this.network_name, - this.client_name + this.network_id, + this.network_name ); logger.debug('Blocks synch interval time >> %s', this.blocksSyncTime); @@ -92,19 +91,15 @@ class SyncPlatform { global.hfc.config.set('discovery-cache-life', this.blocksSyncTime); // global.hfc.config.set('initialize-with-discovery', true); - this.client_configs = network_configs[this.network_name]; + this.network_config = network_configs[this.network_id]; + const config = new FabricConfig(); + config.initialize(this.network_id, this.network_config); - this.client = await FabricUtils.createFabricClient( - this.client_configs, - this.network_name, - this.client_name - ); + this.client = await FabricUtils.createFabricClient(config); if (!this.client) { throw new ExplorerError(explorer_mess.error.ERROR_2011); } - this.client.network_name = this.network_name; - // Updating the client network and other details to DB const res = await this.syncService.synchNetworkConfigToDB(this.client); if (!res) { @@ -129,7 +124,7 @@ class SyncPlatform { }, this.blocksSyncTime); logger.debug( '******* Initialization end for child client process %s ******', - this.client_name + this.network_id ); } diff --git a/app/platform/fabric/sync/SyncService.js b/app/platform/fabric/sync/SyncService.js index 6832eb4c8..a4af6fdf2 100644 --- a/app/platform/fabric/sync/SyncService.js +++ b/app/platform/fabric/sync/SyncService.js @@ -77,7 +77,7 @@ class SyncServices { for (const channel_name of channels) { logger.info( 'SyncServices.synchNetworkConfigToDB client ', - client.client_name, + client.getNetworkId(), ' channel_name ', channel_name ); @@ -119,15 +119,15 @@ class SyncServices { * @memberof SyncServices */ async insertNewChannel(client, channel_name, block, channel_genesis_hash) { - const network_name = client.network_name; + const network_id = client.getNetworkId(); const channelInfo = await this.persistence .getCrudService() - .getChannel(network_name, channel_name, channel_genesis_hash); + .getChannel(network_id, channel_name, channel_genesis_hash); if (!channelInfo) { const count = await this.persistence .getCrudService() - .existChannel(network_name, channel_name); + .existChannel(network_id, channel_name); if (count.count === '0') { if (block.data && block.data.data.length > 0 && block.data.data[0]) { const createdt = await FabricUtils.getBlockTimeStamp( @@ -144,13 +144,12 @@ class SyncServices { }; await this.persistence .getCrudService() - .saveChannel(network_name, channel_row); + .saveChannel(network_id, channel_row); } } else { const notify = { notify_type: fabric_const.NOTITY_TYPE_EXISTCHANNEL, - network_name: this.platform.network_name, - client_name: client.client_name, + network_id: network_id, channel_name }; this.platform.send(notify); @@ -212,21 +211,14 @@ class SyncServices { async insertNewPeer(peer, channel_genesis_hash, client) { let eventurl = ''; let requesturl = peer.endpoint; - const network_name = client.network_name; + const network_id = client.getNetworkId(); const host_port = peer.endpoint.split(':'); - if ( - client.client_config.peers && - client.client_config.peers[host_port[0]] && - client.client_config.peers[host_port[0]].url - ) { - requesturl = client.client_config.peers[host_port[0]].url; + const peers = client.getNetworkConfig().peers; + if (peers && peers[host_port[0]] && peers[host_port[0]].url) { + requesturl = peers[host_port[0]].url; } - if ( - client.client_config.peers && - client.client_config.peers[host_port[0]] && - client.client_config.peers[host_port[0]].eventUrl - ) { - eventurl = client.client_config.peers[host_port[0]].eventUrl; + if (peers && peers[host_port[0]] && peers[host_port[0]].eventUrl) { + eventurl = peers[host_port[0]].eventUrl; } const peer_row = { @@ -237,14 +229,14 @@ class SyncServices { channel_genesis_hash, peer_type: 'PEER' }; - await this.persistence.getCrudService().savePeer(network_name, peer_row); + await this.persistence.getCrudService().savePeer(network_id, peer_row); const channel_peer_row = { peerid: host_port[0], channelid: channel_genesis_hash }; await this.persistence .getCrudService() - .savePeerChannelRef(network_name, channel_peer_row); + .savePeerChannelRef(network_id, channel_peer_row); } /** @@ -256,7 +248,7 @@ class SyncServices { * @memberof SyncServices */ async insertNewOrderers(orderer, channel_genesis_hash, client) { - const network_name = client.network_name; + const network_id = client.getNetworkId(); const discoveryProtocol = client.fabricGateway.getDiscoveryProtocol(); const requesturl = `${discoveryProtocol}://${orderer.host}:${orderer.port}`; logger.debug( @@ -273,14 +265,14 @@ class SyncServices { channel_genesis_hash, peer_type: 'ORDERER' }; - await this.persistence.getCrudService().savePeer(network_name, orderer_row); + await this.persistence.getCrudService().savePeer(network_id, orderer_row); const channel_orderer_row = { peerid: orderer.host, channelid: channel_genesis_hash }; await this.persistence .getCrudService() - .savePeerChannelRef(network_name, channel_orderer_row); + .savePeerChannelRef(network_id, channel_orderer_row); } /** @@ -297,7 +289,7 @@ class SyncServices { channel_genesis_hash, discoveryResults ) { - const network_name = client.network_name; + const network_id = client.getNetworkId(); const channel_name = client.getChannelNameByHash(channel_genesis_hash); const chaincodes = await client.fabricGateway.queryInstantiatedChaincodes( channel_name @@ -317,7 +309,7 @@ class SyncServices { }; await this.persistence .getCrudService() - .saveChaincode(network_name, chaincode_row); + .saveChaincode(network_id, chaincode_row); if (discoveryResults && discoveryResults.peers_by_org) { for (const org_name in discoveryResults.peers_by_org) { const org = discoveryResults.peers_by_org[org_name]; @@ -355,7 +347,7 @@ class SyncServices { endpoint, channel_genesis_hash ) { - const network_name = client.network_name; + const network_id = client.getNetworkId(); const host_port = endpoint.split(':'); const chaincode_peer_row = { chaincodeid: chaincode.name, @@ -365,16 +357,15 @@ class SyncServices { }; await this.persistence .getCrudService() - .saveChaincodPeerRef(network_name, chaincode_peer_row); + .saveChaincodPeerRef(network_id, chaincode_peer_row); } async synchBlocks(client, channel_name) { - const network_name = client.network_name; - const client_name = client.getClientName(); + const network_id = client.getNetworkId(); - const synch_key = `${client_name}_${channel_name}`; + const synch_key = `${network_id}_${channel_name}`; if (this.synchInProcess.includes(synch_key)) { - logger.info(`Block synch in process for >> ${client_name}_${channel_name}`); + logger.info(`Block synch in process for >> ${network_id}_${channel_name}`); return; } this.synchInProcess.push(synch_key); @@ -386,7 +377,7 @@ class SyncServices { // Query missing blocks from DB const results = await this.persistence .getMetricService() - .findMissingBlockNumber(network_name, channel_genesis_hash, blockHeight); + .findMissingBlockNumber(network_id, channel_genesis_hash, blockHeight); if (results) { for (const result of results) { @@ -415,7 +406,7 @@ class SyncServices { * @memberof SyncServices */ async processBlockEvent(client, block) { - const network_name = client.network_name; + const network_id = client.getNetworkId(); const _self = this; // Get the first transaction const first_tx = block.data.data[0]; @@ -454,8 +445,7 @@ class SyncServices { const notify = { notify_type: fabric_const.NOTITY_TYPE_NEWCHANNEL, - network_name: _self.platform.network_name, - client_name: client.client_name, + network_id, channel_name }; @@ -480,8 +470,7 @@ class SyncServices { ); const notify = { notify_type: fabric_const.NOTITY_TYPE_UPDATECHANNEL, - network_name: _self.platform.network_name, - client_name: client.client_name, + network_id, channel_name }; @@ -623,8 +612,7 @@ class SyncServices { const notify = { notify_type: fabric_const.NOTITY_TYPE_CHAINCODE, - network_name: _self.platform.network_name, - client_name: client.client_name, + network_id, channel_name }; @@ -658,15 +646,14 @@ class SyncServices { endorser_signature, creator_id_bytes, payload_proposal_hash, - endorser_id_bytes, - network_name + endorser_id_bytes }; // Insert transaction const res = await this.persistence .getCrudService() - .saveTransaction(network_name, transaction_row); + .saveTransaction(network_id, transaction_row); logger.debug('saveTransaction ', res); } @@ -674,15 +661,14 @@ class SyncServices { logger.info('block_row.blocknum ', block_row.blocknum); const status = await this.persistence .getCrudService() - .saveBlock(network_name, block_row); + .saveBlock(network_id, block_row); logger.debug('status ', status); if (status) { // Push last block const notify = { notify_type: fabric_const.NOTITY_TYPE_BLOCK, - network_name: _self.platform.network_name, - client_name: client.client_name, + network_id, channel_name, title: `Block ${block.header.number.toString()} added to Channel: ${channel_name}`, type: 'block', diff --git a/app/platform/fabric/utils/FabricUtils.js b/app/platform/fabric/utils/FabricUtils.js index f3813c486..33ece1944 100644 --- a/app/platform/fabric/utils/FabricUtils.js +++ b/app/platform/fabric/utils/FabricUtils.js @@ -15,86 +15,22 @@ const helper = require('../../../common/helper'); const logger = helper.getLogger('FabricUtils'); -async function createFabricClient( - client_configs, - network_name, - client_name, - persistence -) { +async function createFabricClient(config, persistence) { // Create new FabricClient - const client = new FabricClient(network_name, client_name); + const client = new FabricClient(config); // Initialize fabric client logger.debug( '************ Initializing fabric client for [%s]************', - client_name + config.getNetworkId() ); try { - await client.initialize(client_configs, persistence); + await client.initialize(persistence); return client; } catch (err) { throw new ExplorerError(explorer_error.ERROR_2014); } } -async function createDetachClient( - client_configs, - network_name, - client_name, - persistence -) { - // Clone global.hfc.config configuration - const client_config = cloneConfig(client_configs, client_name); - - const client = new FabricClient(network_name, client_name); - await client.initializeDetachClient(client_config, persistence); - return client; -} - -function cloneConfig(client_configs, client_name) { - const global_hfc_config = JSON.parse(JSON.stringify(global.hfc.config)); - - let client_config = global_hfc_config; - client_config.client = client_configs.clients[client_name]; - client_config.version = client_configs.version; - client_config.channels = client_configs.channels; - client_config.organizations = client_configs.organizations; - client_config.peers = client_configs.peers; - client_config.orderers = client_configs.orderers; - client_config.certificateAuthorities = client_configs.certificateAuthorities; - - // Modify url with respect to TLS enable - client_config = processTLS_URL(client_config); - return client_config; -} - -/** - * - * - * @param {*} client_config - * @returns - */ -function processTLS_URL(client_config) { - for (const peer_name in client_config.peers) { - const url = client_config.peers[peer_name].url; - client_config.peers[peer_name].url = client_config.client.tlsEnable - ? `grpcs${url.substring(url.indexOf('://'))}` - : `grpc${url.substring(url.indexOf('://'))}`; - if (client_config.peers[peer_name].eventUrl) { - const eventUrl = client_config.peers[peer_name].eventUrl; - client_config.peers[peer_name].eventUrl = client_config.client.tlsEnable - ? `grpcs${eventUrl.substring(eventUrl.indexOf('://'))}` - : `grpc${eventUrl.substring(eventUrl.indexOf('://'))}`; - } - } - for (const ord_name in client_config.orderers) { - const url = client_config.orderers[ord_name].url; - client_config.orderers[ord_name].url = client_config.client.tlsEnable - ? `grpcs${url.substring(url.indexOf('://'))}` - : `grpc${url.substring(url.indexOf('://'))}`; - } - return client_config; -} - /** * * @@ -197,4 +133,3 @@ exports.createFabricClient = createFabricClient; exports.getBlockTimeStamp = getBlockTimeStamp; exports.generateDir = generateDir; exports.getPEMfromConfig = getPEMfromConfig; -exports.createDetachClient = createDetachClient; diff --git a/client/src/components/Login/Login.js b/client/src/components/Login/Login.js index 5d982089f..b50a8e687 100644 --- a/client/src/components/Login/Login.js +++ b/client/src/components/Login/Login.js @@ -91,7 +91,8 @@ export class Login extends Component { }, network: { error: null, - value: '' + value: '', + id: '' }, autoLoginAttempted: false, error: '', @@ -107,7 +108,8 @@ export class Login extends Component { networks, network: { error: null, - value: networks[0].name || '' + value: networks[0].name || '', + id: networks[0].id }, authEnabled: networks[0].authEnabled })); @@ -123,20 +125,23 @@ export class Login extends Component { }; if (name === 'network') { const { networks } = this.state; - newState.authEnabled = (networks.find(n => n.name === value) || {}).authEnabled; + newState.authEnabled = ( + networks.find(n => n.name === value) || {} + ).authEnabled; + newState.network.id = (networks.find(n => n.name === value) || {}).id; } this.setState(newState); }; - async performLogin({ user, password, network}) { + async performLogin({ user, password, network }) { const { login } = this.props; const { authEnabled } = this.state; const info = await login( { user: authEnabled ? user : 'dummy-user', - password: authEnabled ? password : 'dummy-password', + password: authEnabled ? password : 'dummy-password' }, network ); @@ -157,25 +162,40 @@ export class Login extends Component { await this.performLogin({ user: user.value, password: password.value, - network: network.value + network: network.id }); }; async componentDidUpdate() { const { networks, autoLoginAttempted } = this.state; - // If we have only one network and it doesn't have auth enabled, perform a login - // autoLoginAttempted is a safety to prevent multiple tries - if (networks.length === 1 && !networks[0].authEnabled && !autoLoginAttempted) { + /* + * If we have only one network and it doesn't have auth enabled, perform a login + * autoLoginAttempted is a safety to prevent multiple tries + */ + if ( + networks.length === 1 && + !networks[0].authEnabled && + !autoLoginAttempted + ) { + // eslint-disable-next-line react/no-did-update-set-state this.setState(() => ({ autoLoginAttempted: true })); - await this.performLogin({ network: networks[0].name }) + await this.performLogin({ network: networks[0].name }); } } render() { - const { info, user, password, network, networks, authEnabled, isLoading } = this.state; + const { + info, + user, + password, + network, + networks, + authEnabled, + isLoading + } = this.state; const { classes, error } = this.props; return ( @@ -249,8 +269,8 @@ export class Login extends Component { )} - )} - {authEnabled && ( + )} + {authEnabled && ( - {authEnabled ? "Sign in" : "Connect"} + {authEnabled ? 'Sign in' : 'Connect'}