這篇文章主要介紹Hyperledger Fabric中Chaincode的Invoke功能怎么用,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)公司是一家專業(yè)提供正寧企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、成都網(wǎng)站制作、H5技術(shù)、小程序制作等業(yè)務(wù)。10年已為正寧眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計(jì)公司優(yōu)惠進(jìn)行中。
Chaincode的Invoke 功能, 主要包括create, update, delete功能。
完整的實(shí)例代碼如下:
'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);
});這段代碼主要功能有兩個(gè), 一個(gè)是提交交易, 一個(gè)是獲取交易結(jié)果。 關(guān)于Hyperledger Fabric 的交易流程的介紹在這里, 主要包括6個(gè)步驟。
其實(shí), 對(duì)于客戶端來(lái)說(shuō), 交易過(guò)程需要干兩件事:
1 向背書節(jié)點(diǎn)發(fā)送交易提案
2 獲取背書節(jié)點(diǎn)對(duì)交易提案的反饋, 并組裝交易, 向orderer節(jié)點(diǎn)發(fā)送交易
而對(duì)于交易結(jié)果的獲取, Hyperledger Fabric 是通過(guò)事件機(jī)制實(shí)現(xiàn)的。
通過(guò)fabric_client生成一個(gè)EventHub對(duì)象, 然后通過(guò)event_hub對(duì)象注冊(cè)事件獲取, 詳細(xì)介紹見(jiàn) Hyperledger Fabric SDK for node.js Class: EventHub 。
從文檔可以看出, EventHub可以注冊(cè)的事件有:
registerBlockEvent(onEvent, onError) 區(qū)塊事件
registerChaincodeEvent(ccid, eventname, onEvent, onError) 鏈碼事件
registerTxEvent(txid, onEvent, onError) 交易事件
首先看交易過(guò)程。交易包括發(fā)送提案和發(fā)送交易兩個(gè)過(guò)程。交易過(guò)程主要封裝請(qǐng)求鏈碼的參數(shù), 發(fā)送請(qǐng)求到背書節(jié)點(diǎn), 代碼如下:
// 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);首先, 獲取一個(gè)和當(dāng)前用戶關(guān)聯(lián)的transaction id 對(duì)象, 該對(duì)象的定義在這里 。該方法 可以傳入一個(gè)參數(shù) boolean,默認(rèn)為false, 如果為true, 則根據(jù)admin 用戶的證書生成tansaction id 對(duì)象。
接下來(lái)構(gòu)造sendTransactionProposal參數(shù), 也就是提案的請(qǐng)求對(duì)象, 參數(shù)對(duì)象的定義在這里 。 這里需要注意的是chaincodeId, chainId, txId 是必須, 用來(lái)指定已經(jīng)安裝(intall)并且實(shí)例化(initantiate)的chaincode。 fcn 對(duì)應(yīng)鏈碼中定義的業(yè)務(wù)邏輯, 默認(rèn)為invoke, args是fcn對(duì)應(yīng)的參數(shù), 所有的args格式都是一樣的, 是一個(gè)string 數(shù)組。
參數(shù)構(gòu)造完成, 就可以向背書節(jié)點(diǎn)發(fā)送交易提案了。執(zhí)行成功的話, 返回提案結(jié)果對(duì)象, 實(shí)際上是https://fabric-sdk-node.github.io/global.html#ProposalResponseObject 對(duì)象。
接下來(lái), 提交交易到orderer節(jié)點(diǎn)。
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) {如果成功, 構(gòu)建交易參數(shù), 并提交交易。參數(shù)的定義見(jiàn): Hyperledger Fabric SDK for node.js Global 。包括提案執(zhí)行的結(jié)果。
獲取交易結(jié)果是通過(guò)事件機(jī)制實(shí)現(xiàn)的, 需要用到交易的tansaction id .在代碼中是通過(guò)EventHub對(duì)象實(shí)現(xiàn)的。
具體步驟包括:
1 創(chuàng)建 EventHub對(duì)象
let event_hub = fabric_client.newEventHub();
event_hub.setPeerAddr('grpc://localhost:7053');2 獲取一個(gè)事件源的連接
event_hub.connect();
3 注冊(cè)并監(jiān)聽(tīng)事件
Fabric提供的事件對(duì)象有:registerBlockEvent, registerTxEvent 和 registerChaincodeEvent . 這里只關(guān)注registerTxEvent事件。
event_hub.registerTxEvent(transaction_id_string, (tx, code) => {
//......詳細(xì)文檔查看 Hyperledger Fabric SDK for node.js Class: EventHub 。第一個(gè)參數(shù)為 上文提到的transaction id 字符串, 第二個(gè)參數(shù)是一個(gè)回調(diào)函數(shù), 有兩個(gè)參數(shù), 第一個(gè)是一個(gè)Transaction對(duì)象, 第二個(gè)是一個(gè)字符串, 表示交易是否valid狀態(tài)的字符串。
4 斷開(kāi)連接
event_hub.disconnect();
以上是“Hyperledger Fabric中Chaincode的Invoke功能怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享標(biāo)題:HyperledgerFabric中Chaincode的Invoke功能怎么用
當(dāng)前URL:http://chinadenli.net/article40/ipsdeo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、網(wǎng)站策劃、云服務(wù)器、面包屑導(dǎo)航、App開(kāi)發(fā)、定制開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)