Search code examples
hyperledger-fabrichyperledgerhyperledger-fabric-ca

Hyperledger Fabric - How to Decode data_hash to return the actual data?


I have been involved in developing Blockchain application using hyperledger fabric.

I made use of fabric-node-sdk to interact with blockchain layer.

Right now I have few data that were inserted into blocks & we are able to see them in CouchDB & query the same to retrieve data.

When channel.queryBlock(1) is called we get data_hash as its response, Is there a way to decode data_hash to get the actual data ?

The data_hash would look like this : 0dafabc38a7d216426b9a9ab71057fe6c8b984c9e44f92b7265fbd3e2785e26c

Any suggestion would be a helpful.

Thank You!


Solution

  • As per the Fabric SDK docs, Channel.queryBlock returns a Promise for a Block. The Block object returned can be interrogated to extract various fields, e.g.

    channel = client.getChannel(channelName);
    return channel.queryBlock(blockNumber);
    }).then((block) => {
      console.log('Block Number: ' + block.header.number);
      console.log('Previous Hash: ' + block.header.previous_hash);
      console.log('Data Hash: ' + block.header.data_hash);
      console.log('Transactions: ' + block.data.data.length);
      block.data.data.forEach(transaction => {
        console.log('Transaction ID: ' + transaction.payload.header.channel_header.tx_id);
        console.log('Creator ID: ' + transaction.payload.header.signature_header.creator.Mspid);
        console.log('Data: ');
        console.log(JSON.stringify(transaction.payload.data));
      });
    });
    

    Some sample output:

    Block Number: 4
    Previous Hash: b794ee910514f989c0bcb54c2d26d907fca65eb9dd60e86047b3c3c78b96cb96
    Data Hash: 1e267340a5f57ea687bfd6b57aec51b5e16420921fb50f980d08f1302bd289be
    Transactions: 1
    Transaction ID: 49c1333402977a53ec2532a4d425ef8bd6e3efa546358d3d2e3be645ee32b6c0
    Creator ID: Org1MSP
    Data:
    {"actions":[{"header":{"creator":{"Mspid":"Org1MSP","IdBytes":"-----BEGIN CERTIFICATE-----...
    

    The structure of the Block object is fully documented here.