Chaincode无法正确建立状态?

时间:2019-05-11 06:59:52

标签: hyperledger-fabric hyperledger

问题:

实例化Fabcar Chaincode之后,我尝试使用这些命令运行其功能。

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 fabcar -c '{"Args":["initLedger"]}

在此命令上,链码日志是这样的。

  

2019-05-11T06:37:56.994Z信息[lib / handler.js]
  信息:[myc-22dd9c0b]调用链码Init()成功。   将完成的消息发送回同位体   {“ timestamp”:“” 2019-05-11T06:37:56.994Z“} {fcn:'initLedger',参数:   []}   =============开始:初始化分类帐===========成功{状态:200,消息:”,有效载荷:}添加了<-> {make:   '丰田',型号:'Prius',颜色:'蓝色',车主:'Tomoko',
  docType:“汽车”}成功{状态:200,消息:“,有效载荷:    }添加了<-> {品牌:“福特”,型号:“野马”,颜色:   '红色',所有者:'布拉德',文档类型:'汽车'}成功{状态:200,   消息:”,有效载荷:}添加了<-> {make:'Hyundai',
  型号:“图森”,颜色:“绿色”,所有者:“ Jin Soo”,docType:   'car'}成功{状态:200,消息:”,有效载荷:}   添加了<-> {品牌:“大众”,型号:“帕萨特”,颜色:   '黄色',所有者:'最大',文档类型:'汽车'}成功{状态:200,   消息:”,有效载荷:}添加了<-> {make:'Tesla',
  型号:“ S”,颜色:“黑色”,所有者:'Adriana',docType:'car'}   成功{状态:200,消息:”,有效载荷:}已添加<->   {品牌:“标致”,型号:“ 205”,颜色:“紫色”,所有者:   'Michel',docType:'car'}成功{状态:200,消息:”,   有效载荷:}添加了<-> {make:“ Chery”,型号:“ S22L”,
  颜色:“白色”,所有者:“ Aarav”,docType:“汽车”}成功{   状态:200,消息:”,有效载荷:}已添加<-> {make:   '菲亚特',型号:'Punto',颜色:'紫罗兰色,所有者:'Pari',
  docType:“汽车”}成功{状态:200,消息:“,有效载荷:    }添加了<-> {make:'Tata',型号:'Nano',颜色:   'indigo',所有者:'Valeria',docType:'car'}成功{状态:   200,消息:“”,有效载荷:}已添加<-> {make:'Holden',
  型号:“ Barina”,颜色:“棕色”,所有者:“ Shotaro”,docType:   “汽车”}   =============结束:初始化分类帐===========

在此命令上,对等日志是这样的。

  

2019-05-12 02:44:18.189 UTC [vscc]验证-> ERRO 197 VSCC错误:   stateBasedValidator.Validate失败,认可的错误验证   TX 8:0中的链码fabcar的策略失败:签名集未设置   满足政策2019-05-12 02:44:18.189 UTC [committer.txvalidator]   validateTx->事务txId的ERRO 198 VSCCValidateTx   = 9e55c9bb42c109dc5236fedc58c1db95d46f02139525ccb6a6a4b9c9ec72743d返回错误:验证链码fabcar的认可策略   在TX 8:0中失败:签名集不满足策略2019-05-12   02:44:18.189 UTC [committer.txvalidator]验证-> INFO 199   [myc]在28ms内验证区块[8] 2019-05-12 02:44:18.196 UTC   [valimpl] preprocessProtoBlock-> WARN 19a频道[myc]:   块[8]交易索引[0] TxId   [9e55c9bb42c109dc5236fedc58c1db95d46f02139525ccb6a6a4b9c9ec72743d]   由提交者标记为无效。原因码   [ENDORSEMENT_POLICY_FAILURE] 2019-05-12 02:44:19.473 UTC [kvledger]   CommitWithPvtData-> INFO 19b [myc]具有1的提交块[8]   1277毫秒内进行的交易(state_validation = 0毫秒block_commit = 670毫秒   state_commit = 420ms)

然后,我试图像这样运行queryallCars方法。

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 fabcar -c '{"Args":["queryAllCars"]}

在此命令上,链码日志是这样的。

  

2019-05-11T06:39:25.449Z信息[lib / handler.js]
  信息:[myc-88655c1f]调用链码Invoke()成功。   将完成的消息发送回同位体   {“ timestamp”:“” 2019-05-11T06:39:25.449Z“} {fcn:'queryAllCars',   params:[]}数据结束[] 2019-05-11T06:41:50.560Z信息   [lib / handler.js]

在我尝试使用queryCar这样的方法检索一辆汽车后。

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 fabcar -c '{"Args":["queryCar","CAR0"]}'
Error: endorsement failure during invoke. response: status:500 message:"transaction returned with failure: Error: CAR0 does not exist:

在此命令上,链码日志是这样的。

  

{fcn:'queryCar',参数:['CAR0']}错误:CAR0不存在:       在queryCar(/usr/local/src/fabcar.js:50:13)       在       在process._tickCallback(内部/进程/next_tick.js:188:7)2019-05-11T06:43:32.844Z错误[lib / handler.js]
  错误:[myc-4b24ad23]返回调用链代码Invoke()   错误响应[错误:CAR0不存在:]。正在发送错误消息   后退

我做了很多尝试来找出链式代码出了什么问题,但我无法做到。

这是我的密码。

/*
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
*/

"use strict";
const shim = require("fabric-shim");
const util = require("util");

let Chaincode = class {
  // The Init method is called when the Smart Contract 'fabcar' is instantiated by the blockchain network
  // Best practice is to have any Ledger initialization in separate function -- see initLedger()
  async Init(stub) {
    console.info("=========== Instantiated fabcar chaincode ===========");
    return shim.success();
  }

  // The Invoke method is called as a result of an application request to run the Smart Contract
  // 'fabcar'. The calling application program has also specified the particular smart contract
  // function to be called, with arguments
  async Invoke(stub) {
    let ret = stub.getFunctionAndParameters();
    console.info(ret);

    let method = this[ret.fcn];
    if (!method) {
      console.error("no function of name:" + ret.fcn + " found");
      throw new Error("Received unknown function " + ret.fcn + " invocation");
    }
    try {
      let payload = await method(stub, ret.params);
      return shim.success(payload);
    } catch (err) {
      console.log(err);
      return shim.error(err);
    }
  }

  async queryCar(stub, args) {
    if (args.length != 1) {
      throw new Error(
        "Incorrect number of arguments. Expecting CarNumber ex: CAR01"
      );
    }
    let carNumber = args[0];

    let carAsBytes = await stub.getState(carNumber); //get the car from chaincode state
    if (!carAsBytes || carAsBytes.toString().length <= 0) {
      throw new Error(carNumber + " does not exist: ");
    }
    console.log(carAsBytes.toString());
    return carAsBytes;
  }

  async initLedger(stub, args) {
    console.info("============= START : Initialize Ledger ===========");
    let cars = [];
    cars.push({
      make: "Toyota",
      model: "Prius",
      color: "blue",
      owner: "Tomoko"
    });
    cars.push({
      make: "Ford",
      model: "Mustang",
      color: "red",
      owner: "Brad"
    });
    cars.push({
      make: "Hyundai",
      model: "Tucson",
      color: "green",
      owner: "Jin Soo"
    });
    cars.push({
      make: "Volkswagen",
      model: "Passat",
      color: "yellow",
      owner: "Max"
    });
    cars.push({
      make: "Tesla",
      model: "S",
      color: "black",
      owner: "Adriana"
    });
    cars.push({
      make: "Peugeot",
      model: "205",
      color: "purple",
      owner: "Michel"
    });
    cars.push({
      make: "Chery",
      model: "S22L",
      color: "white",
      owner: "Aarav"
    });
    cars.push({
      make: "Fiat",
      model: "Punto",
      color: "violet",
      owner: "Pari"
    });
    cars.push({
      make: "Tata",
      model: "Nano",
      color: "indigo",
      owner: "Valeria"
    });
    cars.push({
      make: "Holden",
      model: "Barina",
      color: "brown",
      owner: "Shotaro"
    });

    for (let i = 0; i < cars.length; i++) {
      cars[i].docType = "car";
      await stub.putState("CAR" + i, Buffer.from(JSON.stringify(cars[i]))).then(
        () => {
          console.info("successful");
          console.log(shim.success());
        },
        () => {
          console.log(shim.error());
        }
      );
      console.info("Added <--> ", cars[i]);
    }
    console.info("============= END : Initialize Ledger ===========");
  }

  async createCar(stub, args) {
    console.info("============= START : Create Car ===========");
    if (args.length != 5) {
      throw new Error("Incorrect number of arguments. Expecting 5");
    }

    var car = {
      docType: "car",
      make: args[1],
      model: args[2],
      color: args[3],
      owner: args[4]
    };

    await stub.putState(args[0], Buffer.from(JSON.stringify(car)));
    console.info("============= END : Create Car ===========");
  }

  async queryAllCars(stub, args) {
    let startKey = "CAR0";
    let endKey = "CAR999";

    let iterator = await stub.getStateByRange(startKey, endKey);

    let allResults = [];
    while (true) {
      let res = await iterator.next();

      if (res.value && res.value.value.toString()) {
        let jsonRes = {};
        console.log(res.value.value.toString("utf8"));

        jsonRes.Key = res.value.key;
        try {
          jsonRes.Record = JSON.parse(res.value.value.toString("utf8"));
        } catch (err) {
          console.log(err);
          jsonRes.Record = res.value.value.toString("utf8");
        }
        allResults.push(jsonRes);
      }
      if (res.done) {
        console.log("end of data");
        await iterator.close();
        console.info(allResults);
        return Buffer.from(JSON.stringify(allResults));
      }
    }
  }

  async changeCarOwner(stub, args) {
    console.info("============= START : changeCarOwner ===========");
    if (args.length != 2) {
      throw new Error("Incorrect number of arguments. Expecting 2");
    }

    let carAsBytes = await stub.getState(args[0]);
    let car = JSON.parse(carAsBytes);
    car.owner = args[1];

    await stub.putState(args[0], Buffer.from(JSON.stringify(car)));
    console.info("============= END : changeCarOwner ===========");
  }
};

shim.start(new Chaincode());

这是package.json文件。

{
    "name": "fabcar",
    "version": "1.0.0",
    "description": "fabcar chaincode implemented in node.js",
    "engines": {
        "node": ">=8.4.0",
        "npm": ">=5.3.0"
    },
    "scripts": {
        "start": "node fabcar.js"
    },
    "engine-strict": true,
    "license": "Apache-2.0",
    "dependencies": {
        "fabric-shim": "~1.4.0"
    }
}

有人可以帮助我解决此问题吗?谢谢!

1 个答案:

答案 0 :(得分:0)

@dwp事务在对等方验证期间失败,您可以看到VSCC错误。