Pippo Pluto
Pippo Pluto

Reputation: 151

How could I capture events generated by transactions on Hyperledger Fabric?

I'd like to know if chaincode events can be captured by all peers of a specific channel that have installed the chaincode through SDK. I tried some experiments but it seems that a chaincode event can be captured only by the peer that required the specific transaction but I need all peers of a channel receive that specific event.

Upvotes: 2

Views: 929

Answers (1)

David Viejo
David Viejo

Reputation: 811

The events which the chaincode emits are stored in the transaction.

In your case, you will need to connect to a peer and listen for contract events.

This is an example of Node.JS client:

const n = await gateway.getNetwork("mychannel");
const contract: network.Contract = n.getContract("fabcar");
contract.addContractListener(async (event) => {
  console.log(event.eventName, event.payload.toString("utf-8"));
});

The output will be:

itemCreated 1f6629d7-999b-4cbb-8b36-68e1de2aa373

Then in the chaincode, you will set an event, this is an example in Java:

ctx.getStub().setEvent("itemCreated", StringUtils.getBytes(item.id, StandardCharsets.UTF_8));

If you want to investigate which events are in a transaction, you can fetch the block by executing the following scripts:

BLOCK_NUMBER=1 # whatever block you want to fetch
peer channel fetch -c mychannel ${BLOCK_NUMBER}
configtxlator proto_decode --input mychannel_${BLOCK_NUMBER}.block --type common.Block > mychannel_${BLOCK_NUMBER}.json

And then you will see in the JSON a key called events:

events property in JSON

Upvotes: 2

Related Questions