Skip to content

Commit

Permalink
Merge pull request #199 from dengyi9/master
Browse files Browse the repository at this point in the history
implement CA management functions of fabricClient. #171
  • Loading branch information
dengyi9 authored Mar 20, 2019
2 parents fba16f8 + f54f0de commit 51d4cbe
Show file tree
Hide file tree
Showing 7 changed files with 353 additions and 184 deletions.
25 changes: 13 additions & 12 deletions src/components/UserLayout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,21 @@ export default class UserLayout extends React.Component {
peerSSLTarget: this.state.peerSSLTarget,
ordererSSLTarget: this.state.ordererSSLTarget,
path: 'resources/key/users/' } },
{}, () => {
});
getFabricClientSingleton().then((fabricClient) => {
fabricClient.importCer(this.state.keyPath, this.state.certPath).then((result) => {
db.update({ id: 0 },
{ $set: { isSign: 2 } },
{}, () => {
{},
() => {
getFabricClientSingleton().then((fabricClient) => {
fabricClient.importCer(this.state.keyPath, this.state.certPath).then((result) => {
db.update({ id: 0 },
{ $set: { isSign: 2 } },
{}, () => {
});
this.props.onGetChildMessage(2);
logger.info('result', result);
}, () => {
message.error(this.state.Common.ERROR.certificateFailed);
});
this.props.onGetChildMessage(2);
logger.info('result', result);
}, () => {
message.error(this.state.Common.ERROR.certificateFailed);
});
});
});

logger.info(this.state.certPath);
}
Expand Down
84 changes: 64 additions & 20 deletions src/util/fabric.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@
import { getConfigDBSingleton } from './createDB';

const FabricClientSDK = require('fabric-client');
const FabricCAClientSDK = require('fabric-ca-client');
const path = require('path');
const util = require('util');
const fs = require('fs');
const { exec } = require('child_process');
const logger = require('electron-log');

const db = getConfigDBSingleton();

const logger = require('electron-log');

class FabricClient {
constructor() {
this.fabricClient = new FabricClientSDK();
this.fabricCAClient = null;
this.user = null;
}

// 抽出空挡,插入配置文件,以便集成测试
Expand All @@ -40,18 +43,24 @@ class FabricClient {

if (config.tlsPeerPath === '' || config.tlsOrdererPath === '') {
logger.info('+++++++++++++++++');
self.flag = false;
self.isTlsEnabled = false;
self.peer = fabricClient.newPeer(config.peerGrpcUrl);
self.order = fabricClient.newOrderer(config.ordererUrl);
} else {
logger.info('------------------');
self.peerCert = fs.readFileSync(config.tlsPeerPath);
self.orderersCert = fs.readFileSync(config.tlsOrdererPath);
self.flag = true;
self.ordererCert = fs.readFileSync(config.tlsOrdererPath);
self.isTlsEnabled = true;
self.peer = fabricClient.newPeer(config.peerGrpcUrl,
{ pem: Buffer.from(this.peerCert).toString(), 'ssl-target-name-override': config.peerSSLTarget });
self.order = fabricClient.newOrderer(config.ordererUrl,
{ pem: Buffer.from(this.orderersCert).toString(), 'ssl-target-name-override': config.ordererSSLTarget });
{ pem: Buffer.from(this.ordererCert).toString(), 'ssl-target-name-override': config.ordererSSLTarget });
}

// TODO: 考虑 ca管理 与 peer管理,分别维护两套用户
// FIXME: CA also need to support TLS like peer/orderer above
if (config.caServerUrl) {
self.fabricCAClient = new FabricCAClientSDK(config.caServerUrl);
}

logger.info('config:', config);
Expand All @@ -70,7 +79,7 @@ class FabricClient {
* @returns {Promise<Client.User | never>}
*
*/
_enrollUser() {
_loginUser() {
const self = this;
const usrName = self.config.mspid;
logger.info('start to load member user.', ' store_path: ', self.store_path);
Expand All @@ -89,7 +98,12 @@ class FabricClient {
self.fabricClient.setCryptoSuite(cryptoSuite);

logger.info('almost done');
return self.fabricClient.getUserContext(usrName, true);
return self.fabricClient.getUserContext(usrName, true) // FIXME: usernaem和mspid可能要分开
.then((user) => {
logger.info('loginUser: ', user.toString());
self.user = user;
return Promise.resolve(user);
});
});
}

Expand All @@ -104,15 +118,8 @@ class FabricClient {
if (!channel) {
logger.info('start create channel');
channel = this.fabricClient.newChannel(channelName);
if (this.flag) {
logger.info('-----------');
channel.addPeer(this.peer);
channel.addOrderer(this.order);
} else {
logger.info('+++++++++++++++++');
channel.addPeer(this.peer);
channel.addOrderer(this.order);
}
channel.addPeer(this.peer);
channel.addOrderer(this.order);
this.channels[channelName] = channel;
} else {
logger.info(`channel(${channelName}) exists, get it from memory.`);
Expand Down Expand Up @@ -194,12 +201,11 @@ class FabricClient {
let txID;
const fabricClient = this.fabricClient;
const self = this;
return this._enrollUser(this).then((user) => {
return this._loginUser(this).then((user) => {
if (user && user.isEnrolled()) {
logger.info(`Successfully loaded user(${user.getName()}) from persistence`);
} else {
logger.error('Failed to get user run registerUser.js');
return Promise.reject(new Error('Failed to get user1.... run registerUser.js'));
return Promise.reject(new Error('Failed to get user'));
}

// get a transaction id object based on the current user assigned to fabric client
Expand Down Expand Up @@ -769,6 +775,44 @@ class FabricClient {
return this.fabricClient.newPeer(url, opts);
}


/**
* 连接CA,获取用户证书私钥 - 参考 https://fabric-sdk-node.github.io/release-1.4/FabricCAServices.html#enroll
* @param {EnrollmentRequest} req - 参考 https://fabric-sdk-node.github.io/release-1.4/global.html#EnrollmentRequest
* @return {Promise<Enrollment>} enrollment - 参考 https://fabric-sdk-node.github.io/release-1.4/global.html#Enrollment
*/
enroll(req) {
return this.fabricCAClient.enroll(req);
}

/**
* 连接CA,注册用户 - 参考 https://fabric-sdk-node.github.io/release-1.4/FabricCAServices.html#register
* @param {RegisterRequest} req - 参考 https://fabric-sdk-node.github.io/release-1.4/global.html#RegisterRequest
* @return {Promise<string>} secret
*/
register(req) {
return this.fabricCAClient.register(req, this.user);
}

/**
* 连接CA,获取当前用户更新后的证书私钥 - 参考 https://fabric-sdk-node.github.io/release-1.4/FabricCAServices.html#reenroll
* @param {Array.<AttributeRequest>} Optional - https://fabric-sdk-node.github.io/release-1.4/FabricCAServices.html#reenroll
* @return {Promise<Object>} keyCert - Promise for an object with "key" for private key
* and "certificate" for the signed certificate
*/
reenroll(Optional) {
return this.fabricCAClient.reenroll(this.user, Optional);
}

/**
* 连接CA,吊销用户证书 - 参考 https://fabric-sdk-node.github.io/release-1.4/FabricCAServices.html#revoke
* @param {Object} req - 参考 https://fabric-sdk-node.github.io/release-1.4/FabricCAServices.html#revoke
* @return {Promise<>} result -
*/
revoke(req) {
return this.fabricCAClient.revoke(req, this.user);
}

// 关闭连接
close() {
this.peer.close();
Expand All @@ -785,7 +829,7 @@ export function getFabricClientSingletonHelper(dbConfig) {
__fabricClient = new FabricClient();
return __fabricClient._getConfig(dbConfig)
.then(input => __fabricClient._config(input))
.then(() => __fabricClient._enrollUser())
.then(() => __fabricClient._loginUser())
.then(() => Promise.resolve(__fabricClient));
}
return Promise.resolve(__fabricClient);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg4LFP9ew4+MANaSfs
hJc5hPLpGRQS1levGOe19U7PDGKhRANCAATdmT3EuHwOuBcV/EWS8o6eRgExHEQb
HYZAxpVM5VYai8UElGbc2C+n6NnV9ZzlMSJN7eg1AWaWg97ccPc9bRDO
-----END PRIVATE KEY-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE3Zk9xLh8DrgXFfxFkvKOnkYBMRxE
Gx2GQMaVTOVWGovFBJRm3Ngvp+jZ1fWc5TEiTe3oNQFmloPe3HD3PW0Qzg==
-----END PUBLIC KEY-----
1 change: 1 addition & 0 deletions test/resources/key/users/admin
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"admin","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"904e6dc0cc8eaca2c0e7fd56c7f5b8d0b935234710d573234c22bc37a8e6baac","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIICATCCAaigAwIBAgIUEUVSn1hCPY+58LjvJ3I7Lmf3ZI8wCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTkwMzE5MDgxMDAwWhcNMjAwMzE4MDgx\nNTAwWjAhMQ8wDQYDVQQLEwZjbGllbnQxDjAMBgNVBAMTBWFkbWluMFkwEwYHKoZI\nzj0CAQYIKoZIzj0DAQcDQgAE3Zk9xLh8DrgXFfxFkvKOnkYBMRxEGx2GQMaVTOVW\nGovFBJRm3Ngvp+jZ1fWc5TEiTe3oNQFmloPe3HD3PW0QzqNsMGowDgYDVR0PAQH/\nBAQDAgeAMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFLCKLsOVHbg2hXq92LBp5jCd\njNzYMCsGA1UdIwQkMCKAIEI5qg3NdtruuLoM2nAYUdFFBNMarRst3dusalc2Xkl8\nMAoGCCqGSM49BAMCA0cAMEQCICnpF9fYDEWfb69goCT/2Wk84QxHdY3ORG0ckpp8\nfCbqAiA0P4MIHoOeXf1q3FEuGsZwsRSqhnnCAbQjjICh+DOXgg==\n-----END CERTIFICATE-----\n"}}}
2 changes: 1 addition & 1 deletion test/resources/persistence/config.db
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"id":0,"isSign":1,"_id":"0RYjfGm5ZQNGBcxV","peerGrpcUrl":"grpc://localhost:7051","peerEventUrl":"grpc://localhost:7053","ordererUrl":"grpc://localhost:7050","mspid":"Org1MSP","tlsPeerPath":"","tlsOrdererPath":"","path":"test/resources/key/users/"}
{"id":0,"isSign":1,"_id":"0RYjfGm5ZQNGBcxV","peerGrpcUrl":"grpc://localhost:7051","peerEventUrl":"grpc://localhost:7053","ordererUrl":"grpc://localhost:7050","mspid":"Org1MSP","tlsPeerPath":"","tlsOrdererPath":"","path":"test/resources/key/users/","caServerUrl":"http://localhost:7054"}
Loading

0 comments on commit 51d4cbe

Please sign in to comment.