博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hyperledger Fabric 客户端开发二
阅读量:7075 次
发布时间:2019-06-28

本文共 18280 字,大约阅读时间需要 60 分钟。

hot3.png

由于知乎文章字数限制, 接 , 继续介绍Hyperledger Fabric 的客户端开发。

 

上篇文章中, 主要介绍了Hyperledger Fabric 的 SDK相关的知识, 其中, 重点介绍了Node SDK的功能, 并通过一个fabcar的实例,说明Fabric 客户端开发, 其中使用Node实现了Chaincode。 接下来, 我们通过使用Node SDK来说明如何与Blockchain进行交互。

 

由于Fabric是企业级的区块链平台, 对安全性要求极高, Fabric的所有请求都必须具有有效注册证书的数字签名。 其安全性是通过数字签名来实现的, Fabric默认提供了一个可选的Fabric CA实现。

 

因此, 我们的客户端实现也分为一下几个步骤:

1 登记admin并获取Fabric CA签署的登记证书

'use strict';/** Copyright IBM Corp All Rights Reserved** SPDX-License-Identifier: Apache-2.0*//* * Chaincode Invoke */var Fabric_Client = require('fabric-client');var path = require('path');var util = require('util');var os = require('os');//var fabric_client = new Fabric_Client();// setup the fabric networkvar channel = fabric_client.newChannel('mychannel');var peer = fabric_client.newPeer('grpc://localhost:7051');channel.addPeer(peer);var order = fabric_client.newOrderer('grpc://localhost:7050')channel.addOrderer(order);//var member_user = null;var store_path = path.join(__dirname, 'hfc-key-store');console.log('Store path:'+store_path);var tx_id = null;// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' settingFabric_Client.newDefaultKeyValueStore({ path: store_path}).then((state_store) => {	// assign the store to the fabric client	fabric_client.setStateStore(state_store);	var crypto_suite = Fabric_Client.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)	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});	crypto_suite.setCryptoKeyStore(crypto_store);	fabric_client.setCryptoSuite(crypto_suite);	// get the enrolled user from persistence, this user will sign all requests	return fabric_client.getUserContext('user1', true);}).then((user_from_store) => {	if (user_from_store && user_from_store.isEnrolled()) {		console.log('Successfully loaded user1 from persistence');		member_user = user_from_store;	} else {		throw new Error('Failed to get user1.... run registerUser.js');	}	// get a transaction id object based on the current user assigned to fabric client	tx_id = fabric_client.newTransactionID();	console.log("Assigning transaction_id: ", tx_id._transaction_id);	// createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],	// changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],	// must send the proposal to endorsing peers	var request = {		//targets: let default to the peer assigned to the client		chaincodeId: 'fabcar',		fcn: '',		args: [''],		chainId: 'mychannel',		txId: tx_id	};	// send the transaction proposal to the peers	return channel.sendTransactionProposal(request);}).then((results) => {	var proposalResponses = results[0];	var proposal = results[1];	let isProposalGood = false;	if (proposalResponses && proposalResponses[0].response &&		proposalResponses[0].response.status === 200) {			isProposalGood = true;			console.log('Transaction proposal was good');		} else {			console.error('Transaction proposal was bad');		}	if (isProposalGood) {		console.log(util.format(			'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s"',			proposalResponses[0].response.status, proposalResponses[0].response.message));		// build up the request for the orderer to have the transaction committed		var request = {			proposalResponses: proposalResponses,			proposal: proposal		};		// set the transaction listener and set a timeout of 30 sec		// if the transaction did not get committed within the timeout period,		// report a TIMEOUT status		var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing		var promises = [];		var sendPromise = channel.sendTransaction(request);		promises.push(sendPromise); //we want the send transaction first, so that we know where to check status		// get an eventhub once the fabric client has a user assigned. The user		// is required bacause the event registration must be signed		let event_hub = fabric_client.newEventHub();		event_hub.setPeerAddr('grpc://localhost:7053');		// using resolve the promise so that result status may be processed		// under the then clause rather than having the catch clause process		// the status		let txPromise = new Promise((resolve, reject) => {			let handle = setTimeout(() => {				event_hub.disconnect();				resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));			}, 3000);			event_hub.connect();			event_hub.registerTxEvent(transaction_id_string, (tx, code) => {				// this is the callback for transaction event status				// first some clean up of event listener				clearTimeout(handle);				event_hub.unregisterTxEvent(transaction_id_string);				event_hub.disconnect();				// now let the application know what happened				var return_status = {event_status : code, tx_id : transaction_id_string};				if (code !== 'VALID') {					console.error('The transaction was invalid, code = ' + code);					resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));				} else {					console.log('The transaction has been committed on peer ' + event_hub._ep._endpoint.addr);					resolve(return_status);				}			}, (err) => {				//this is the callback if something goes wrong with the event registration or processing				reject(new Error('There was a problem with the eventhub ::'+err));			});		});		promises.push(txPromise);		return Promise.all(promises);	} else {		console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');		throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');	}}).then((results) => {	console.log('Send transaction promise and event listener promise have completed');	// check the results in the order the promises were added to the promise all list	if (results && results[0] && results[0].status === 'SUCCESS') {		console.log('Successfully sent transaction to the orderer.');	} else {		console.error('Failed to order the transaction. Error code: ' + results[0].status);	}	if(results && results[1] && results[1].event_status === 'VALID') {		console.log('Successfully committed the change to the ledger by the peer');	} else {		console.log('Transaction failed to be committed to the ledger due to ::'+results[1].event_status);	}}).catch((err) => {	console.error('Failed to invoke successfully :: ' + err);});

 

2 注册用户并获取证书

'use strict';/** Copyright IBM Corp All Rights Reserved** SPDX-License-Identifier: Apache-2.0*//* * Register and Enroll a user */var Fabric_Client = require('fabric-client');var Fabric_CA_Client = require('fabric-ca-client');var path = require('path');var util = require('util');var os = require('os');//var fabric_client = new Fabric_Client();var fabric_ca_client = null;var admin_user = null;var member_user = null;var store_path = path.join(__dirname, 'hfc-key-store');console.log(' Store path:'+store_path);// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' settingFabric_Client.newDefaultKeyValueStore({ path: store_path}).then((state_store) => {    // assign the store to the fabric client    fabric_client.setStateStore(state_store);    var crypto_suite = Fabric_Client.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)    var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});    crypto_suite.setCryptoKeyStore(crypto_store);    fabric_client.setCryptoSuite(crypto_suite);    var	tlsOptions = {    	trustedRoots: [],    	verify: false    };    // be sure to change the http to https when the CA is running TLS enabled    fabric_ca_client = new Fabric_CA_Client('http://localhost:7054', null , '', crypto_suite);    // first check to see if the admin is already enrolled    return fabric_client.getUserContext('admin', true);}).then((user_from_store) => {    if (user_from_store && user_from_store.isEnrolled()) {        console.log('Successfully loaded admin from persistence');        admin_user = user_from_store;    } else {        throw new Error('Failed to get admin.... run enrollAdmin.js');    }    // at this point we should have the admin user    // first need to register the user with the CA server    return fabric_ca_client.register({enrollmentID: 'user1', affiliation: 'org1.department1',role: 'client'}, admin_user);}).then((secret) => {    // next we need to enroll the user with CA server    console.log('Successfully registered user1 - secret:'+ secret);    return fabric_ca_client.enroll({enrollmentID: 'user1', enrollmentSecret: secret});}).then((enrollment) => {  console.log('Successfully enrolled member user "user1" ');  return fabric_client.createUser(     {username: 'user1',     mspid: 'Org1MSP',     cryptoContent: { privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: enrollment.certificate }     });}).then((user) => {     member_user = user;     return fabric_client.setUserContext(member_user);}).then(()=>{     console.log('User1 was successfully registered and enrolled and is ready to interact with the fabric network');}).catch((err) => {    console.error('Failed to register: ' + err);	if(err.toString().indexOf('Authorization') > -1) {		console.error('Authorization failures may be caused by having admin credentials from a previous CA instance.\n' +		'Try again after deleting the contents of the store directory '+store_path);	}});

3 发送交易改变Blockchain状态

'use strict';/* * Chaincode Invoke */var Fabric_Client = require('fabric-client');var path = require('path');var util = require('util');var os = require('os');//var fabric_client = new Fabric_Client();// setup the fabric networkvar channel = fabric_client.newChannel('mychannel');var peer = fabric_client.newPeer('grpc://localhost:7051');channel.addPeer(peer);var order = fabric_client.newOrderer('grpc://localhost:7050')channel.addOrderer(order);//var member_user = null;var store_path = path.join(__dirname, 'hfc-key-store');console.log('Store path:'+store_path);var tx_id = null;// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' settingFabric_Client.newDefaultKeyValueStore({ path: store_path}).then((state_store) => {	// assign the store to the fabric client	fabric_client.setStateStore(state_store);	var crypto_suite = Fabric_Client.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)	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});	crypto_suite.setCryptoKeyStore(crypto_store);	fabric_client.setCryptoSuite(crypto_suite);	// get the enrolled user from persistence, this user will sign all requests	return fabric_client.getUserContext('user1', true);}).then((user_from_store) => {	if (user_from_store && user_from_store.isEnrolled()) {		console.log('Successfully loaded user1 from persistence');		member_user = user_from_store;	} else {		throw new Error('Failed to get user1.... run registerUser.js');	}	// get a transaction id object based on the current user assigned to fabric client	tx_id = fabric_client.newTransactionID();	console.log("Assigning transaction_id: ", tx_id._transaction_id);	// createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],	// changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],	// must send the proposal to endorsing peers	var request = {		//targets: let default to the peer assigned to the client		chaincodeId: 'fabcar',		fcn: '',		args: [''],		chainId: 'mychannel',		txId: tx_id	};	// send the transaction proposal to the peers	return channel.sendTransactionProposal(request);}).then((results) => {	var proposalResponses = results[0];	var proposal = results[1];	let isProposalGood = false;	if (proposalResponses && proposalResponses[0].response &&		proposalResponses[0].response.status === 200) {			isProposalGood = true;			console.log('Transaction proposal was good');		} else {			console.error('Transaction proposal was bad');		}	if (isProposalGood) {		console.log(util.format(			'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s"',			proposalResponses[0].response.status, proposalResponses[0].response.message));		// build up the request for the orderer to have the transaction committed		var request = {			proposalResponses: proposalResponses,			proposal: proposal		};		// set the transaction listener and set a timeout of 30 sec		// if the transaction did not get committed within the timeout period,		// report a TIMEOUT status		var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing		var promises = [];		var sendPromise = channel.sendTransaction(request);		promises.push(sendPromise); //we want the send transaction first, so that we know where to check status		// get an eventhub once the fabric client has a user assigned. The user		// is required bacause the event registration must be signed		let event_hub = fabric_client.newEventHub();		event_hub.setPeerAddr('grpc://localhost:7053');		// using resolve the promise so that result status may be processed		// under the then clause rather than having the catch clause process		// the status		let txPromise = new Promise((resolve, reject) => {			let handle = setTimeout(() => {				event_hub.disconnect();				resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));			}, 3000);			event_hub.connect();			event_hub.registerTxEvent(transaction_id_string, (tx, code) => {				// this is the callback for transaction event status				// first some clean up of event listener				clearTimeout(handle);				event_hub.unregisterTxEvent(transaction_id_string);				event_hub.disconnect();				// now let the application know what happened				var return_status = {event_status : code, tx_id : transaction_id_string};				if (code !== 'VALID') {					console.error('The transaction was invalid, code = ' + code);					resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));				} else {					console.log('The transaction has been committed on peer ' + event_hub._ep._endpoint.addr);					resolve(return_status);				}			}, (err) => {				//this is the callback if something goes wrong with the event registration or processing				reject(new Error('There was a problem with the eventhub ::'+err));			});		});		promises.push(txPromise);		return Promise.all(promises);	} else {		console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');		throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');	}}).then((results) => {	console.log('Send transaction promise and event listener promise have completed');	// check the results in the order the promises were added to the promise all list	if (results && results[0] && results[0].status === 'SUCCESS') {		console.log('Successfully sent transaction to the orderer.');	} else {		console.error('Failed to order the transaction. Error code: ' + results[0].status);	}	if(results && results[1] && results[1].event_status === 'VALID') {		console.log('Successfully committed the change to the ledger by the peer');	} else {		console.log('Transaction failed to be committed to the ledger due to ::'+results[1].event_status);	}}).catch((err) => {	console.error('Failed to invoke successfully :: ' + err);});

4 查询Blockchain

'use strict';/* * Chaincode query */var Fabric_Client = require('fabric-client');var path = require('path');var util = require('util');var os = require('os');//var fabric_client = new Fabric_Client();// setup the fabric networkvar channel = fabric_client.newChannel('mychannel');var peer = fabric_client.newPeer('grpc://localhost:7051');channel.addPeer(peer);//var member_user = null;var store_path = path.join(__dirname, 'hfc-key-store');console.log('Store path:'+store_path);var tx_id = null;// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' settingFabric_Client.newDefaultKeyValueStore({ path: store_path}).then((state_store) => {	// assign the store to the fabric client	fabric_client.setStateStore(state_store);	var crypto_suite = Fabric_Client.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)	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});	crypto_suite.setCryptoKeyStore(crypto_store);	fabric_client.setCryptoSuite(crypto_suite);	// get the enrolled user from persistence, this user will sign all requests	return fabric_client.getUserContext('user1', true);}).then((user_from_store) => {	if (user_from_store && user_from_store.isEnrolled()) {		console.log('Successfully loaded user1 from persistence');		member_user = user_from_store;	} else {		throw new Error('Failed to get user1.... run registerUser.js');	}	// queryCar chaincode function - requires 1 argument, ex: args: ['CAR4'],	// queryAllCars chaincode function - requires no arguments , ex: args: [''],	const request = {		//targets : --- letting this default to the peers assigned to the channel		chaincodeId: 'fabcar',		fcn: 'queryAllCars',		args: ['']	};	// send the query proposal to the peer	return channel.queryByChaincode(request);}).then((query_responses) => {	console.log("Query has completed, checking results");	// query_responses could have more than one  results if there multiple peers were used as targets	if (query_responses && query_responses.length == 1) {		if (query_responses[0] instanceof Error) {			console.error("error from query = ", query_responses[0]);		} else {			console.log("Response is ", query_responses[0].toString());		}	} else {		console.log("No payloads were returned from query");	}}).catch((err) => {	console.error('Failed to query successfully :: ' + err);});

转载于:https://my.oschina.net/kingwjb/blog/1861508

你可能感兴趣的文章
我的友情链接
查看>>
thinkphp 生成 excel 文件
查看>>
free()
查看>>
Sort Array By Parity
查看>>
部署 Lync 2010 移动电话(Internal)
查看>>
Android应用程序在新的进程中启动新的Activity的方法和过程分析
查看>>
解析DELL R710服务器迁移操作内容
查看>>
parted用法
查看>>
转 > map和reduce 个数的设定 (Hive优化)经典
查看>>
eclipse安装pydev插件时没有任何错误提示,但是就是装完了后不显示pydev的设置项...
查看>>
IDC:中国安全市场发展潜力巨大
查看>>
javaScript中的this指针
查看>>
arp简析
查看>>
Cookbook系列之Cpp:杂项
查看>>
第八章 前七章总结考试
查看>>
Linux 服务器的安装规划
查看>>
我的友情链接
查看>>
一次union all 的优化
查看>>
设计师必看的8个TED 演讲
查看>>
python from-import语句用法
查看>>