Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use channel-based event service for Hyperledger Fabric Node.js

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how Hyperledger Fabric Node.js uses channel-based event services, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

Overview

Client applications can use the Fabric Node.js client to register listeners to receive blocks when they are added to the channel ledger. We call these "channel-based events," and they allow clients to start receiving blocks from specific block numbers, allowing event processing to work properly on blocks that may have been lost. The Fabric Node.js client can also assist client applications by processing incoming blocks and looking for specific transaction or chain code events. This allows client applications to be notified of transaction completion or arbitrary chain code events without having to execute multiple queries or search blocks when receiving.

The service allows any user to receive "filtered" block events (in other words, does not contain sensitive information). Receiving "unfiltered" block events requires read access to the channel. The default behavior is to connect to receive filtered block events. To connect to receive unfiltered block events, call connect (true) (see below).

Please note that if you register a block event and then submit a transaction, you should not make any assumptions about the block that contains the transaction. In particular, you should not assume that your transaction is in a block associated with the first block event received after registering with the peer channel-based event service. Instead, you can register only one transaction event.

API on the channel

NewChannelEventHub (peer): the Channel instance method that gets the new instance of ChannelEventHub.

GetChannelEventHubsForOrg: gets the list of ChannelEventHubs based on the organization. If the organization name is omitted, the current organization of the current user is used.

New ChannelEventHub and API in v1.1:

RegisterBlockEvent (eventCallBack,errorCallBack,options): registers the block event.

UnregisterBlockEvent (reg_num): delete block registration.

RegisterTxEvent (tx_id,eventCallBack,errorCallBack,options): registers a specific transaction event.

UnregisterTxEvent (tx_id): delete specific deal registrations.

RegisterChaincodeEvent (ccid,eventCallBack,errorCallBack,options): register chain code event.

UnregisterChaincodeEvent (cc_handle): delete chain code event registration.

Connect (full_block): connects the event center of the client channel to the event service based on the structure channel. This call must be made before your ChannelEventHub instance receives the event. When a channel-based event center connects to a service, it requests to receive blocks or filtered blocks. If the full_block parameter is omitted, the default is false, and the filtered block will be requested. After connect () is called, the received block or filtered block cannot be changed.

Disconnect (): causes the client channel event route to close the connection to the structured network channel-based event service and notifies all current channel event registrations of the shutdown using the registered errorCallBacks.

Node parameters

This parameter must be included when getting a new instance of ChannelEventHub. When using a connection profile, this value can be the name of an Peer instance or node, see how to use a common network profile.

EventCallback parameter

This parameter must be included. This is the callback function that is notified when listening for a specific transaction or chain code event when this channel receives a new block.

ErrorCallback parameter

This is an optional parameter. This is the callback function to be notified when this channel event route is turned off. The shutdown may be caused by a structural network error, a network connection problem, or by calling the disconnect () method.

Options parameter

This is an optional parameter. This parameter will contain the following optional attributes:

{integer} startBlock (optional): this option is set to the starting block number of the event check. When included, the peer's channel-based event service is required to start sending blocks from this block number. This is also how to resume monitoring or replay missing blocks added to the ledger. The default value is the number of the last block in the ledger. Replay events can confuse other event listeners; therefore, when using startBlock and endBlock, only one listener is allowed on ChannelEventHub. When this parameter is excluded (because it will be normal), the event service will be asked to start sending blocks from the last block on the ledger.

{integer} endBlock (optional): this option is set to the end block number of the event check. When included, the peer's channel-based event service is required to stop sending the block after the block is delivered. This is how to replay the missing blocks added to the ledger. If startBlock is not included, the endBlock must be equal to or greater than the current channel block height. Replay events can confuse other event listeners; therefore, when using startBlock and endBlock, only one listener is allowed on ChannelEventHub.

{boolean} unregister (optional): this option setting indicates that registration should be deleted (unregistered) when an event is seen. When an application uses a timeout to wait only for a specified time to view a transaction, timeout handling should include manual "unregistration" of the transaction event listener to avoid accidental event callbacks. The default value for this setting is different for different types of event listeners. For block listeners, the default value is true when end_block is set as an option. For transaction listeners, the default value is true. For chain code listeners, the default value is false, because matching filters may apply to many transactions.

{boolean} disconnect (optional): this option setting instructs the ChannelEventHub instance to automatically disconnect itself from the peer's channel-based event service when it sees the event. Unless endBlock is set, the default value is false, then it will be true.

Get channel-based event routing

A new method has been added to the Fabric Node.js client Channel object to simplify the setup of the ChannelEventHub object. Use the following command to get the ChannelEventHub instance that will be set up for use with the peer channel-based event service. The ChannelEventHub instance will use all the same endpoint configuration settings that the peer instance is using, such as tls certificates and host and port addresses.

When using the connection profile (see Resources), you can use the name of the node to get the new channel event route.

Var channel_event_hub = channel.newChannelEventHub ('peer0.org1.example.com')

The following is an example of how to get a route list of channel events when using a connection profile. The following gets the list based on the current organization defined in the currently active client client section of the connection profile. Objects defined in the organization that set eventSource to true are added to the list.

Var channel_event_hubs = channel.getChannelEventHubsForOrg ()

When you create a node instance, you can use the node instance to get the ChannelEventHub instance.

Let data = fs.readFileSync (path.join (_ _ dirname, 'somepath/tlscacerts/org1.example.com-cert.pem')); let peer = client.newPeer (' grpcs://localhost:7051', {pem: Buffer.from (data). ToString (), 'ssl-target-name-override':' peer0.org1.example.com'}); let channel_event_hub = channel.newChannelEventHub (peer); Block listener

Use block event listeners when you need to monitor new blocks to be added to the ledger. When the new block is submitted to the ledger on the node, the Fabric client Node.js. Ledger is notified. The client Node.js then invokes the registered callback of the application. The callback passes the JSON representation of the newly added block. Note that when connect () is not called with a true value, the callback will receive the filter block. The access rights of users who register to receive the full block are checked by the channel-based event service of the node. When you need to view previously added blocks, the registration of the callback can include the starting block number. The callback starts to receive blocks from this number and continues to receive new blocks as they are added to the ledger. This is a way for applications resume and replay to lose events that may have been lost while the application is offline. The application should remember the last block it has processed to avoid replay the entire ledger.

The following example registers a block listener to start receiving blocks.

/ / keep the block_reg to unregister with later if neededblock_reg = channel_event_hub.registerBlockEvent ((block) = > {console.log ('Successfully received the block event');}, (error) = > {console.log (' Failed to receive the block event::'+ error);})

The following example registers with the starting block number because this application needs to recover lost blocks in a specific block and replay. The application callback will handle replay blocks in the same area as the current event. Block listeners will continue to receive blocks because they have been submitted to the node's ledger.

/ / keep the block_reg to unregister with later if neededblock_reg = channel_event_hub.registerBlockEvent ((block) = > {console.log ('Successfully received the block event');}, (error) = > {console.log (' Failed to receive the block event::'+ error);}, {startBlock:23})

The following example registers with the starting block number and the ending block. The application needs a missing block from replay. The application callback handles replay blocks in the same area as the current event. When the listener sees the end block event, the block listener automatically unregisters and the ChannelEventHub closes. The application will not have to process this handle.

Block_reg = channel_event_hub.registerBlockEvent ((block) = > {console.log ('Successfully received the block event');}, (error) = > {console.log (' Failed to receive the block event::'+ error);}, / / for block listeners, the defaults for unregister and disconnect are true, / / so the they are not required to be set in the following example {startBlock:23, endBlock:30, unregister: true, disconnect: true}); transaction listener

Use a transaction listener when you need to monitor the completion of a transaction for an organization peer. When the new block is submitted to the ledger on the node, the client is notified Node.js. The client then checks to see if the block is a registered transaction identifier. If a deal is found, the callback will be notified through the transaction ID, transaction status, and block number. The filtered block contains the transaction status, so the complete block can be received without the channel-based event service connected to the peer. Since most non-administrator users will not be able to see the complete block, connecting to the received filtered block will avoid access problems when these users only need to listen for their submitted transactions.

The following example shows registering the deal ID in the javascript commitment and building another commitment to send the deal to the orderer. These two commitments will be implemented together in order to receive the results of the two actions together. Using the transaction listener, the default optional setting for unregistration is true. Therefore, in the following example, after the listener sees the transaction, the listener that will be registered will automatically unregister.

Let tx_object = client.newTransactionID (); / / get the transaction ID string for later uselet tx_id = tx_object.getTransactionID (); let request = {targets: targets, chaincodeId: 'my_chaincode', fcn:' invoke', args: ['doSomething',' with this data'], txId: tx_object}; return channel.sendTransactionProposal (request);}). Then ((results) = > {/ / a real application would check the proposal resultsconsole.log ('Successfully endorsed proposal to invoke chaincode') / / start block may be null if there is no need to resume or replaylet start_block = getBlockFromSomewhere (); let event_monitor = new Promise ((resolve, reject) = > {let handle = setTimeout (()) = > {/ / do the housekeeping when there is a problem channel_event_hub.unregisterTxEvent (tx_id); console.log ('Timeout-Failed to receive the transaction event'); reject (new Error (' Timed out waiting for block event'));}, 20000) Channel_event_hub.registerTxEvent ((event_tx_id, status, block_num) = > {clearTimeout (handle); / / channel_event_hub.unregisterTxEvent (event_tx_id); let the default do this console.log ('Successfully received the transaction event'); storeBlockNumForLater (block_num); resolve (status);}, (error) = > {clearTimeout (handle) Console.log ('Failed to receive the transaction event::' + error); reject (error);}, / / when this `startBlock` is null (the normal case) transaction / / checking will start with the latest block {startBlock:start_block} / / notice that `unregister` is not specified, so it will default to true / / `disconnect` is also not specified and will default to false);}) Let send_trans = channel.sendTransaction ({proposalResponses: results [0], proposal: results [1]}); return Promise.all ([event_monitor, send_trans]);}) .then ((results) = > {Chaincode event listener

Use the chain code event listener when you need to monitor events that will be published in your chain code. When a new block is submitted to the ledger, the client is notified to Node.js. The client then checks for the registered chain code pattern in the name field of the chain code event. The registration of the listener includes a regular expression to check the chain code event name. If the chain code event name is found to match the regular expression of the listener, the callback of the listener is notified through the chain code event, block number, transaction ID, and transaction status. The filtered block will not have chain code event payload information; it will only have the chaincode event name. If payload information is required, the user must be able to access the full block, and the channel event center must be connected (true) to receive the full block event from the peer's channel-based event service.

The following example shows how to register a chain code event listener in a javascript commitment and build another commitment to send the deal to the subscriber. These two commitments will be implemented together in order to receive the results of the two actions together. If long-term monitoring requires chaincode event listeners, follow the block listener example above.

Let tx_object = client.newTransactionID (); let request = {targets: targets, chaincodeId: 'my_chaincode', fcn:' invoke', args: ['doSomething',' with this data'], txId: tx_object}; return channel.sendTransactionProposal (request);}). Then ((results) = > {/ / a real application would check the proposal resultsconsole.log ('Successfully endorsed proposal to invoke chaincode') / / Build the promise to register an event listener with the NodeSDK.// The NodeSDK will then send a request to the peer's channel-based event// service to start sending blocks. The blocks will be inspected to see if// there is a match with a chaincode event listener.let event_monitor = new Promise ((resolve, reject) = > {let regid = null; let handle = setTimeout (()) = > {if (regid) {/ / might need to do the clean up this listener channel_event_hub.unregisterChaincodeEvent (regid); console.log ('Timeout-Failed to receive the chaincode event') } reject (new Error ('Timed out waiting for chaincode event'));}, 20000); regid = channel_event_hub.registerChaincodeEvent (chaincode_id.toString (),' ^ 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 channel_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) }); / / build the promise to send the proposals to the ordererlet send_trans = channel.sendTransaction ({proposalResponses: results [0], proposal: results [1]}); / / now that we have two promises all set to go... Execute themreturn Promise.all ([event_monitor, send_trans]);}) .then ((results) = > {

=

Share some interactive online programming hands-on tutorials related to Bitcoin, Ethernet Square, EOS, Fabric, etc.:

Java Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into Java code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare bitcoin development course for Java engineers.

Php Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into Php code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare bitcoin development course for Php engineers.

C # Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into C # code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare Bitcoin development course for C # engineers.

The java ethernet development tutorial is mainly for java and android programmers to conduct a detailed web3j explanation of blockchain ethernet development.

Python ethernet, mainly for python engineers to use web3.py for block chain ethernet development of the detailed explanation.

Php Ethernet Square, mainly introduces the use of php for intelligent contract development interaction, account creation, transaction, transfer, token development, filter and transaction and so on.

Introduction to Ethernet Square tutorial, mainly introduces the intelligent contract and dapp application development, suitable for entry.

Yi Tai Fang development advanced tutorial, mainly introduces the use of node.js, mongodb, block chain, ipfs to achieve decentralized e-commerce DApp practice, suitable for advanced.

ERC721 focuses on Taifang pass practice, and the course focuses on the practical development of a digital art creation and sharing DApp. It deeply explains the concept, standard and development scheme of ethernet non-homogenization pass. The content includes the independent implementation of ERC-721 standard, explains the secondary development of OpenZeppelin contract code base, the actual combat project adopts Truffle,IPFS, and realizes the pass and decentralized stock exchange.

C # Ethernet Square, mainly explains how to use C # to develop .net-based Ethernet Square applications, including account management, status and transactions, intelligent contract development and interaction, filters and transactions, etc.

EOS introduction course, this course helps you quickly get started with the development of EOS block chain decentralized applications, covering core knowledge points such as EOS tool chain, accounts and wallets, issuing tokens, smart contract development and deployment, using code and intelligent contract interaction, and finally using all knowledge points to complete the development of a note DApp.

Play with EOS wallet development. This course focuses on the complete development process of mobile EOS wallet, and deeply studies the application development of EOS blockchain. The course covers the core concepts of EOS blockchain, such as accounts, computing resources, intelligent contracts, actions and transactions. It also explains how to use eosjs and eosjs-ecc development packages to access EOS blockchain, and how to integrate EOS blockchain support in React front-end applications. The content of the course is profound and simple, which is very suitable for front-end engineers to study the application development of EOS block chain.

This course is for beginners. It includes core concepts such as Hyperledger Fabric identity certificate and MSP service, authority policy, channel configuration and startup, chain code communication interface, as well as Fabric network design, nodejs chain code and application development. It is the best choice for Nodejs engineers to learn Fabric block chain development.

The course is aimed at beginners, including Hyperledger Fabric identity certificate and MSP service, authority policy, channel configuration and startup, chain code communication interface and other core concepts, as well as the operation practice of Fabric network design, java chain code and application development. It is the best choice for java engineers to learn Fabric block chain development.

Tendermint block chain development detailed understanding, this course is suitable for engineers who want to use tendermint for block chain development, the course content includes the core concepts of tendermint application development model, such as ABCI interface, Merkel tree, multi-version state library, etc., as well as rich practical code such as token issuance, it is the best choice for go language engineers to get started with block chain development.

These are all the contents of the article "how Hyperledger Fabric Node.js uses Channel-based event Services". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 294

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report