Skip to content

Commit

Permalink
Merge pull request blockchain-desktop#194 from dengyi9/master
Browse files Browse the repository at this point in the history
 Test case: fabricClient. blockchain-desktop#49
  • Loading branch information
dengyi9 authored Mar 8, 2019
2 parents 931e534 + 9cc3f41 commit 6e49f75
Show file tree
Hide file tree
Showing 2 changed files with 163 additions and 75 deletions.
106 changes: 55 additions & 51 deletions src/util/fabric.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,54 +14,54 @@ const logger = require('electron-log');

class FabricClient {
constructor() {
const fabricClient = new FabricClientSDK();
this.fabric_client = fabricClient;
this.fabricClient = new FabricClientSDK();
}

// 抽出空挡,插入配置文件,以便集成测试
_getConfig(configDb) {
const self = this;
return new Promise((resolve, reject) => {
configDb.find({}, (err, resultList) => {
if (err) {
logger.info('the operation of find documents failed!');
reject('error');
}
logger.info('success get config!');
const output = {
result: resultList,
obj: self,
};
resolve(output);
logger.info('result:', resultList);
logger.info('success get config!', ' result:', resultList);
resolve(resultList);
});
});
}

_config(input) {
const obj = input.obj;
const config = input[0];
const self = this;
const fabricClient = this.fabricClient;
return new Promise((resolve) => {
logger.info('input:', input.result);
const config = input.result[0];

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

logger.info('config:', config);
const storePath = path.join(__dirname, '../../', config.path);
logger.info(`Store path:${storePath}`);
obj.config = config;
obj.store_path = storePath;
obj.channels = {};
self.config = config;
self.store_path = storePath;
self.channels = {};

resolve(obj);
resolve();
});
}

Expand All @@ -70,22 +70,26 @@ class FabricClient {
* @returns {Promise<Client.User | never>}
*
*/
_enrollUser(self) {
_enrollUser() {
const self = this;
const usrName = self.config.mspid;
// logger.info('start to load member user.');
logger.info('start to load member user.', ' store_path: ', self.store_path);
return FabricClientSDK.newDefaultKeyValueStore({ path: self.store_path,
}).then((stateStore) => {
logger.info('get stateStore: ', stateStore);

// assign the store to the fabric client
self.fabric_client.setStateStore(stateStore);
self.fabricClient.setStateStore(stateStore);
const cryptoSuite = FabricClientSDK.newCryptoSuite();

// use the same location for the state store (where the users' certificate are kept)
// and the crypto store (where the users' keys are kept)
const cryptoStore = FabricClientSDK.newCryptoKeyStore({ path: self.store_path });
cryptoSuite.setCryptoKeyStore(cryptoStore);
self.fabric_client.setCryptoSuite(cryptoSuite);
self.fabricClient.setCryptoSuite(cryptoSuite);

return self.fabric_client.getUserContext(usrName, true);
logger.info('almost done');
return self.fabricClient.getUserContext(usrName, true);
});
}

Expand All @@ -99,21 +103,14 @@ class FabricClient {
let channel = this.channels[channelName];
if (!channel) {
logger.info('start create channel');
channel = this.fabric_client.newChannel(channelName);

channel = this.fabricClient.newChannel(channelName);
if (this.flag) {
logger.info('-----------');
this.peer = this.fabric_client.newPeer(this.config.peerGrpcUrl,
{ pem: Buffer.from(this.peerCert).toString(), 'ssl-target-name-override': this.config.peerSSLTarget });
channel.addPeer(this.peer);
this.order = this.fabric_client.newOrderer(this.config.ordererUrl,
{ pem: Buffer.from(this.orderersCert).toString(), 'ssl-target-name-override': this.config.ordererSSLTarget });
channel.addOrderer(this.order);
} else {
logger.info('+++++++++++++++++');
this.peer = this.fabric_client.newPeer(this.config.peerGrpcUrl);
channel.addPeer(this.peer);
this.order = this.fabric_client.newOrderer(this.config.ordererUrl);
channel.addOrderer(this.order);
}
this.channels[channelName] = channel;
Expand Down Expand Up @@ -195,7 +192,7 @@ class FabricClient {
return Promise.reject(err);
}
let txID;
const fabricClient = this.fabric_client;
const fabricClient = this.fabricClient;
const self = this;
return this._enrollUser(this).then((user) => {
if (user && user.isEnrolled()) {
Expand All @@ -212,7 +209,7 @@ class FabricClient {
tempTargets.push(self.peer);
for (let i = 0; i < peerList.length; i++) {
const peerCert = fs.readFileSync(certList[i]);
const peer = self.fabric_client.newPeer((peerList[i]),
const peer = self.fabricClient.newPeer((peerList[i]),
{ pem: Buffer.from(peerCert).toString(), 'ssl-target-name-override': sslTargetList[i] });
tempTargets.push(peer);
}
Expand Down Expand Up @@ -342,15 +339,16 @@ class FabricClient {
* @param chaincodeVersion
*/
installCc(chaincodePath, chaincodeName, chaincodeVersion) {
logger.info(`${chaincodePath}, ${chaincodeName}, ${chaincodeVersion}`);
logger.info(`installing chaincode: ${chaincodePath}, ${chaincodeName}, ${chaincodeVersion}`);

const request = {
targets: [this.peer], // peerAddress
chaincodePath,
chaincodeId: chaincodeName,
chaincodeVersion,
};
return this.fabric_client.installChaincode(request)
logger.info('installChaincode request param: ', request);
return this.fabricClient.installChaincode(request)
.then((results) => {
const proposalResponses = results[0];
if (proposalResponses && proposalResponses[0].response &&
Expand Down Expand Up @@ -393,7 +391,7 @@ class FabricClient {
}
logger.info('args: ', args, '&& endors-policy:', endorspolicy);

const txID = this.fabric_client.newTransactionID();
const txID = this.fabricClient.newTransactionID();

let endorspolicyObj;
let argsObj;
Expand Down Expand Up @@ -445,7 +443,7 @@ class FabricClient {
return Promise.resolve('success');
}, (err) => {
logger.info('Failed instantiating chaincode.', err.stack);
return Promise.resolve('fail');
return Promise.reject('fail');
})
.catch((err) => {
logger.error(`Fail to instantiate chaincode. Error message: ${err.stack}` ? err.stack : err);
Expand Down Expand Up @@ -497,7 +495,7 @@ class FabricClient {
importCer(keyPath, certPath) {
// -------------------- admin start ---------
logger.info('start to create admin user.');
return this.fabric_client.createUser({
return this.fabricClient.createUser({
username: this.config.mspid,
mspid: this.config.mspid,
cryptoContent: {
Expand Down Expand Up @@ -533,7 +531,7 @@ class FabricClient {
logger.error(err);
return Promise.reject('fail');
}
return this.fabric_client.queryInstalledChaincodes(this.peer)
return this.fabricClient.queryInstalledChaincodes(this.peer)
.then((response) => {
if (response) {
logger.info('Successfully get response from fabric client');
Expand Down Expand Up @@ -597,7 +595,7 @@ class FabricClient {
return Promise.reject('fail');
}
const self = this;
return self.fabric_client.queryChannels(self.peer)
return self.fabricClient.queryChannels(self.peer)
.then((response) => {
if (response) {
logger.info('Successfully get response from fabric client');
Expand Down Expand Up @@ -661,10 +659,10 @@ class FabricClient {
return Promise.reject('fail');
}

const tempTxId = self.fabric_client.newTransactionID();
const tempTxId = self.fabricClient.newTransactionID();
const envelopeBytes = fs.readFileSync(path.join(__dirname, '../../resources/key/tx/' + channelName + '.tx'));
const tempConfig = self.fabric_client.extractChannelConfig(envelopeBytes);
const signature = self.fabric_client.signChannelConfig(tempConfig);
const tempConfig = self.fabricClient.extractChannelConfig(envelopeBytes);
const signature = self.fabricClient.signChannelConfig(tempConfig);
const stringSignature = signature.toBuffer().toString('hex');
const tempSignatures = [];
tempSignatures.push(stringSignature);
Expand All @@ -675,7 +673,7 @@ class FabricClient {
orderer: self.order,
txId: tempTxId,
};
return self.fabric_client.createChannel(request);
return self.fabricClient.createChannel(request);
})
.then((result) => {
logger.info(' response ::%j', result);
Expand Down Expand Up @@ -707,7 +705,7 @@ class FabricClient {
}
const self = this;

const tempTxId = self.fabric_client.newTransactionID(); // 根据用户的证书构建新的事务ID,并自动生成nonce值。
const tempTxId = self.fabricClient.newTransactionID(); // 根据用户的证书构建新的事务ID,并自动生成nonce值。
const request = {
txId: tempTxId,
};
Expand All @@ -719,7 +717,7 @@ class FabricClient {
const tempTargets = [];
tempTargets.push(self.peer);
const genesisBlock = block;
const _tempTxId = self.fabric_client.newTransactionID();
const _tempTxId = self.fabricClient.newTransactionID();
const _request = {
targets: tempTargets,
block: genesisBlock,
Expand Down Expand Up @@ -768,7 +766,13 @@ class FabricClient {
* @param opts 对象
*/
newPeer(url, opts) {
return this.fabric_client.newPeer(url, opts);
return this.fabricClient.newPeer(url, opts);
}

// 关闭连接
close() {
this.peer.close();
this.order.close();
}
}

Expand All @@ -780,8 +784,8 @@ export function getFabricClientSingletonHelper(dbConfig) {
logger.info('instantiating fabric client.');
__fabricClient = new FabricClient();
return __fabricClient._getConfig(dbConfig)
.then(__fabricClient._config)
.then(__fabricClient._enrollUser)
.then(input => __fabricClient._config(input))
.then(() => __fabricClient._enrollUser())
.then(() => Promise.resolve(__fabricClient));
}
return Promise.resolve(__fabricClient);
Expand Down
Loading

0 comments on commit 6e49f75

Please sign in to comment.