Hyperledger架构:无法在Fabcar示例中查询分类帐

时间:2019-01-15 11:35:36

标签: node.js hyperledger-fabric hyperledger

我正在尝试在Hyperledger fabric版本1.2中编写一些简单的chaincode应用程序。但是,当我在fabric-samples / chaincode / fabcar中尝试Fabcar示例时,我无法查询任何汽车。这是我的查询命令:

    docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer chaincode instantiate -o orderer.example.com:7050 -C mychannel -n mycc -l node -v 1.0 -c '{"Args":["Init"]}'
    docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer chaincode query -C mychannel -n mycc -c '{"Args":["initLedger", "1"]}'
docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/e
tc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer chaincode query -C mychannel -n mycc -c '{"Args":["queryCar", "1"]}'
    docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer chaincode query -C mychannel -n mycc -c '{"Args":["queryAllCars"]}'

这是有问题的链码:

/*
# 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])));
      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());

这是我输入

时的结果
  

docker日志dev-peer0.org1.example.com-mycc-1.0

> fabcar@1.0.0 start /usr/local/src
> node fabcar.js "--peer.address" "peer0.org1.example.com:7052"

=========== Instantiated fabcar chaincode ===========
{ fcn: 'initLedger', params: [ '1' ] }
============= START : Initialize Ledger ===========
Added <-->  { make: 'Toyota',
  model: 'Prius',
  color: 'blue',
  owner: 'Tomoko',
  docType: 'car' }
Added <-->  { make: 'Ford',
  model: 'Mustang',
  color: 'red',
  owner: 'Brad',
  docType: 'car' }
Added <-->  { make: 'Hyundai',
  model: 'Tucson',
  color: 'green',
  owner: 'Jin Soo',
  docType: 'car' }
Added <-->  { make: 'Volkswagen',
  model: 'Passat',
  color: 'yellow',
  owner: 'Max',
  docType: 'car' }
Added <-->  { make: 'Tesla',
  model: 'S',
  color: 'black',
  owner: 'Adriana',
  docType: 'car' }
Added <-->  { make: 'Peugeot',
  model: '205',
  color: 'purple',
  owner: 'Michel',
  docType: 'car' }
Added <-->  { make: 'Chery',
  model: 'S22L',
  color: 'white',
  owner: 'Aarav',
  docType: 'car' }
Added <-->  { make: 'Fiat',
  model: 'Punto',
  color: 'violet',
  owner: 'Pari',
  docType: 'car' }
Added <-->  { make: 'Tata',
  model: 'Nano',
  color: 'indigo',
  owner: 'Valeria',
  docType: 'car' }
Added <-->  { make: 'Holden',
  model: 'Barina',
  color: 'brown',
  owner: 'Shotaro',
  docType: 'car' }
============= END : Initialize Ledger ===========
{ fcn: 'queryCar', params: [ 'CAR1' ] }
Error: CAR1 does not exist: 
    at queryCar (/usr/local/src/fabcar.js:49:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
2019-01-15T11:19:33.113Z ERROR [lib/handler.js] [mychannel-e871dea2]Calling chaincode Invoke() returned error response [Error: CAR1 does not exist: ]. Sending ERROR message back to peer 
{ fcn: 'queryCar', params: [ '1' ] }
Error: 1 does not exist: 
    at queryCar (/usr/local/src/fabcar.js:49:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
2019-01-15T11:19:38.799Z ERROR [lib/handler.js] [mychannel-063f1069]Calling chaincode Invoke() returned error response [Error: 1 does not exist: ]. Sending ERROR message back to peer 
{ fcn: 'queryAllCars', params: [] }
end of data
[]

我能够在Building first network中运行该示例,但是显然在该示例中,变量是在init函数中初始化的,而在本示例中则不是。

我正在使用基本网络来运行Hyperledger网络。

我是Fabric的新手,所以我只是想了解如何创建一个简单的chaincode应用程序,但是我不知道如何解决此错误。 请帮助我,非常感谢。

更新:这是CouchDB的日志:

[notice] 2019-01-15T11:22:16.089668Z nonode@nohost <0.674.0> 0269d8db8d couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/2?attachments=true 404 ok 0
[notice] 2019-01-15T11:22:19.270219Z nonode@nohost <0.674.0> 1668dfe5a3 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/2?attachments=true 404 ok 0
[notice] 2019-01-15T11:36:11.858609Z nonode@nohost <0.20709.0> d43f3ef0f8 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/1?attachments=true 404 ok 51
[notice] 2019-01-15T11:36:20.814603Z nonode@nohost <0.20709.0> 92a6fef801 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/1?attachments=true 404 ok 0
[notice] 2019-01-15T11:36:31.675132Z nonode@nohost <0.20709.0> 9d4f700668 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/2?attachments=true 404 ok 0
[notice] 2019-01-15T11:36:49.859017Z nonode@nohost <0.20709.0> 81625d8469 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/CAR2?attachments=true 404 ok 0
[notice] 2019-01-15T11:36:51.211387Z nonode@nohost <0.20709.0> fbd0612525 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/CAR2?attachments=true 404 ok 0
[notice] 2019-01-15T11:37:04.092872Z nonode@nohost <0.20709.0> 791cfa83a0 couchdb:5984 172.23.0.5 undefined GET /mychannel_mycc/_all_docs?attachments=true&endkey=%22CAR999%22&include_docs=true&inclusive_end=false&limit=1001&startkey=%22CAR0%22 200 ok 30

这是否意味着分类帐无法连接到CouchDB?这是我的docker-compose.yaml文件:

#
# Copyright IBM Corp All Rights Reserved
#
# SPDX-License-Identifier: Apache-2.0
#
version: '2'

networks:
  basic:

services:
  ca.example.com:
    image: hyperledger/fabric-ca
    environment:
      - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
      - FABRIC_CA_SERVER_CA_NAME=ca.example.com
      - FABRIC_CA_SERVER_CA_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.org1.example.com-cert.pem
      - FABRIC_CA_SERVER_CA_KEYFILE=/etc/hyperledger/fabric-ca-server-config/2ef41cf85bf5f581c1bf943dc0231656f5b151c7e579649c96f69ed5d96b437c_sk
    ports:
      - "7054:7054"
    command: sh -c 'fabric-ca-server start -b admin:adminpw'
    volumes:
      - ./crypto-config/peerOrganizations/org1.example.com/ca/:/etc/hyperledger/fabric-ca-server-config
    container_name: ca.example.com
    networks:
      - basic

  orderer.example.com:
    container_name: orderer.example.com
    image: hyperledger/fabric-orderer
    environment:
      - ORDERER_GENERAL_LOGLEVEL=info
      - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
      - ORDERER_GENERAL_GENESISMETHOD=file
      - ORDERER_GENERAL_GENESISPROFILE=SampleDevModeSolo
      - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
      - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
      - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/msp/orderer/msp
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
    command: orderer
    ports:
      - 7050:7050
    volumes:
        - ./config/:/etc/hyperledger/configtx
        - ./crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/:/etc/hyperledger/msp/orderer
        - ./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/msp/peerOrg1
    networks:
      - basic

  peer0.org1.example.com:
    container_name: peer0.org1.example.com
    image: hyperledger/fabric-peer
    environment:
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_LOGGING_PEER=debug
      - CORE_CHAINCODE_LOGGING_LEVEL=debug
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/peer/
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      # # the following setting starts chaincode containers on the same
      # # bridge network as the peers
      # # https://docs.docker.com/compose/networking/
      - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_basic
      - CORE_LEDGER_STATE_STATEDATABASE=CouchDB
      - CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb:5984
      # The CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME and CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD
      # provide the credentials for ledger to connect to CouchDB.  The username and password must
      # match the username and password set for the associated CouchDB.
      - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=
      - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric
    # command: peer node start
    command: peer node start --peer-chaincodedev=true
    ports:
      - 7051:7051
      - 7053:7053
    volumes:
        - /var/run/:/host/var/run/
        - ./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp:/etc/hyperledger/msp/peer
        - ./crypto-config/peerOrganizations/org1.example.com/users:/etc/hyperledger/msp/users
        - ./config:/etc/hyperledger/configtx
        - ./fabcar:/opt/gopath/src/github.com/
    depends_on:
      - orderer.example.com
      - couchdb
    networks:
      - basic

  couchdb:
    container_name: couchdb
    image: hyperledger/fabric-couchdb
    # Populate the COUCHDB_USER and COUCHDB_PASSWORD to set an admin user and password
    # for CouchDB.  This will prevent CouchDB from operating in an "Admin Party" mode.
    environment:
      - COUCHDB_USER=
      - COUCHDB_PASSWORD=
    ports:
      - 5984:5984
    networks:
      - basic

  cli:
    container_name: cli
    image: hyperledger/fabric-tools
    tty: true
    environment:
      - GOPATH=/opt/gopath
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_LOGGING_LEVEL=info
      - CORE_PEER_ID=cli
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
      - CORE_CHAINCODE_KEEPALIVE=10
    working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
    command: /bin/bash
    volumes:
        - /var/run/:/host/var/run/
        - ./../chaincode/:/opt/gopath/src/github.com/
        - ./crypto-config:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
    networks:
        - basic
    #depends_on:
    #  - orderer.example.com
    #  - peer0.org1.example.com
    #  - couchdb

0 个答案:

没有答案