How could I capture events generated by transactions on Hyperledger Fabric? - 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.

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:

Related

fabric-sdk-go Execute Not always updating ledger

I am using client.channel.Execute API in fabric-sdk-go to invoke the ledger update Txs in chaincode.
I know my chaincode for ledger update is correct because invoke Tx when run from cli container command line is working perfectly all the times.
Few times, randomly, ledger updates are not reflecting when executed as REST API call from POSTMAN like below. In those cases, response code is 200 with correct response payload suggestive of successful chaincode running.
`
chaincodeID := "hcc"
fcn := "GiftToken"
args := [][]byte{
[]byte(reqBody.TokenID),
[]byte(reqBody.GiftToUserID),
[]byte(GiftTokenCountAsString),
}
setup := lib.GetFabricSetup()
transientDataMap := make(map[string][]byte)
transientDataMap["result"] = []byte("Transient data in GiftToken invoke")
response, err := setup.Client.Execute(channel.Request{ChaincodeID: chaincodeID, Fcn: fcn, Args: args, TransientMap: transientDataMap})
I am running Fabric 1.4.4 images in docker containers. My network has 1 org with 4 peer nodes.
Surely missing some aspect which is leading to this sort of behaviour.
Thanks in advance.
It takes time for all peers to sync their blocks. Once peers receive these blocks they update their world state, so you can see your change via querying.
When you query for the "just executed" transaction, you may hit one of other peers. If you want immediate result, ensure that you're querying the same peer(s) where you actually executed your transaction. You may try putting some delay to see other peers as well get the block.
The reason why you see the change immediately on CLI, is about the way of the client implementation. On CLI command execution, you specify the peer explicitly. So transaction is executed on one peer and queried on the same peer (no issues). You may prove this behavior by immediately querying (via CLI) another organization's peer just after you execute the transaction (via CLI).
However with your client, probably since you don't explicitly specify the peer, your client SDK uses peers' discovery service and find a peer in the network for you and use it.
Due to this reason, when endorsement policy is formed like "AND(org1, org2)", client SDK actually queries 2 peers (one each org) and compare results.

How can I get an endorsement back from a specific peer?

Is there a way to get endorsements back from specific peer(s) after submitting a transaction in Hyperledger fabric, using contract.submitTransaction() or channel.sendTransaction()?
So far the endorsements always seem to come back from the same peer and not other peers in the organization. Please see my environment details below.
Also if I target specific peers using the node sdk sendTransactionProposal(request)'s ChaincodeInvokeRequest preferred or ignore list, that doesn't seem to make any difference.
Is there any specific documentation or an alternative resource available that addresses this issue?
ChaincodeInvokeRequest{
targets: allPeers or peer2, // or a different peer
preferred: peer2,
ignore, peer1
}
Environment details
Current setup:
1 org with 2 peers
Simple Endorsement policy:
{"identities":[{"role":{"name":"member","mspId":"Org1MSP"}}],policy:{"1-of":[{"signed-by":0}]}}
Fabric sdk libraries:
fabric-ca-client - v1.4.1
fabric-client - v1.4.1
fabric-network - v1.4.1
Hyperledger Fabric version: v1.4.1
Using the following approach to target specific peers in the sdk:
const request = {
targets: peers or peer[1] or [peer2], -- target specific peer
chaincodeId: chaincodeName,
txId,
fcn: functionName,
args,
transientMap: transientMapData // , // private data,
ignore: list of peer[s] to ignore
preferred: list of peer[s] to prefer
};
const endorsementResults = await channel.sendTransactionProposal(request);
if (channel.verifyProposalResponse(endorsementResults[0][0])) {
const transactionRequest = {
proposalResponses: endorsementResults[0],
proposal: endorsementResults[1]
};
invokeResponse = await channel.sendTransaction(transactionRequest);
}
Expected results:
transaction1 - client submits a transaction to peer1 and gets an endorsement back from peer1.
transaction2 - client submits a transaction to peer2 and gets an endorsement back from peer2.
Actual results:
transaction1 - client submits a transaction to peer1 and gets an endorsement back from peer1.
transaction2 - client submits a transaction to peer2 and gets an endorsement back from peer1.

How to query a chaincode from outside an organization

I have 4 Orgs:
Org1 -- 2 peer
Org2 -- 2 peer
OrgCam -- 0 peer, 1 client
OrgView -- 0 peer, 1 client
Org1's peers have a chaincode installed on them that access some private data only available to Org1.
As a client of OrgCam, I want to access the chaincode installed on Org1's peers.
When I try to do that:
const result = await contract.evaluateTransaction('getPoints','ID1');
This error occurs
2019-05-19T15:20:20.084Z - error: [SingleQueryHandler]: evaluate: message=No peers available to query. Errors: [], stack=FabricError: No peers available to query. Errors: []
at SingleQueryHandler.evaluate (/home/zanna/fabric-samples/first-network/clientCode/node_modules/fabric-network/lib/impl/query/singlequeryhandler.js:39:17)
at Transaction.evaluate (/home/zanna/fabric-samples/first-network/clientCode/node_modules/fabric-network/lib/transaction.js:246:29)
at Contract.evaluateTransaction (/home/zanna/fabric-samples/first-network/clientCode/node_modules/fabric-network/lib/contract.js:172:39)
at main (/home/zanna/fabric-samples/first-network/clientCode/camera.js:41:39)
at <anonymous>, name=FabricError
Failed to evaluate transaction: FabricError: No peers available to query. Errors: []
My question is: How can I query the Org1's chaincode even if I'm not a client from Org1?
I am a bit confused by your configuration, but I'll try to answer as best as I can.
Lets make it clear
A chaincode does not "belong" to an organization. A chaincode belongs to a channel and has particular endorsement policies.
Considering that, you could say a chaincode belongs to the peers that are member of the channel.
An organization can only interact with a chaincode if it possesses a peer that is member of the channel that has the chaincode.
Answer
You did not provide any information about your channel. Considering you error, I suppose you did not join the OrgCam peer to the channel in which Org1 peer(s) deployed the chaincode.
You OrgCam peer is not part of the channel, you cannot query the chaincode of the channel.
Moreover, you cannot use a OrgCam client certificate to interact with a Org1 peer, because the certificate is not known/accepted by the Org1 peers. Only Org1 explicitly defined clients can interact with org1 peers.
I finally managed to do that.
1.
const result = await contract.evaluateTransaction('getPoints','ID1');
must be changed to:
const result = await contract.submitTransaction('getPoints','ID1');
in order to get the information from peers in an external organization.
2.
If private data are in use, it's important that the fields "memberOnlyRead" and "memberOnlyWrite" (1) must be removed or set to false in the collections_config.json file.
example:
[
{
"name": "collectionFacepoints",
"policy": "OR('Org1MSP.member')",
"requiredPeerCount": 2,
"maxPeerCount": 2,
"blockToLive": 0,
"memberOnlyRead": false
}
]
3.
In the gateway.connect(connectionProfile, connectionOptions) it is important to add discovery.enable=true to the connectionOptions.
example:
await gateway.connect(
connectionProfile,
{
wallet,
identity: identityConfig.identityLabel,
discovery: {
enabled: true,
asLocalhost: true
},
eventHandlerOptions: {
strategy: DefaultEventHandlerStrategies.NETWORK_SCOPE_ALLFORTX
}
}
);
4.
Unfortunately it seems that a client from OrgCam cannot directly query a chaincode installed in org1's peers, but It can be done adding an empty (2) OrgCam's peer that act as an anchor peer.
(1): "memberOnlyWrite" is not available yet. See here.
(2): With "empty" I mean without any chaincode installed on it.

Hyperledger Fabric nodejs sdk performance issue

I am facing a performance issue while using Hyperledger fabric node.js sdk.
When I issue the invocation request to sdk and consume the response given by the chaincode by using the following code
var proposalResponse = results[0];
var proposal = results[1];
let isProposalGood = false;
if(proposalResponse
&& proposalResponse[0].response
&& proposalResponse[0].response.status === 200){
isProposalGood = true;
var res = JSON.parse(proposalResponse[0].response.payload.toString());
res.event_status = 'VALID'
resolve(res);
}else{
reject(createErrorResponse(proposalResponse[0].message,500))
return
}
The api responds within 50ms as you can see the screenshot below:
But, when I wait for orderer to confirm the transaction by using the following code:
if (code === 'VALID'){
//get payload from proposal response
var res = JSON.parse(proposalResponse[0].response.payload.toString());
res.event_status = 'VALID'
resolve(res);
}else{
var return_status = createErrorResponse("Transaction was not valid", 500);
return_status.tx_id = transaction_id_string
reject(return_status)
return
}
It takes nearby 2500ms to response as you can see the screenshot of postman below:
Correct me if I am wrong
I know it takes time because the orderer confirms the transaction and commits into the ledger. But don't you think we should proceed only if the orderer agrees to transaction and commits into the ledger. If yes, then it will take 2.5 seconds to response (network is running on docker in local machine & sdk on same machine) which is a performance issue.
What happen if data is written into the chaincode and after that orderers deny to write the transaction into the ledger?
Any help would be appreciated
the orderer confirms the transaction and commits into the ledger.
The task for the Ordering service (As the name suggests) is only to order the received endorsed transactions chronologically by channel and then deliver them to all the peers in the channel. Orderers don't actually commit the transactions into the ledger.
The Committer Peers do. And committing is a time-taking process since all the peers validate all the transactions within the block to ensure endorsement policy is fulfilled and to ensure that there have been no changes to ledger state for read set variables since the read set was generated by the transaction execution. Transactions in the block are tagged as being valid or invalid. Then Each peer appends the block to the channel’s chain, and for each valid transaction the write sets are committed to current state database. An event is emitted, to notify the client application that the transaction (invocation) has been immutably appended to the chain, as well as notification of whether the transaction was validated or invalidated.
So after knowing all these details in the Transaction Flow, It should be noted that the client application shouldn't wait for the response received by the orderer. Instead it should just request the orderer to deliver the endorsed transactions and the application should be subscribed to the events emitted by the peers so that it should know or be notified that the transactions are actually immutably committed in the channel's chain.
You can have further help regarding event subscription in the Fabric Node SDK docs.
What happen if data is written into the chaincode and after that
orderers deny to write the transaction into the ledger?
This is simply impossible as data is appended to the chain only when the transaction is validated through proper endorsements from the endorser peers (specified by the endorsement policy) and then finally delivered to the committer peers to append the new values in the chain and update the world state. Data is only written in the chain after it passes all the validations and hence an orderer can never deny for the changes made in the data.
I found another reason for this delay.
The batchtimeout variable in configtx.yaml is set to 2 seconds. So it will do its processing and then wait for 2 seconds and then cut a block. So for write operation it takes approximately 2.5 seconds.

Error reading from stream

JIRA issue: https://jira.hyperledger.org/browse/FAB-7420
I'm trying to set up a network of four organisations, each with one peer (set as admin), and an orderer with kafka ordering service along with a client, which makes 7 VMs.
Setting up the cryptographic material, starting every channel (two of them), joining them with the appropriate peers and installing/instantiating chaincode happens with no trouble.
When trying to invoke chaincode, the chaincode can be successfully invoked (status:200) however the results do not seem to be recorded on the ledger. When running chaincode which returns the value for a/multiple key(s), the resulting payload is simply null. This seems to be due to a fault in the ordering service: I get keeping the error message "Error reading from stream: rpc error: code = Canceled desc = context canceled".
Here are logs for the orderer and endorsing peers of the transaction (which returns status:200)
Orderer: https://gist.github.com/alexanderlhicks/91f32fb5ed2b6d5d232dcdad0572ffee
Peer1 (initiating transaction): https://gist.github.com/alexanderlhicks/a2c7a37d3e692336dbc9a8a9f7fd66ba
Peer2 (has the chaincode installed): https://gist.github.com/alexanderlhicks/75c76b11a26963d7a6962f51295ea816
Peer3 (on channel but does not have that chaincode installed): https://gist.github.com/alexanderlhicks/951757e880d8c2f658d2d188e25b9274
What could be causing the "Error reading from stream" message which seems to be the only error happening? I'm tried playing around with peer and orderer configurations but to no avail. Searching for this error also returns issues in channel creation, or joining channels, which I assume has gone fine since I can invoke chaincode on the channels with my peers.
The txid in the logs is 61f54319421bae9c47fab505e502b932ff6c6b58d7d3795afe1400466e663a5d.
Cheers.

Resources