dwp
dwp

Reputation: 958

Cannot get state in Hyperledger fabric correctly?

Problem:

I have developed a Hyperledger fabric network and after that, I install a chain code in there. This is my Initialize ledger methods looks like.

async initLedger(stub, args) {
    console.info("============= START : Initialize Ledger ===========");
    let drivers = [];

    drivers.push({
      nic: "123",
      firstName: "Saman",
      lastName: "Frenando",
      status: "Not verified",
      licenceNo: "1234"
    });

    drivers.push({
      nic: "124",
      firstName: "Janith",
      lastName: "Bentharaarachchi",
      status: "Not verified",
      licenceNo: "1235"
    });


    for (let i = 0; i < drivers.length; i++) {
      drivers[i].docType = "driver";
      console.log(drivers[i].nic); 
      await stub.putState(
        drivers[i].nic,
        Buffer.from(JSON.stringify(drivers[i]))
      );
      console.info("Added <--> ", drivers[i]);
    }

 console.info("============= END : Initialize Ledger ===========");
  }

This is how I am retrieving those data.

async selectNthDriver(stub, args) {
    if (args.length != 1)  {
      throw new Error(
        "Incorrect number of arguments. Expecting NIC ex: 123"
      );
    }
    let nic = args[0];
    console.log(`nic: ${nic}`);

    let driverAsBytes = await stub.getState(nic); 
    console.log("hi"+driverAsBytes);
    if (!driverAsBytes || driverAsBytes.toString().length <= 0) {
      throw new Error("Driver with NIC" + nic + " does not exist");
    }
    console.log(driverAsBytes.toString());
    return driverAsBytes;
  }

When I am Issuing this command on peer it successfully initializes the ledger.

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C myc -n mycc -c '{"Args":["initLedger"]}'

By Issuing the following command when I try to retrieve a driver it leaves me an error by saying this.

Error: endorsement failure during invoke. response: status:500 message:"transaction returned with failure: Error: Driver with NIC123 does not exist"

peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C myc -n mycc -c '{"Args":["selectNthDriver","123"]}

This is the chaincode logs.

2019-05-09T05:18:51.184Z info [lib/handler.js]
info: [myc-09f261c4] Calling chaincode Init() succeeded. Sending COMPLETED message back to peer {"timestamp":"2019-05-09T05:18:51.184Z"} { fcn: 'initLedger', params: [] } ============= START : Initialize Ledger =========== 123 Added <--> { nic: '123', firstName: 'Saman', lastName: 'Fernando', status: 'Not verified', licenceNo: '1234', docType: 'driver' } 124 Added <--> { nic: '124', firstName: 'Janith', lastName: 'Bentharaarachchi', status: 'Not verified', licenceNo: '1235',
docType: 'driver' } ============= END : Initialize Ledger =========== { fcn: 'selectNthDriver', params: [ '123' ] } nic: 123 hi Error: Driver with NIC123 does not exist at selectNthDriver (/usr/local/src/mycc.js:494:13) at at process._tickCallback (internal/process/next_tick.js:188:7) 2019-05-09T05:43:42.430Z error [lib/handler.js]
error: [myc-e7aef847] Calling chaincode Invoke() returned error response [Error: Driver with NIC123 does not exist]. Sending ERROR message back to peer {"timestamp":"2019-05-09T05:43:42.430Z"}

And when I go to the CouchDB through browser It is not showing the data I initialized. It only shows this data.

{
  "_id": "mycc",
  "_rev": "1-5c5ecfec35f65ec74cbe52a52be96048",
  "~version": "\u0000CgMBBwA=",
  "_attachments": {
    "valueBytes": {
      "content_type": "application/octet-stream",
      "revpos": 1,
      "digest": "md5-SkPMcpW++nrvo5v00rCdRQ==",
      "length": 424,
      "stub": true
    }
  }
}

Can someone help me to find where am I doing wrong? Thank you.

Upvotes: 0

Views: 1017

Answers (1)

Udyan Sharma
Udyan Sharma

Reputation: 134

You should use "query" command for querying a state from the ledger using the peer binary, the invoke command which you have used is for generating a transaction, which is not required for a query operation.

You should just try replacing invoke with query and it should look something like this:

peer chaincode query -o orderer.example.com:7050 -C myc -n mycc -c '{"Args":["selectNthDriver","123"]}

EDIT: Also please check for the following condition in your if statement in the selectNthDriver Method:

if (!driverAsBytes.toString()) 

Also please console for the same(driverAsBytes.toString()) in the line just before this if statement in your code.

Upvotes: 1

Related Questions