Can't invoke chaincode from SDK - hyperledger-fabric

I can invoke chaincode from my peer by the following command:
peer chaincode invoke -o coreOrderer.dip.com:7050 --tls --cafile /etc/hyperledger/tlsca.dip.com-cert.pem --tlsRootCertFiles /etc/hyperledger/fabric/tls/ca.crt -C dipchannel -n mycc --peerAddresses peer0.core.dip.com:7051 -c '{"Args":["query","a"]}'
And it works, I can see in the peer logs:
Entry chaincode: name:"mycc"
Exit chaincode: name:"mycc" (2ms)
And I can see result of this invoke in my chaincode container.
But when I'm trying to invoke from my code by SDK
req := channel.Request{
ChaincodeID: "mycc",
Fcn: "query",
Args: [][]byte{[]byte("a")},
}
resp, err := client.Execute(req)
I have empty response, and in the peer log I see:
Entry chaincode: name:"cscc"
Exit chaincode: name:"cscc" (1ms)
Entry chaincode: name:"lscc"
Exit chaincode: name:"lscc" (1ms)
Why it is calling "cscc" and "lscc" chaincodes and doesn't call to "mycc" ?

check this below are System Chaincodes
LSCC Lifecycle system chaincode handles lifecycle requests described above. >>> Chaincode lifecycle
CSCC Configuration system chaincode handles channel configuration on the peer side. >>> which helps regulate access control
QSCC Query system chaincode provides ledger query APIs such as getting blocks and transactions.
Note: In particular, install, instantiate and upgrade do not apply to system chaincodes.
System chaincode is used in Hyperledger Fabric to implement a number of system behaviors so that they can be replaced or modified as appropriate by a system integrator.
Unlike a user chaincode, a system chaincode is not installed and instantiated using proposals from SDKs or CLI. It is registered and deployed by the peer at start-up
COMING to your query >>>>
Check whether you are providing identity or not, as it enters into CSCC which is a regulator for ACL
Check below my code snippet
func (setup *FabricSetup) Query() (string, error) {
// Channel client is used to query and execute transactions
clientContext := setup.sdk.ChannelContext(setup.ChannelID, fabsdk.WithUser(setup.OrgAdmin))
client, err := channel.New(clientContext)
setup.client = client
// Prepare arguments
var args []string
args = append(args, "queryRate")
args = append(args, "001")
response, err := setup.client.Query(
channel.Request{
ChaincodeID: setup.ChainCodeID,
Fcn: args[0],
Args: [][]byte{[]byte(args[1])},
},
)
if err != nil {
return "", fmt.Errorf("failed to query: %v", err)
}
return string(response.Payload), nil
}

Related

Error while I run a p. benchmark with Hyperledger Caliper: No valid responses from any peers, chaincode registration failed: container exited with 0

I want to run a performance benchmark for the contract (which is writen in typescript) from this repository:https://github.com/AleRapchan/hyperledger-supply-chain
So, I am using Hyperledger Caliper based on this tutorial: https://hyperledger.github.io/caliper/v0.5.0/fabric-tutorial/tutorials-fabric-existing/
to run the performance benchmark and I followed these steps:
Steps followed:
I have clonned this repo as I mentioned before: https://github.com/AleRapchan/hyperledger-supply-chain and, at the same level, I created the caliper-workspace folder as the tutorial said.
I created the channel "mychannel" and deployed the chaincode respectively.
./network.sh up createChannel -ca -s couchdb
./network.sh deployCC -ccn supplychain -ccp ../../chaincode -ccl typescript
I have configured the three caliper files as shown below (myAssetBenchmark.yaml, networkConfig.yaml, readAsset.js) into the caliper-workspace folder.
I have installed the caliper dependencies in the caliper-workspace folder.
npm install --only=prod #hyperledger/caliper-cli#0.5.0
npx caliper bind --caliper-bind-sut fabric:2.2
At the same directory, I run the performance benchmark with the following command:
npx caliper launch manager --caliper-workspace ./ --caliper-networkconfig networks/networkConfig.yaml --caliper-benchconfig benchmarks/myAssetBenchmark.yaml --caliper-flow-only-test
but I got the following errors:
Error 1
error: [Transaction]: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: failed to execute transaction b6cc9ab28537a5539aa0876a823a679a952dee1232540e8efbe1ad01e02ebfbb: could not launch chaincode supplychain_1.0:a38d65123f915a15106ad4d0f8893b0880ed2979ddcc84106b9267f5ee31ddd4: chaincode registration failed: container exited with 0
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: failed to execute transaction b6cc9ab28537a5539aa0876a823a679a952dee1232540e8efbe1ad01e02ebfbb: could not launch chaincode supplychain_1.0:a38d65123f915a15106ad4d0f8893b0880ed2979ddcc84106b9267f5ee31ddd4: chaincode registration failed: container exited with 0
Error 2
error [caliper] [connectors/v2/FabricGateway] Failed to perform submit transaction [createProduct] using arguments [1_0,1234567890,50,Fruit Juices,,2022-06-24T18:25:43.511Z,{},Apple Juice,Etobicoke, ON, Canada,2021-06-24T18:25:43.511Z,$9.00,200,ml], with error: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: failed to execute transaction 5837e5ab8b41016290a3d204f4ffde53bad977e917eb1ae53784623959d4e359: could not launch chaincode supplychain_1.0:a38d65123f915a15106ad4d0f8893b0880ed2979ddcc84106b9267f5ee31ddd4: chaincode registration failed: container exited with 0
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: failed to execute transaction 5837e5ab8b41016290a3d204f4ffde53bad977e917eb1ae53784623959d4e359: could not launch chaincode supplychain_1.0:a38d65123f915a15106ad4d0f8893b0880ed2979ddcc84106b9267f5ee31ddd4: chaincode registration failed: container exited with 0
myAssetBenchmark.yaml
test:
name: basic-contract-benchmark
description: test benchmark
workers:
number: 2
rounds:
- label: readAsset
description: Read asset benchmark
txDuration: 30
rateControl:
type: fixed-load
opts:
transactionLoad: 2
workload:
module: workload/readAsset.js
arguments:
assets: 10
contractId: supplychain
networkConfig.yaml
name: Caliper test
version: "2.0.0"
caliper:
blockchain: fabric
channels:
- channelName: mychannel
contracts:
- id: supplychain
organizations:
- mspid: Org1MSP
identities:
certificates:
- name: 'User1'
clientPrivateKey:
path: '../hyperledger-supply-chain/network/fabric-network/organizations/peerOrganizations/org1.example.com/users/User1#org1.example.com/msp/keystore/46d82eb2dbaed33f941f9a39394bba7b5167d09d116ba563de1675f22b083d3e_sk'
clientSignedCert:
path: '../hyperledger-supply-chain/network/fabric-network/organizations/peerOrganizations/org1.example.com/users/User1#org1.example.com/msp/signcerts/cert.pem'
connectionProfile:
path: '../hyperledger-supply-chain/network/fabric-network/organizations/peerOrganizations/org1.example.com/connection-org1.yaml'
discover: true
readAsset.js
'use strict';
const { WorkloadModuleBase } = require('#hyperledger/caliper-core');
class MyWorkload extends WorkloadModuleBase {
constructor() {
super();
}
async initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext) {
await super.initializeWorkloadModule(workerIndex, totalWorkers, roundIndex, roundArguments, sutAdapter, sutContext);
for (let i=0; i<this.roundArguments.assets; i++) {
const id = `${this.workerIndex}_${i}`;
console.log(`Worker ${this.workerIndex}: Creating asset ${id}`);
const request = {
contractId: this.roundArguments.contractId,
contractFunction: 'createProduct',
invokerIdentity: 'User1',
contractArguments: [id, '1234567890', 50, 'Fruit Juices', [],
'2022-06-24T18:25:43.511Z', JSON.stringify({}),'Apple Juice', 'Etobicoke, ON, Canada',
'2021-06-24T18:25:43.511Z','$9.00', 200, 'ml'],
readOnly: false
};
await this.sutAdapter.sendRequests(request);
}
}
async submitTransaction() {
const randomId = Math.floor(Math.random()*this.roundArguments.assets);
const myArgs = {
contractId: this.roundArguments.contractId,
contractFunction: 'readProduct',
invokerIdentity: 'User1',
contractArguments: [`${this.workerIndex}_${randomId}`],
readOnly: true
};
await this.sutAdapter.sendRequests(myArgs);
}
async cleanupWorkloadModule() {
for (let i=0; i<this.roundArguments.assets; i++) {
const assetID = `${this.workerIndex}_${i}`;
console.log(`Worker ${this.workerIndex}: Deleting asset ${assetID}`);
const request = {
contractId: this.roundArguments.contractId,
contractFunction: null,
invokerIdentity: 'User1',
contractArguments: [id],
readOnly: false
};
await this.sutAdapter.sendRequests(request);
}
}
}
function createWorkloadModule() {
return new MyWorkload();
}
module.exports.createWorkloadModule = createWorkloadModule;
PD: I am using WSL2 based engine (Docker Desktop and WSL2).

Error: No valid responses from any peers. Failed to execute transaction could not launch chaincode

I am trying to run the app.js file in the provided asset-transfer-ledger-queries folder with a slight modification.
I made a change to the asset-transfer-ledger-chaincode.js file as shown below:
async CreateAsset(ctx, assetID, color, size, owner, appraisedValue) {
const exists = await this.AssetExists(ctx, assetID);
if (exists) {
throw new Error(`The asset ${assetID} already exists`);
}
// ==== Create asset object and marshal to JSON ====
let asset = {
docType: 'asset',
assetID: assetID,
color: color,
size: size,
owner: owner,
appraisedValue: appraisedValue,
couponID: assetID,
value: color,
expiration: size,
user: sha256(owner),
uuid: uuid.v5(),
redeemed: false
};
basically I just added some properties to the asset object.
After updating the chaincode and running node app.js, I get the following error:
--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger
2020-12-08T18:22:27.975Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: failed to execute transaction 3832a02eeafd57382fb4810bc263d41693764f0d8cb76c27e5613c359b14d42f: could not launch chaincode ledger_1.0:7230409065bcd9da163bc285287935a7d6a3799c99ee59b8a77c93883b607bdb: chaincode registration failed: container exited with 1
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: failed to execute transaction 3832a02eeafd57382fb4810bc263d41693764f0d8cb76c27e5613c359b14d42f: could not launch chaincode ledger_1.0:7230409065bcd9da163bc285287935a7d6a3799c99ee59b8a77c93883b607bdb: chaincode registration failed: container exited with 1
******** initLedger failed :: Error: No valid responses from any peers. Errors:
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: failed to execute transaction 3832a02eeafd57382fb4810bc263d41693764f0d8cb76c27e5613c359b14d42f: could not launch chaincode ledger_1.0:7230409065bcd9da163bc285287935a7d6a3799c99ee59b8a77c93883b607bdb: chaincode registration failed: container exited with 1
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: failed to execute transaction 3832a02eeafd57382fb4810bc263d41693764f0d8cb76c27e5613c359b14d42f: could not launch chaincode ledger_1.0:7230409065bcd9da163bc285287935a7d6a3799c99ee59b8a77c93883b607bdb: chaincode registration failed: container exited with 1
It works fine if I don't make any changes to the chaincode file. Does anyone know what I can do?
I tried to reproduce your situation.
# fabric-samples/test-network
./network.sh down
./network.sh up createChannel -c mychannel -ca
./network.sh deployCC -ccn ledger -ccl javascript
# fabric-samples/asset-transfer-ledger-queries/application-javascript
node -v
# v12.13.1
npm install
node app.js
You can also, see error logs in chaincode container
# check <your_chaincode_container_name>
docker ps -a
# view logs
docker logs <your_chaincode_container_name>
1. Import library [chaincode.js]
#[ERROR CODE] - `node app.js`
--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger
2020-12-10T00:53:48.061Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: ReferenceError: sha256 is not defined
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: ReferenceError: sha256 is not defined
do it
# asset_transfer_ledger_chaincode.js
const {Contract} = require('fabric-contract-api');
const sha256 = require('sha256'); // added
const uuid = require('uuid'); // added
# package.json
"dependencies": {
"fabric-contract-api": "^2.0.0",
"fabric-shim": "^2.0.0", // added ','
"sha256": "^0.2.0", // added
"uuid": "^8.3.2" // added
}
2. Fix wrong module code
#[ERROR CODE] - `node app.js`
--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger
2020-12-10T01:03:27.583Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: failed to execute transaction 62c19fbb84394ba1de399745c46f781078134b84de6b3d73419b9f65c5fa692b: could not launch chaincode ledger_1.0:5303ef138ca9cdb054cd3d814835fffca2706aa0c8e387611b93e4d6d1773742: chaincode registration failed: container exited with 1
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: failed to execute transaction 62c19fbb84394ba1de399745c46f781078134b84de6b3d73419b9f65c5fa692b: could not launch chaincode ledger_1.0:5303ef138ca9cdb054cd3d814835fffca2706aa0c8e387611b93e4d6d1773742: chaincode registration failed: container exited with 1
******** initLedger failed :: Error: No valid responses from any peers. Errors:
peer=peer0.org1.example.com:7051, status=500, message=error in simulation: failed to execute transaction 62c19fbb84394ba1de399745c46f781078134b84de6b3d73419b9f65c5fa692b: could not launch chaincode ledger_1.0:5303ef138ca9cdb054cd3d814835fffca2706aa0c8e387611b93e4d6d1773742: chaincode registration failed: container exited with 1
peer=peer0.org2.example.com:9051, status=500, message=error in simulation: failed to execute transaction 62c19fbb84394ba1de399745c46f781078134b84de6b3d73419b9f65c5fa692b: could not launch chaincode ledger_1.0:5303ef138ca9cdb054cd3d814835fffca2706aa0c8e387611b93e4d6d1773742: chaincode registration failed: container exited with 1
uuid.v4() Create a version 4 (random) UUID
uuid.v5() Create a version 5 (namespace w/ SHA-1) UUID
uuid.v5() requires input parameters
do it
# asset_transfer_ledger_chaincode.js
// ==== Create asset object and marshal to JSON ====
let asset = {
docType: 'asset',
assetID: assetID,
color: color,
size: size,
owner: owner,
appraisedValue: appraisedValue,
couponID: assetID,
value: color,
expiration: size,
user: sha256(owner),
uuid: uuid.v5('Hello, World!', '1b671a64-40d5-491e-99b0-da01ff1f3341'), // modified
redeemed: false
};
3. Result (Solved)
# fabric-samples/asset-transfer-ledger-queries/application-javascript
# node app.js
Loaded the network configuration located at /Users/kmk/Project/src/github.com/hyperledger/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/connection-org1.json
Built a CA Client named ca-org1
Built a file system wallet at /Users/kmk/Project/src/github.com/hyperledger/fabric-samples/asset-transfer-ledger-queries/application-javascript/wallet
Successfully enrolled admin user and imported it into the wallet
Successfully registered and enrolled user appUser and imported it into the wallet
--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger
*** Result: committed
*** application ending

ENDORSEMENT_POLICY_FAILURE in hyperledger fabric in case of private data

We are working a project in which we are using the latest private data collection.
We are running the peers in a kubernetes setup. We have a collection config as described below,
{
"name": "Org1_PDC2",
"policy": "OR ('Org1.member')",
"requiredPeerCount": 0,
"maxPeerCount": 2,
"memberOnlyRead": true,
"memberOnlyWrite": true,
"blockToLive": 0,
"endorsementPolicy": {
"signaturePolicy": "OR('Org1.member')"
}
}
we have 2 organisation in the channel with 2 peers each. Since we have already mentioned the endorsementPolicy for "Org1_PDC2" only needs signature from Org1. but we see that the transaction is also send to the peer1 of Org2. But it fails in org2 since it cannot access "Org1_PDC2". We also observe that from nodejs application that when we submit the transaction it gives us an endorsementPolicy Failure and I could see in the peer1 logs of Org1 that the chaincode is executed successfully but in the peer2 of Org1 logs i see the error as
2020-11-02 13:18:24.249 UTC [gossip.privdata] fetchPrivateData -> DEBU 566a286 Total members that fit some digest: []
2020-11-02 13:18:24.249 UTC [gossip.privdata] fetchPrivateData -> WARN 566a287 Do not know any peer in the channel( mychannel ) that matches the policies , aborting
2020-11-02 13:18:24.249 UTC [gossip.privdata] populateFromRemotePeers -> WARN 566a288 Failed fetching private data from remote peers for dig2src:
2020-11-02 13:18:25.249 UTC [gossip.privdata] RetrievePvtdata -> DEBU 566a28b Could not fetch all missing collection private write sets from remote peers for block [291588] channel=mychannel
2020-11-02 13:18:25.249 UTC [gossip.privdata] prepareBlockPvtdata -> WARN 566a28c Could not fetch all missing eligible collection private write sets for block [291588]. Will commit block with missing private write sets:[txID: 6d14a881ecc6b437f553fc5df7f8fd29d10d92f22f752a2488fc382d535b62e8, seq: 0, namespace: mycc, collection: Org1_PDC2, hash: b8317508d3b677563bb5119626eabfc866ad561358e2d1a7116749d86c952ebe
] channel=mychannel
We are using the discovery option in the nodejs application with option as
await gateway.connect(connectionProfile, {discovery: { enabled: true, asLocalhost: false}});
const network = await gateway.getNetwork('mychannel');
const contract = await network.getContract(contractName);
and in the connection Profile of org1 client we only kept the information of the peers from org1 and orderer. The error message we get when we invoke any transaction from the client is
[TransactionEventHandler]: strategyFail: commit failure for transaction "e7080f63ff9be02002d2723b7431b1e9f236c8119c7c37e7dd21bf924a8a5b7a": TransactionError: Commit of transaction e7080f63ff9be02002d2723b7431b1e9f236c8119c7c37e7dd21bf924a8a5b7a failed on peer peer1.org1.svc.cluster.local with status ENDORSEMENT_POLICY_FAILURE
You may need to let the client SDK know about the collections accessed by the chaincode using contract.addDiscoveryInterest() before using that Contract to invoke transactions, as described in this tutorial page:
https://hyperledger.github.io/fabric-sdk-node/release-2.2/tutorial-discovery-fabric-network.html
If that isn't successful then you can explicitly set the organizations used for endorsement with transaction.setEndorsingOrganizations():
https://hyperledger.github.io/fabric-sdk-node/release-2.2/module-fabric-network.Transaction.html#setEndorsingOrganizations

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.
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.

Fabric node sdk use service discovery function

I tried to use fabric node sdk to call for service discovery function of Fabric v1.2, but I got these errors:
2018-12-12 11:51:26.413 UTC [endorser] callChaincode -> INFO 05d [mychannel][16a59ced] Entry chaincode: name:"mycc"
2018-12-12 11:51:30.138 UTC [chaincode] ProcessStream -> ERRO 05e handling chaincode support stream: rpc error: code = Canceled desc = context canceled
receive failed
github.com/hyperledger/fabric/core/chaincode.(*Handler).ProcessStream
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/handler.go:408
github.com/hyperledger/fabric/core/chaincode.(*ChaincodeSupport).HandleChaincodeStream
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:182
github.com/hyperledger/fabric/core/chaincode.(*ChaincodeSupport).Register
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:187
github.com/hyperledger/fabric/core/chaincode/accesscontrol.(*interceptor).Register
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/accesscontrol/interceptor.go:57
github.com/hyperledger/fabric/protos/peer._ChaincodeSupport_Register_Handler
/opt/gopath/src/github.com/hyperledger/fabric/protos/peer/chaincode_shim.pb.go:1066
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).processStreamingRPC
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:1160
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).handleStream
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:1253
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).serveStreams.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:680
runtime.goexit
/opt/go/src/runtime/asm_amd64.s:2361
2018-12-12 11:52:00.041 UTC [endorser] callChaincode -> INFO 05f [mychannel][16a59ced] Exit chaincode: name:"mycc" (33628ms)
However, I can totally ensure that I have already instantiated my chaincode, and I can normally invoke it if I do not use service discovery.
And here is my code for service discovery:
let client = await helper.getClientForOrg(orgName);
let channel = client.newChannel(channelName);
channel.addPeer(client.getPeer("peer0.org1.example.com"));
await channel.initialize({discover:true, asLocalhost:true});
let request = {
chaincodeId: chaincodeName,
fcn: functionName,
args: args,
transientMap: transient
};
logger.debug("Make query");
let response_payloads = await channel.queryByChaincode(request);
Where am I wrong? And there are codes before I use service discovery:
let client = await helper.getClientForOrg(orgName);
let channel = client.newChannel(channelName);
// assign orderer to channel
channel.addOrderer(client.getOrderer(ordererName));
// assign peers to channel
peers.forEach(function (peerName) {
channel.addPeer(client.getPeer(peerName));
});
let request = {
targets: peers,
chaincodeId: chaincodeName,
fcn: functionName,
args: args,
transientMap: transient
};
logger.debug("Make query");
let response_payloads = await channel.queryByChaincode(request);
I just solved it myself. That may be some kind of a network error.
Now I changed port of peer1.org1.example.com, peer0.org2.example.com, peer1.org2.example.com to 8051, 9051, 10051, 11051. According to the node sdk official doc, I set asLocalhost = true.
And here are my codes that could work for me:
let channel = client.newChannel(channelName);
channel.addPeer(client.getPeer("peer0.org1.example.com"));
await channel.initialize({discover: true, asLocalhost: true});
let tx_id = client.newTransactionID();
tx_id_string = tx_id.getTransactionID();
let request = {
args: args,
chaincodeId: chaincodeName,
chainId: channelName,
fcn: functionName,
txId: tx_id,
transientMap: transient
};
let results = await channel.sendTransactionProposal(request);
hope this could help others.

Resources