как получить консольную информацию о chaincode.js при ее вызове из основной команды hyperledger - PullRequest
0 голосов
/ 24 июня 2018

Привет! Я создал сеть с цепочкой блоков, и я пытаюсь сохранить данные в одноранговом узле, и для этого я сохраняю их в файле data.json, который содержит некоторый уже существующий объект данных, но мой код не работает:

> peer chaincode instantiate -o orderer.tech.com:7050 --tls --cafile
> /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/tech.com/orderers/orderer.tech.com/msp/tlscacerts/tlsca.tech.com-cert.pem
> -C mychannel -n mychain -l node -v 1.0 -c '{"Args":["init","SBIN0000607", "ramji", "10000007","20500"]}' -P "OR
> ('Org1MSP.peer','Org2MSP.peer')"

и это мой код страницы chaincode.js

const shim = require('fabric-shim'); 
const util = require('util'); 
var db = require('data.json'); 
var fs = require('fs');


var Chaincode = class {

  // Initialize the chaincode   async Init(stub) {
    console.info('========= example02 Init =========');
    let ret = stub.getFunctionAndParameters();
    console.info(ret);
    let args = ret.params;
    // initialise only if 4 parameters passed.
    if (args.length != 4) {
      return shim.error('Incorrect number of arguments. Expecting 4');
    }

    let Ifsc = args[0];
    let AccountHolder = args[2];
    let AccountNumber = args[1];
    let Amount = args[3];
    console.info("step2");


      console.info("step3");
      db.push({"Ifsc":Ifsc,"AccountHolder":AccountHolder,"AccountNumber":AccountNumber,"Amount":Amount})
      fs.writeFile('data.json', JSON.stringify(db));
      return shim.success();

    //return shim.success();

  }

  async Invoke(stub) {
    let ret = stub.getFunctionAndParameters();
    console.info(ret);
    let method = this[ret.fcn];
    if (!method) {
      console.log('no method of name:' + ret.fcn + ' found');
      return shim.success();
    }
    try {
      let payload = await method(stub, ret.params);
      return shim.success(payload);
    } catch (err) {
      console.log(err);
      return shim.error(err);
    }   }

  async invoke(stub, args) {
    if (args.length != 3) {
      throw new Error('Incorrect number of arguments. Expecting 3');
    }

    let A = args[0];
    let B = args[1];
    if (!A || !B) {
      throw new Error('asset holding must not be empty');
    }

    // Get the state from the ledger
    let Avalbytes = await stub.getState(A);
    if (!Avalbytes) {
      throw new Error('Failed to get state of asset holder A');
    }
    let Aval = parseInt(Avalbytes.toString());

    let Bvalbytes = await stub.getState(B);
    if (!Bvalbytes) {
      throw new Error('Failed to get state of asset holder B');
    }

    let Bval = parseInt(Bvalbytes.toString());
    // Perform the execution
    let amount = parseInt(args[2]);
    if (typeof amount !== 'number') {
      throw new Error('Expecting integer value for amount to be transaferred');
    }

    Aval = Aval - amount;
    Bval = Bval + amount;
    console.info(util.format('Aval = %d, Bval = %d\n', Aval, Bval));

    // Write the states back to the ledger
    await stub.putState(A, Buffer.from(Aval.toString()));
    await stub.putState(B, Buffer.from(Bval.toString()));

  }

  // Deletes an entity from state   async delete(stub, args) {
    if (args.length != 1) {
      throw new Error('Incorrect number of arguments. Expecting 1');
    }

    let A = args[0];

    // Delete the key from the state in ledger
    await stub.deleteState(A);   }

  // query callback representing the query of a chaincode   async query(stub, args) {
    if (args.length != 1) {
      throw new Error('Incorrect number of arguments. Expecting name of the person to query')
    }

    let jsonResp = {};
    let A = args[0];

    // Get the state from the ledger
    let Avalbytes = await stub.getState(A);
    if (!Avalbytes) {
      jsonResp.error = 'Failed to get state for ' + A;
      throw new Error(JSON.stringify(jsonResp));
    }

    jsonResp.name = A;
    jsonResp.amount = Avalbytes.toString();
    console.info('Query Response:');
    console.info(jsonResp);
    return Avalbytes;   } };

shim.start(new Chaincode());

Я пытаюсь сохранить данные в файле data.json, но он не работает, и я также не могуИнформация консоли на странице chaincode.js, чтобы я мог отлаживать.Может ли кто-нибудь помочь мне с этим Спасибо!

1 Ответ

0 голосов
/ 22 декабря 2018

Использование

docker logs -f <container-name>

где container-name - это имя контейнера, в котором был создан экземпляр цепного кода. для просмотра журнала консоли. Чтобы получить имя контейнера, попробуйте

docker ps --format "{{.Names}}"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...