Node.js 无法使用nodejs SDK提交事务建议

Node.js 无法使用nodejs SDK提交事务建议,node.js,hyperledger-fabric,Node.js,Hyperledger Fabric,问题: 我启动了网络并安装了链码,并在cli容器中成功地完成了事务。但我尝试使用node SDK进行此操作,但失败了,然后我将控制台记录建议响应,然后在终端中留下类似这样的错误 [ { Error: 2 UNKNOWN: Stream removed at Object.exports.createStatusError (C:\Users\tharindusa\Desktop\fabric-samples\myapp\app\node_modules\fabric-client\nod

问题:

我启动了网络并安装了链码,并在cli容器中成功地完成了事务。但我尝试使用node SDK进行此操作,但失败了,然后我将控制台记录建议响应,然后在终端中留下类似这样的错误

[ { Error: 2 UNKNOWN: Stream removed
    at Object.exports.createStatusError (C:\Users\tharindusa\Desktop\fabric-samples\myapp\app\node_modules\fabric-client\node_modules\grpc\src\common.js:87:15)
    at Object.onReceiveStatus (C:\Users\tharindusa\Desktop\fabric-samples\myapp\app\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:1188:28)
    at InterceptingListener._callNext (C:\Users\tharindusa\Desktop\fabric-samples\myapp\app\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:564:42)
    at InterceptingListener.onReceiveStatus (C:\Users\tharindusa\Desktop\fabric-samples\myapp\app\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:614:8)
    at callback (C:\Users\tharindusa\Desktop\fabric-samples\myapp\app\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:841:24)
    code: 2,
    metadata: Metadata { _internal_repr: {} },
    details: 'Stream removed' } ]
Transaction proposal was bad
这就是我的invoke.js文件的样子

"use strict";
/*
 * Copyright IBM Corp All Rights Reserved
 *
 * SPDX-License-Identifier: Apache-2.0
 */
/*
 * Chaincode Invoke
 */

var Fabric_Client = require("fabric-client");
var path = require("path");
var util = require("util");
var os = require("os");

//
var fabric_client = new Fabric_Client();

// setup the fabric network
var channel = fabric_client.newChannel("mychannel");
var peer = fabric_client.newPeer("grpc://localhost:7051");
channel.addPeer(peer, "Org1MSP");
var order = fabric_client.newOrderer("grpc://localhost:7050");
channel.addOrderer(order, true);

//
var member_user = null;
var store_path = path.join(__dirname, "hfc-key-store");
console.log("Store path:" + store_path);
var tx_id = null;

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path })
  .then(state_store => {
    // assign the store to the fabric client
    fabric_client.setStateStore(state_store);
    var crypto_suite = Fabric_Client.newCryptoSuite();
    // use the same location for the state store (where the users' certificate are kept)
    // and the crypto store (where the users' keys are kept)
    var crypto_store = Fabric_Client.newCryptoKeyStore({ path: store_path });
    crypto_suite.setCryptoKeyStore(crypto_store);
    fabric_client.setCryptoSuite(crypto_suite);

    // get the enrolled user from persistence, this user will sign all requests
    return fabric_client.getUserContext("TharinduSA", true);
  })
  .then(user_from_store => {
    if (user_from_store && user_from_store.isEnrolled()) {
      console.log("Successfully loaded user1 from persistence");
      member_user = user_from_store;
    } else {
      throw new Error("Failed to get user1.... run registerUser.js");
    }

    // get a transaction id object based on the current user assigned to fabric client
    tx_id = fabric_client.newTransactionID();
    console.log("Assigning transaction_id: ", tx_id._transaction_id);

    // createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],
    // changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],
    // must send the proposal to endorsing peers
    var request = {
      //targets: peer,
      chaincodeId: "fabcar",
      fcn: "invoke",
      args: ["queryCar", "CAR0"],
      txId: tx_id
    };

    // send the transaction proposal to the peers
    return channel.sendTransactionProposal(request, 3000);
  })
  .then(results => {
    var proposalResponses = results[0];
    console.log(proposalResponses);
    var proposal = results[1];
    let isProposalGood = false;
    if (
      proposalResponses &&
      proposalResponses[0].response &&
      proposalResponses[0].response.status === 200
    ) {
      isProposalGood = true;
      console.log("Transaction proposal was good");
    } else {
      console.error("Transaction proposal was bad");
    }
    if (isProposalGood) {
      console.log(
        util.format(
          'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s"',
          proposalResponses[0].response.status,
          proposalResponses[0].response.message
        )
      );

      // build up the request for the orderer to have the transaction committed
      var request = {
        proposalResponses: proposalResponses,
        proposal: proposal
      };

      // set the transaction listener and set a timeout of 30 sec
      // if the transaction did not get committed within the timeout period,
      // report a TIMEOUT status
      var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing
      var promises = [];

      var sendPromise = channel.sendTransaction(request);
      promises.push(sendPromise); //we want the send transaction first, so that we know where to check status

      // get an eventhub once the fabric client has a user assigned. The user
      // is required bacause the event registration must be signed
      let event_hub = fabric_client.newEventHub();
      event_hub.setPeerAddr("grpc://localhost:7053");

      // using resolve the promise so that result status may be processed
      // under the then clause rather than having the catch clause process
      // the status
      let txPromise = new Promise((resolve, reject) => {
        let handle = setTimeout(() => {
          event_hub.disconnect();
          resolve({ event_status: "TIMEOUT" }); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));
        }, 3000);
        event_hub.connect();
        event_hub.registerTxEvent(
          transaction_id_string,
          (tx, code) => {
            // this is the callback for transaction event status
            // first some clean up of event listener
            clearTimeout(handle);
            event_hub.unregisterTxEvent(transaction_id_string);
            event_hub.disconnect();

            // now let the application know what happened
            var return_status = {
              event_status: code,
              tx_id: transaction_id_string
            };
            if (code !== "VALID") {
              console.error("The transaction was invalid, code = " + code);
              resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));
            } else {
              console.log(
                "The transaction has been committed on peer " +
                  event_hub._ep._endpoint.addr
              );
              resolve(return_status);
            }
          },
          err => {
            //this is the callback if something goes wrong with the event registration or processing
            reject(new Error("There was a problem with the eventhub ::" + err));
          }
        );
      });
      promises.push(txPromise);

      return Promise.all(promises);
    } else {
      console.error(
        "Failed to send Proposal or receive valid response. Response null or status is not 200. exiting..."
      );
      throw new Error(
        "Failed to send Proposal or receive valid response. Response null or status is not 200. exiting..."
      );
    }
  })
  .then(results => {
    console.log(
      "Send transaction promise and event listener promise have completed"
    );
    // check the results in the order the promises were added to the promise all list
    if (results && results[0] && results[0].status === "SUCCESS") {
      console.log("Successfully sent transaction to the orderer.");
    } else {
      console.error(
        "Failed to order the transaction. Error code: " + response.status
      );
    }

    if (results && results[1] && results[1].event_status === "VALID") {
      console.log(
        "Successfully committed the change to the ledger by the peer"
      );
    } else {
      console.log(
        "Transaction failed to be committed to the ledger due to ::" +
          results[1].event_status
      );
    }
  })
  .catch(err => {
    console.error("Failed to invoke successfully :: " + err);
  });

有人能帮我解决这个问题吗?我在网上搜索并尝试了很多例子,但我找不到任何适合我的解决方案。如果有人能帮我解决这个问题,这对我来说是一个很大的帮助。

这个问题与使用grpc而不是od有关grpcs

当您使用nodejs SDK时,您可以通过在代码中将grpc更改为grpc来更正它。如果您这样做,您将发现PEM错误。要更正它,您应该向newPeer添加其他参数。。。功能

您可以在使用newPeer函数的代码中修改这段代码,如果使用neworder函数,则可以使用与newPeer相同的方式添加更改

代码:要添加和修改:

var fs=要求“fs”; var firstnetwork_path=path.resolve“..”、“..”、“first network”; var org1tlscacert_path=path.resolvefirstnetwork_path,'crypto config','peerOrganizations','org1.example.com','tlsca','tlsca.org1.example.com-cert.pem'; var org1tlscacert=fs.readFileSyncorg1tlscacert_路径“utf8”; var peer=fabric_client.newPeer'grpcs://localhost:7051“,{'ssl目标名称覆盖':'peer0.org1.example.com',pem:org1tlscacert};
您看过Fabric 1.4的新编程模型吗?Invoke的代码要简单得多。最新的教程介绍了Fabcar示例的新模型:@Rhatcher我尝试过它,但在创建用户身份时出现了问题。