i am getting an error while i am trying to install my chain code on my peers
i am using Hyperledger Fabric
var request = {
targets: ["peer1.org2.example.com","peer0.org2.example.com"],
chaincodePath: 'github.com/fabcar/node',
// chaincodePath:'/opt/gopath/src/github.com/fabcar/node',
chaincodeId: 'org2cc',
chaincodeVersion: 'v1',
chaincodeType: 'test'
};
let results = await client.installChaincode(request);
This is my function to install chain code
I am using NodeSDK
chaincodeType => Type of chaincode. One of 'golang', 'car', 'node' or 'java'. Default is 'golang'.
Better remove this optional field (chaincodeType) from your request and try again!!
Related
My problem is that i get an Error while trying to use the chaincode for the test-network but running my application instead of the application-javascript provided at fabric-samples/asset-transfer-basic.
The steps that I follow are:
1. ./network.sh up createChannel -c mychannel -ca
2. ./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-javascript/ -ccl javascript
3. run my application thats is exaclty same with the one provided at docs (fabric-samples/asset-transfer-basic) to InitLedger and they query or update it.
The error I get is the following:
--> Submit Transaction: InitLedger, function creates the initial set of assets on the ledger
2021-11-09T15:54:16.248Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
******** FAILED to run the application: Error: No valid responses from any peers. Errors:
The code in my application is exactly the same as the one at docs:
const ccp = buildCCPOrg1();
const caClient = buildCAClient(FabricCAServices, ccp, 'ca.org1.example.com');
const wallet = await buildWallet(Wallets, walletPath);
await enrollAdmin(caClient, wallet, mspOrg1);
await registerAndEnrollUser(caClient, wallet, mspOrg1, org1UserId, 'org1.department1');
const gateway = new Gateway();
await gateway.connect(ccp, {
wallet,
identity: org1UserId,
discovery: { enabled: false, asLocalhost: true } // using asLocalhost as this gateway is using a fabric network deployed locally
});
const network = await gateway.getNetwork(channelName);
const contract = network.getContract(chaincodeName);
await contract.submitTransaction('InitLedger');
You have peer discovery disabled in your code, usually, you do it when you specify peers you want to connect to but since you don't do it - the SDK client just didn't know to what peers it should connect so it connected to none of them, got 0 responses and threw an error. So I changed this line from your example:
discovery: { enabled: false, asLocalhost: true }
to:
discovery: { enabled: true, asLocalhost: true }
And it worked.
I am facing this problem, below is the exact error:
Error: instantiation policy violation: signature set did not satisfy policy
at self._endorserClient.processProposal
(/home/ubuntu/node_modules/fabric-client/lib/Peer.js:144:36)
at Object.onReceiveStatus
(/home/ubuntu/node_modules/grpc/src/client_interceptors.js:1212:9)
at InterceptingListener._callNext
(/home/ubuntu/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus
(/home/ubuntu/node_modules/grpc/src/client_interceptors.js:618:8)
at callback
(/home/ubuntu/node_modules/grpc/src/client_interceptors.js:847:24)
Here's my code, helper is the connection profile object of yaml.
var client = await helper.getClientForOrg(orgName, username);
var channel = client.getChannel(channelName);
var txId = client.newTransactionID(true);
var params = {
targets: peerNames,
chaincodePath: chaincodePath,
chaincodeId: chaincodeName,
chaincodeVersion: chaincodeVersion,
chaincodeType: "node",
channelNames: channelName
}
var deployResponse = await client.installChaincode(params);
console.log(deployResponse);
// send proposal to endorsing peers
var request = {
targets: peerNames,
chaincodeType: 'node',
chaincodeId: chaincodeName,
chaincodeVersion: chaincodeVersion,
txId: txId,
fcn: 'instantiate',
args: args
}
let results = await channel.sendUpgradeProposal(request);
console.log(results);
This is the example of classic one member & one peer Fabric BlockChain (AWS managed) where using fabric-client library we are able to invoke chaincode and do the query as well. And it's working with any deployed chaincode. However if we try to instantiate / update a chain code using sendUpgradeProposal() method or sendInstantiateProposal() it's giving permission error, mentioned on the post. However installChaincode() method working fine.
I have a network on hyperledger fabric 1.4.4 with 5 organizations A , B, C , D , E. I created a channel with these 5 orgs and installed my chaincode on org A and org B because only they are apart of the endorsement policy.
This is the endorsement policy :
{"identities":[{"role":{"name":"member","mspId":"AMSP"}},{"role":{"name":"member","mspId":"BMSP"}},{"role":{"name":"member","mspId":"CMSP"}},{"role":{"name":"member","mspId":"DMSP"}},{"role":{"name":"member","mspId":"EMSP"}}],"policy":{"2-of":[{"signed-by":0},{"signed-by":1}]}}
I am using a gateway with the below configuration to invoke the chain code
const walletPath = path.join('wallet' );
const wallet = new FileSystemWallet(walletPath);
let connectionOptions = {
identity: userName,
wallet: wallet,
discovery: { enabled:true, asLocalhost: true },
eventHandlerOptions: {
commitTimeout: 100,
strategy: DefaultEventHandlerStrategies.NETWORK_SCOPE_ALLFORTX
}
};
logger.debug('Connecting to Fabric gateway');
await gateway.connect(clientConnectionProfileJson, connectionOptions);
const network = await gateway.getNetwork(channelName);
const contract = await network.getContract(chaincodeName , contractName);
const transaction = contract.createTransaction(functionName);
await transaction.submit(<arguments>);
This is the error which I a getting , at the client level
2021-02-17T05:28:13.063Z - warn: [TransactionEventHandler]: _strategyFail: strategy fail for transaction "9be4da8b1d52ddde804d6c7c08d134ef4b6ac2043cbe0258b5b4c921424c9f04": TransactionError: Peer a-org-peer1.a-org.com:7051 has rejected transaction "9be4da8b1d52ddde804d6c7c08d134ef4b6ac2043cbe0258b5b4c921424c9f04" with code "ENDORSEMENT_POLICY_FAILURE"
This is what I see in all the peer logs
2021-02-17 05:28:12.313 UTC [vscc] Validate -> ERRO 0db VSCC error: stateBasedValidator.Validate failed, err validation of endorsement policy for chaincode {chaincodeName} in tx 26:0 failed: signature set did not satisfy policy
After some research , I found that this is a failure that is occurring when the org peer is trying to commit the transaction to the ledger , and finds that the signature set did not satisfy the policy.
I have gone ahead and looked at the transaction object using the getTransactionByID method. I see that there are two endorsers MSP with the correct sign certificates , these certificates belong to the one of the peers of A and B orgs. So the discovery service correctly identified the peers and even the peers have endorsed the transaction , but not sure why the transaction is not getting committed.
What am I missing here ?
How can I verify if the signatures are correct ?
To explicitly say to the gateway that the request should go to specific endorsing peers , I have used the below code.
const walletPath = path.join('wallet' );
const wallet = new FileSystemWallet(walletPath);
let connectionOptions = {
identity: userName,
wallet: wallet,
discovery: { enabled: true , asLocalhost: true },
eventHandlerOptions: {
commitTimeout: 100,
strategy: DefaultEventHandlerStrategies.NETWORK_SCOPE_ALLFORTX
}
};
logger.debug('Connecting to Fabric gateway');
await gateway.connect(clientConnectionProfileJson, connectionOptions);
const network = await gateway.getNetwork(channelName);
const channel = network.getChannel();
let endorsingPeers = [];
endorsingPeers.push(channel.getChannelPeer('a-org-peer1.a-org.com'));
endorsingPeers.push(channel.getChannelPeer('b-org-peer1.b-org.com'));
// Get addressability to org.cargoesnetwork.ebilloflading contract
// Use chaincodeName that is used for installing
const contract = await network.getContract(chaincodeName , contractName);
const transaction = contract.createTransaction(functionName).setEndorsingPeers(endorsingPeers);
await transaction.submit(<arguments>);
No luck , the transaction still fails with the same endorsement policy failure. I verified the transaction object if the endorser sign certs are correctly present. They are present , but still got the same error.
Out of curiosity , I changed the endorsement policy to only one org from two orgs , every thing worked as expected. The issue exists only when the policy contains more than one endorsing organisations.
Please help in debugging this issue.
An ENDORSEMENT_POLICY_FAILURE can occur for a number of reasons. The first being you don't have enough signatures which is what you have said you have already checked. Another reason is that not all the signatures match to the proposal that was sent.
In the 1.4 gateway apis the proposals are received and not compared to see if they all match before a proposal is sent to the orderer. The SDK will send all the signatures and one of the proposals that was received back. The signatures are created over the each peer's individual proposal response.
If those proposals don't match (which would mean that your chaincode is not deterministic) then one of those signatures will be ok, but the other one won't because it won't match the proposal that was sent to the orderer.
I would check that your chaincode is deterministic because it's possible that each peer is generating different responses. An example of non-deterministic chaincode for example is where it creates a new date and stores that in the world state. Each peer would create a slightly different date value resulting in differing responses.
I'm currently running a project with 2 chaincodes, 2 channels and 2 organizations. I want to install my first chaincode (CC1) on first channel (channel-1) consisting of both org1 and org2. The second chaincode(CC2) will be installed on channel-2 consisting of only org2.
I want to retrieve data from first chaincode and the retrieved data will be used in the second chaincode. Is it possible to retrieve data from a chaincode which is on different channel using invokeChaincode method?
If not possible what are then what are the ways to retrieve data from other chaincodes which is installed on different channel?
I'm using hyperledger fabric version 2.0 and node js to build my chaincode.
You can use the invokeChaincode function to invoke chaincode from a difference channel:
//get data from channel 1
const cc1Args = ['arg1', 'arg2'];
const cc1Res = await ctx.stub.invokeChaincode('CC1', cc1Args, 'channel-1');
if (cc1Res.status !== 200) {
throw new Error(cc1Res.message);
}
const cc1Asset = JSON.parse(cc1Res.payload.toString('utf8'));
//save data to channel 2
const cc2Args = [cc1Asset.arg1, cc1Asset.arg2];
const cc2Res = await ctx.stub.invokeChaincode('CC2', cc2Args, 'channel-2');
if (cc2Res.status !== 200) {
throw new Error(cc2Res.message);
}
const cc2ResObj = JSON.parse(cc1Res.payload.toString('utf8'));
You may also read the document of invokeChaincode: https://hyperledger.github.io/fabric-chaincode-node/master/api/fabric-shim.ChaincodeStub.html#invokeChaincode__anchor
Yes, you can call other chaincode using invokechaincode method but your peer should be joined on that channel. for more information please these links
https://kctheservant.medium.com/cross-chaincode-invoking-in-hyperledger-fabric-8b8df1183c04
https://github.com/hyperledger-archives/fabric/blob/master/examples/chaincode/go/chaincode_example04/chaincode_example04.go
https://golang.hotexamples.com/examples/github.com.hyperledger.fabric.core.chaincode.shim/ChaincodeStubInterface/InvokeChaincode/golang-chaincodestubinterface-invokechaincode-method-examples.html
I successfully installed and instantiated chaincode on my chain. I'm able to enroll the admin and register a user trough nodejs. If I query the chaincode it only returns a correct response around 3 out of 5 times. The rest throws errors that the chaincode can't be found.
The chaincode installed is the basic example from the fabric samples.
My js file to query the chaincode (based on the fabcar example):
/*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const { FileSystemWallet, Gateway } = require('fabric-network');
const path = require('path');
const ccpPath = path.resolve(__dirname, 'connection-org1.json');
async function main() {
try {
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');
// Get the contract from the network.
const contract = network.getContract('mycc');
const result = await contract.evaluateTransaction('query', 'a');
console.log(`Transaction has been evaluated, result is: ${result}`);
} catch (error) {
console.error(`Failed to evaluate transaction: ${error}`);
process.exit(1);
}
}
main();
The successful queries with the errors, nothing has been changed between those executions and they have been called with around 5 seconds beetween them.
root#devserver ~/fabric-samples/bla/first-network # node index.js
Transaction has been evaluated, resultb is: 210
root#devserver ~/fabric-samples/bla/first-network # node index.js
Transaction has been evaluated, resultb is: 210
root#devserver ~/fabric-samples/bla/first-network # node index.js
Transaction has been evaluated, resultb is: 210
root#devserver ~/fabric-samples/bla/first-network # node index.js
Transaction has been evaluated, resultb is: 210
root#devserver ~/fabric-samples/bla/first-network # node index.js
2019-09-09T18:53:24.646Z - warn: [Query]: evaluate: Query ID "[object Object]" of peer "peer1.PharmaProducer.bigpharma.com:8051" failed: message=cannot retrieve package for chaincode mycc/1.0, error open /var/hyperledger/production/chaincodes/mycc.1.0: no such file or directory, stack=Error: cannot retrieve package for chaincode mycc/1.0, error open /var/hyperledger/production/chaincodes/mycc.1.0: no such file or directory
at self._endorserClient.processProposal (/root/fabric-samples/bla/first-network/node_modules/fabric-network/node_modules/fabric-client/lib/Peer.js:140:36)
at Object.onReceiveStatus (/root/fabric-samples/bla/first-network/node_modules/grpc/src/client_interceptors.js:1207:9)
at InterceptingListener._callNext (/root/fabric-samples/bla/first-network/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (/root/fabric-samples/bla/first-network/node_modules/grpc/src/client_interceptors.js:618:8)
at callback (/root/fabric-samples/bla/first-network/node_modules/grpc/src/client_interceptors.js:845:24), status=500, , url=grpcs://localhost:8051, name=peer1.PharmaProducer.bigpharma.com:8051, grpc.max_receive_message_length=-1, grpc.max_send_message_length=-1, grpc.keepalive_time_ms=120000, grpc.http2.min_time_between_pings_ms=120000, grpc.keepalive_timeout_ms=20000, grpc.http2.max_pings_without_data=0, grpc.keepalive_permit_without_calls=1, name=peer1.PharmaProducer.bigpharma.com:8051, grpc.ssl_target_name_override=peer1.PharmaProducer.bigpharma.com, grpc.default_authority=peer1.PharmaProducer.bigpharma.com, isProposalResponse=true
Failed to evaluate transaction: Error: cannot retrieve package for chaincode mycc/1.0, error open /var/hyperledger/production/chaincodes/mycc.1.0: no such file or directory
I expect the code to successfuly return a correct result every time and not randomly show an error that the code doesn't exist.
Any insight on how this can happen is appreciated.
Looking at the logs I can see why sometimes you get peer0 and occasionally you get peer1, and that is because the discovery results and processing result in it not being possible to get the list of peers in any particular order so with 2 peers in your org and the fact that this is not a long running app but a short running invocation sometimes peer0 will be first in the list of peers and sometimes peer1. Because you have only installed the chaincode on peer0, peer1 can't honour the evaluate request and return an error.
The node-sdk should detect this and then try peer0 but either you are using an older version of the node-sdk which definitely had an issue where it did not try a different peer or the node-sdk is thinking this is (incorrectly, but may not be able to distinguish) a chaincode response and passes that back to the caller.
The solution to avoid the error is to install the chaincode on all the peers.