[英]Can i generate Events in hyperledger-fabric?
我之前曾在Ethereum上工作,當調用函數或更改狀態時可以生成“事件”,並且可以通過觀察狀態更改從應用程序捕獲這些事件。 Hyperledger有這個功能嗎? 我可以在hyperledger-fabric中看到“事件”但是如何在狀態發生變化時生成我自己的事件並在節點應用中捕獲它們?
在Hyperledger Fabric中有一個名為的shim.ChaincodeStubInterface
API方法:
// SetEvent allows the chaincode to set an event on the response to the
// proposal to be included as part of a transaction. The event will be
// available within the transaction in the committed block regardless of the
// validity of the transaction.
SetEvent(name string, payload []byte) error
它允許您在調用鏈代碼(aka smartcontract)期間指定事件。 之后您可以注冊到活動中心以獲取這些活動。
您可以在鏈代碼中設置事件,如以下代碼所示:
APIstub.SetEvent("evtsender", []byte("abcdef"))
然后在用於執行查詢的文件中,您應該使用registerChaincodeEvent()
; 見官方文檔:
https://fabric-sdk-node.github.io/EventHub.html#registerChaincodeEvent__anchor
這可能是一個例子:
let event_monitor = new Promise((resolve, reject) => {
let regid = null;
let handle = setTimeout(() => {
if (regid) {
// might need to do the clean up this listener
eh.unregisterChaincodeEvent(regid);
console.log('Timeout - Failed to receive the chaincode event');
}
reject(new Error('Timed out waiting for chaincode event'));
}, 20000);
eh.connect();
regid = eh.registerChaincodeEvent('fabcar', 'evtsender',
(event, block_num, txnid, status) => {
// This callback will be called when there is a chaincode event name
// within a block that will match on the second parameter in the registration
// from the chaincode with the ID of the first parameter.
console.log('Successfully got a chaincode event with transid:' + txnid + ' with status:' + status);
// might be good to store the block number to be able to resume if offline
storeBlockNumForLater(block_num);
// to see the event payload, the channel_event_hub must be connected(true)
let event_payload = event.payload.toString('utf8');
if (event_payload.indexOf('CHAINCODE') > -1) {
clearTimeout(handle);
// Chaincode event listeners are meant to run continuously
// Therefore the default to automatically unregister is false
// So in this case we want to shutdown the event listener once
// we see the event with the correct payload
event_hub.unregisterChaincodeEvent(regid);
console.log('Successfully received the chaincode event on block number ' + block_num);
resolve('RECEIVED');
} else {
console.log('Successfully got chaincode event ... just not the one we are looking for on block number ' + block_num);
}
}, (error) => {
clearTimeout(handle);
console.log('Failed to receive the chaincode event ::' + error);
reject(error);
}
// no options specified
// startBlock will default to latest
// endBlock will default to MAX
// unregister will default to false
// disconnect will default to false
);
})
無論如何,我在測試它時遇到了一些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.