HyperledgerFabric中Chaincode的Invoke功能怎么用
这篇文章主要介绍Hyperledger Fabric中Chaincode的Invoke功能怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
创新互联公司是一家专业提供正宁企业网站建设,专注与做网站、成都网站制作、H5技术、小程序制作等业务。10年已为正宁众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。
Chaincode的Invoke 功能, 主要包括create, update, delete功能。
完整的实例代码如下:
'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 network var 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' setting Fabric_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); });
这段代码主要功能有两个, 一个是提交交易, 一个是获取交易结果。 关于Hyperledger Fabric 的交易流程的介绍在这里, 主要包括6个步骤。
其实, 对于客户端来说, 交易过程需要干两件事:
1 向背书节点发送交易提案
2 获取背书节点对交易提案的反馈, 并组装交易, 向orderer节点发送交易
而对于交易结果的获取, Hyperledger Fabric 是通过事件机制实现的。
通过fabric_client生成一个EventHub对象, 然后通过event_hub对象注册事件获取, 详细介绍见 Hyperledger Fabric SDK for node.js Class: EventHub 。
从文档可以看出, EventHub可以注册的事件有:
registerBlockEvent(onEvent, onError) 区块事件
registerChaincodeEvent(ccid, eventname, onEvent, onError) 链码事件
registerTxEvent(txid, onEvent, onError) 交易事件
首先看交易过程。交易包括发送提案和发送交易两个过程。交易过程主要封装请求链码的参数, 发送请求到背书节点, 代码如下:
// 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: 'createCar', args: ['CAR100', 'Honda', 'Accord', 'Black', 'Jarvis'], chainId: 'mychannel', txId: tx_id }; // send the transaction proposal to the peers return channel.sendTransactionProposal(request);
首先, 获取一个和当前用户关联的transaction id 对象, 该对象的定义在这里 。该方法 可以传入一个参数 boolean,默认为false, 如果为true, 则根据admin 用户的证书生成tansaction id 对象。
接下来构造sendTransactionProposal参数, 也就是提案的请求对象, 参数对象的定义在这里 。 这里需要注意的是chaincodeId, chainId, txId 是必须, 用来指定已经安装(intall)并且实例化(initantiate)的chaincode。 fcn 对应链码中定义的业务逻辑, 默认为invoke, args是fcn对应的参数, 所有的args格式都是一样的, 是一个string 数组。
参数构造完成, 就可以向背书节点发送交易提案了。执行成功的话, 返回提案结果对象, 实际上是https://fabric-sdk-node.github.io/global.html#ProposalResponseObject 对象。
接下来, 提交交易到orderer节点。
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);
首先判断提案交易是不是成功
if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) {
如果成功, 构建交易参数, 并提交交易。参数的定义见: Hyperledger Fabric SDK for node.js Global 。包括提案执行的结果。
获取交易结果是通过事件机制实现的, 需要用到交易的tansaction id .在代码中是通过EventHub对象实现的。
具体步骤包括:
1 创建 EventHub对象
let event_hub = fabric_client.newEventHub(); event_hub.setPeerAddr('grpc://localhost:7053');
2 获取一个事件源的连接
event_hub.connect();
3 注册并监听事件
Fabric提供的事件对象有:registerBlockEvent, registerTxEvent 和 registerChaincodeEvent . 这里只关注registerTxEvent事件。
event_hub.registerTxEvent(transaction_id_string, (tx, code) => { //......
详细文档查看 Hyperledger Fabric SDK for node.js Class: EventHub 。第一个参数为 上文提到的transaction id 字符串, 第二个参数是一个回调函数, 有两个参数, 第一个是一个Transaction对象, 第二个是一个字符串, 表示交易是否valid状态的字符串。
4 断开连接
event_hub.disconnect();
以上是“Hyperledger Fabric中Chaincode的Invoke功能怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!
文章题目:HyperledgerFabric中Chaincode的Invoke功能怎么用
网址分享:http://azwzsj.com/article/ipsdeo.html