How to get history of asset with block hash in hyperledger fabric using node sdk - hyperledger-fabric

I have assets whose state get updated and I want get history of that asset with previous_hash and current Block_hash. I am using CouchDB as State DB of Hyperledger Fabric.
I tried fabcar example function 'getHistoryForAsset' but it can give me only TxID but I need Block hash with this.
Can anybody help me how can we do it.
Thanks

Using the transaction ID you can call (evaluate) the GetBlockByTxID transaction function on the system qscc chaincode to get the block that contained that transaction. It expects a transaction ID as an argument and returns a common.Block protobuf response payload.
https://github.com/hyperledger/fabric-protos/blob/f44816d6f621f1f7615cb4fc65643791eb6d8ce6/common/common.proto#L142
Note that a block only contains the hash of the previous block, not the hash of itself.

Related

How to get block hash inside chaincode hyperledger fabric

Currently I'm working with Hyperledger Fabric chaincode and trying to get the hash of last block but I haven't found any way to get it. I need my chaincode to access this hash to do a security check.
I have tried to invoke qscc from my chaincode, which from a client does return blockchain and hash block information, but in this way access is restricted.
Code
#Transaction()
public String getBlockHash(final Context ctx) {
ChaincodeStub stub = ctx.getStub();
String[] argsQscc = {"GetChainInfo","mychannel"};
Response response = stub.invokeChaincodeWithStringArgs("qscc", argsQscc);
System.out.println("Result"+response.getMessage());
return response.getMessage();
}
Error
Rejecting invoke of QSCC from another chaincode because of potential for deadlocks, original invocation for 'mychaincode'.
It is not possible to get from within chaincode. I'm not sure you would want to anyways, because different peers may be at different heights and you would get different endorsement results leading to an invalidation of your transaction.
I'd suggest to have client query this information and pass it into the invoked chaincode as an input.

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.

Hyperledger Fabric : Impact on transaction when we migrate Orderer

Migration of Ordering service from Kafka to Raft.
As we understand the Ordering service never signs the transaction in Fabric. Dose this migration will effect anything on old transaction ordered by old ordere?
Also when we query transaction(local peer query), why do we set the orderer flag?
As long as you have successfully migrated consensus type from kafka >> raft
You are allowed to proceed with transactions.
Question1: Ordering service never signs the transaction in Fabric
Endorsing peers alone will sign transactions & orderer signs the blocks
Question2: Dose this migration will effect anything on old transaction ordered by old ordere?
No, If migration is successful then you are OK to proceed
If you would have followed this link and complete without errors https://hyperledger-fabric.readthedocs.io/en/release-1.4/kafka_raft_migration.html
THEN OK, dont worry about previous data, All SAFE.
However, let me know if you need any assistance in migration. Feel free to create another question reg: migration.
If you want to see old blocks after migration
check this snippet
// keep the block_reg to unregister with later if needed
block_reg = channel_event_hub.registerBlockEvent((block) => {
console.log('Successfully received the block event');
<do something with the block>
}, (error)=> {
console.log('Failed to receive the block event ::'+error);
<do something with the error>
},
{startBlock:23}
);
startBlock:{can be any Block No}
check > https://fabric-sdk-node.github.io/tutorial-channel-events.html
you will get complete block as json format, you will have orderer signature so that you can check which orderer has sealed this block.

Where Endorsing policy is stored?

I'm new to Hyperledger Fabric.
Can any one tell me where the endorsing policy is stored in Hyperledger Fabric?
Thanks in advance
When you specify (or modify) an endorsement policy for a chaincode within the context of a channel, it is stored in the configuration block for that channel by the orderer.
From the Hyperledger Fabric 1.1 documentation:
When the CONFIG_UPDATE is received, the orderer computes the resulting
CONFIG by doing the following:
Verifies the channel_id and read_set. All elements in the read_set must exist at the given versions.
Computes the update set by collecting all elements in the write_set which do not appear at the same version in the read_set.
Verifies that each element in the update set increments the version number of the element update by exactly 1.
Verifies that the signature set attached to the ConfigUpdateEnvelope satisfies the mod_policy for each element in the
update set.
Computes a new complete version of the config by applying the update set to the current config.
Writes the new config into a ConfigEnvelope which includes the CONFIG_UPDATE as the last_update field and the new config encoded in
the config field, along with the incremented sequence value.
Writes the new ConfigEnvelope into a Envelope of type CONFIG, and ultimately writes this as the sole transaction in a new configuration
block.
When the peer (or any other receiver for Deliver) receives this
configuration block, it should verify that the config was
appropriately validated by applying the last_update message to the
current config and verifying that the orderer-computed config field
contains the correct new configuration.

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.

Resources