Hyperledger Fabric - Update a channel config by adding a new Org - hyperledger-fabric

I am trying to add a new Org to an existing Hyperledger fabric network.
The initial network is created by the byfn.sh script that stands up an Orderer and Org1 & Org2.
I have followed this example on Medium.com to create the update protobuf file. Everything that requires configtxgen, cryptogen and configtxlator is done as per this example. However, when it comes to executing the command peer channel signconfigtx -f org3_update_in_envelope.pb, I would like to do that using the Fabric Node SDK.
A point to note here is that if I execute the peer channel ... commands from the cli container command line, the channel update goes through, so I know that the file org3_update_in_envelope.pb is not corrupted.
Using this tutorial and some guidance from this question, I have the following code:
let envelope_pb_file_name = '/tmp/' + json.msp + '_update_in_envelope.pb'; // the pb file we create using command line
let envelope_bytes = fs.readFileSync(envelope_pb_file_name);
if (envelope_bytes === undefined) {
throw new Error(`Could not read the protobuffer file ${envelope_pb_file_name}. Error`);
}
// have the nodeSDK extract out the config update
let config_update = client.extractChannelConfig(envelope_bytes);
let signature = client.signChannelConfig(config_update);
let signatures = [];
signatures.push(signature);
//let orderers = this.loanNetwork.getChannel().getOrderers();
let orderer, ordererName = "orderer.example.com:7050";
const ORDERER_URL = 'grpcs://localhost:7050';
const data = fs.readFileSync(SyndLoanConfig.chainconfig.networkpath + '/crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem').toString();
orderer = client.newOrderer(ORDERER_URL,
{
'pem': Buffer.from(data).toString(),
'ssl-target-name-override': 'orderer.example.com'
});
let mspId = client.getMspid(); // mspId shows "OrdererMSP" after this call is executed
const keyPath = SyndLoanConfig.chainconfig.networkpath + '/crypto-config/ordererOrganizations/example.com/users/Admin#example.com/msp/keystore';
let keyFile, keyFileAry = fs.readdirSync(keyPath).filter(fn => fn.endsWith('_sk'));
for (let f of keyFileAry) {
keyFile = f;
break;
}
keyFile = path.join(keyPath,keyFile);
const keyPEM = fs.readFileSync(keyFile).toString();
const certPath = SyndLoanConfig.chainconfig.networkpath + '/crypto-config/ordererOrganizations/example.com/users/Admin#example.com/msp/signcerts';
let certFile, certFileAry = fs.readdirSync(certPath).filter(fn => fn.endsWith('.pem'));
for (let f of certFileAry) {
certFile = f;
break;
}
certFile = path.join(certPath,certFile);
const certPEM = fs.readFileSync(certFile).toString();
client.setAdminSigningIdentity(keyPEM, certPEM, "OrdererMSP");
if (orderer === undefined) {
throw new Error(`Could not find an orderer associated with channel ${orgJSON.channel}. Error.`)
}
let tx_id = client.newTransactionID();
let request = {
config: config_update, //the binary config
// envelope: envelope_bytes,
signatures: signatures, // the collected signatures
name: orgJSON.channel, // the channel name
orderer: orderer, //the orderer from above
txId: tx_id //the generated transaction id
};
let addOrgResult = await client.updateChannel(request);
addOrgResult variable shows the following error:
info: implicit policy evaluation failed - 0 sub-policies were satisfied, but this policy requires 1 of the 'Writers' sub-policies to be satisfied: permission denied
status: FORBIDDEN
Orderer logs show this:
2020-01-17 21:49:21.620 UTC [cauthdsl] deduplicate -> ERRO 057 Principal deserialization failure (MSP is unknown) for identity 0
2020-01-17 21:49:21.621 UTC [cauthdsl] deduplicate -> ERRO 058 Principal deserialization failure (MSP is unknown) for identity 0
2020-01-17 21:49:21.621 UTC [cauthdsl] deduplicate -> ERRO 059 Principal deserialization failure (MSP is unknown) for identity 0
2020-01-17 21:49:21.621 UTC [orderer.common.broadcast] ProcessMessage -> WARN 05a [channel: mychannel] Rejecting broadcast of config message from 192.168.208.1:56556 because of error: implicit policy evaluation failed - 0 sub-policies were satisfied, but this policy requires 1 of the 'Writers' sub-policies to be satisfied: permission denied
Going through Nikhil Gupta's helpful response to this question, it appears that this error is due to
The error before the policy warning, ERRO 021 Principal
deserialization failure (MSP SampleOrg is unknown) for identity 0,
indicates that the MSP ID that was passed as a parameter with the
request was not recognized by the ordering service. This could be a
result of passing the wrong MSP ID to the command. This error may also
indicate that your organization has not joined the consortium hosted
by the ordering service system channel. If you are updating an
application channel, this error could occur if your organization is
not yet a member of the channel you are trying to update.
However, I am not sure how to proceed because I have connected to the network (Gateway.connect) using the Admin#example.com identity. Additionally, I am also calling client.setAdminSigningIdentity(keyPEM, certPEM, "OrdererMSP"); before making the update.
Any help would be greatly appreciated. Thank you.

The default policy for updating a channel requires a majority, which in your case means you will need signatures from both Org1 admin and Org2 admin and then either Org1 or Org2 can send the actual config update to the orderer.
This means that you need to run
let config_update = client.extractChannelConfig(envelope_bytes);
let signature = client.signChannelConfig(config_update);
let signatures = [];
signatures.push(signature);
as both an Org1 admin and an Org2 admin.
You can then submit the transaction to the orderer as either an Org1 admin or an Org2 admin (but not as the Orderer admin).

Related

ENDORSEMENT_POLICY_FAILURE while invoking chain code using even if the transaction object contains enough endorsements

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.

Added a new Org to an existing Hyperledger Fabric Network. Now having issues with getting a Peer to join an existing channel

This question picks up from my earlier question about adding a new org to an existing channel using fabric node sdk.
Gari helped addressing my issues with using the Node SDK and I was able to successfully add the Org to the channel mychannel, which is part of byfn.sh.
Now, following the original tutorial which I had adapted, I want to add the new Org's peers to join the channel mychannel. I am stuck here at the moment and have not been able to find a solution despite looking on Stackoverflow, HL Lists and HL Jira.
At a high level, the steps I am following are these:
Add the new Org to the channel (uses Client.updateChannel API). I can do this successfully.
I then bring up the peer and the couchdb docker containers for the peers associated with the new Org. The new org is Org3 and here is the connection profile
{
"name": "first-network-org3",
"version": "1.0.0",
"client": {
"organization": "Org3",
"connection": {
"timeout": {
"peer": {
"endorser": "300"
}
}
}
},
"organizations": {
"Org3": {
"mspid": "Org3MSP",
"peers": [
"peer0.org3.example.com"
]
}
},
"peers": {
"peer0.org3.example.com": {
"url": "grpcs://localhost:11051",
"tlsCACerts": {
"path": "/usr/local/fabric/fabric-samples/first-network/crypto-config/peerOrganizations/org3.example.com/tlsca/tlsca.org3.example.com-cert.pem"
},
"grpcOptions": {
"ssl-target-name-override": "peer0.org3.example.com"
}
}
}
}
I use a client pointing to the Org1 connection profile and extract the Network and Channel objects, and subsequently retrieve the channel's genesis block.
I then create a new connection profile to point to Org3 peers and connect to it, and get a new (Org3) client reference.
Using this Org3 client, I create a new Peer object (Client.newPeer)
I then issue a channel.joinChannel(request).
Every single time, I get the following error from the client application
Error: 2 UNKNOWN: access denied: channel [] creator org [Org1MSP]
Docker logs for Peer 3 say this:
2020-01-24 19:46:47.774 UTC [protoutils] ValidateProposalMessage ->
WARN 039 channel []: MSP error: expected MSP ID Org3MSP, received
Org1MSP
2020-01-24 19:46:47.774 UTC [comm.grpc.server] 1 -> INFO 03a
unary call completed grpc.service=protos.Endorser
grpc.method=ProcessProposal grpc.peer_address=192.168.240.1:49860
error="access denied: channel [] creator org [Org1MSP]"
grpc.code=Unknown grpc.call_duration=329.567µs
I know this error is because the MSP ID being submitted with the Channel.joinChannel request is Org1MSP but I am not sure why. I am submitting a peer created using an Org3 client and the transaction ID is also an Org3 Admin transaction ID.
Here is my code:
public async addPeerToChannel(orgJSON) {
try {
let json = JSON.parse(JSON.stringify(orgJSON));
if (json.name === undefined || json.msp === undefined || json.domain === undefined || json.peer === undefined
||
json.peerport === undefined || json.channel === undefined || json.peerurl === undefined) {
throw new Error("Invalid org info provided to addPeerToChannel method");
}
let client = this.loanGateway.getClient(); // get the client reference for Org1 ccp
let cMSP = client.getMspid(); // confirms MSP ID is Org1MSP
let network = await this.loanGateway.getNetwork(json.channel); // mychannel
let channel = network.getChannel();
if (client === undefined || network === undefined || channel === undefined) {
throw new Error(`Invalid network, orderer, channel or client handle in function addPeerToChannel. Error.`);
}
let data = fs.readFileSync(SyndLoanConfig.chainconfig.networkpath + `/crypto-config/peerOrganizations/${json.domain}/peers/${json.peer}/tls/ca.crt`).toString();
// load a new client for Org3
const gateway = new Gateway();
const wallet = this.localWallet;
const ccpFile = fs.readFileSync(path.join(SyndLoanConfig.chainconfig.networkpath,'connection-org3_ac.json'));
const ccp = JSON.parse(ccpFile.toString());
await this.importWalletIdentityFromCryptoConfig('Admin#org3.example.com','Org3MSP');
await gateway.connect(ccp, {
identity: 'Admin#org3.example.com',
wallet: wallet
});
let newClient = gateway.getClient();
let peer = newClient.newPeer(json.peerurl,
{
'pem': Buffer.from(data).toString(),
'ssl-target-name-override': json.peer,
'name': json.peer,
'grpc.keepalive_timeout_ms': 10000
})
if (peer === undefined) {
throw new Error(`Could not create the peer for URL ${json.peerurl}. Error.`)
}
channel.addPeer(peer, json.msp);
let request = {
txId: client.newTransactionID() //the generated transaction id
};
let gBlock = await channel.getGenesisBlock(request);
// for(let p of ccp.peers)
// {
// ccp.peers[p].tlsCACerts.path = path.join(SyndLoanConfig.chainconfig.networkpath,ccp.peers[p].tlsCACerts.path);
// }
// let newNetwork = await gateway.getNetwork("mychannel");
// let newChannel = newNetwork.getChannel();
let channel_request = {
targets: [peer],
block: gBlock,
txId: newClient.newTransactionID(true)
}
let proposal_response = {};
proposal_response = await channel.joinChannel(channel_request);
if (proposal_response[0].code !== 200)
{
throw new Error(`Could not make the peer ${json.peer} join channel ${json.channel}. Error: ${proposal_response[0].message}`);
}
}
catch (err) {
throw new Error(err.message);
}
}
I am sure I am missing something but I am not able to figure out what, and why the joinChannel request is being submitted with MSP set to Org1MSP (by the way, where is this set?)
Appreciate any advice on how to proceed. Thank you.
Was finally able to locate some sample code for Channel.joinChannel.
For those interested, these examples by ksachdeva are extremely helpful.
Essentially, what I was doing wrong was using a channel object associated with an Org1MSP client context, and using that to submit the Channel.joinChannel call.
So, the fix was this (broadly speaking)
Assuming the Org has already been added to the channel,
Create a new client instance using the new Org's common connection profile, or you can create a new client instance from scratch using this sample code by ksachdeva.
Create a new channel instance using Client.newChannel("mychannel") or whatever channel you are joining.
Create a new Orderer instance using Client.newOrderer call, that serves as the Orderer for the channel you are joining. In byfn.sh terminology, this is grpcs://localhost:7050 aka orderer.example.com.
Create a new Peer instance using the peer information for the peer you are adding to the channel.
Add the orderer from Step 3 above to the channel object created in Step 2 using Channel.addOrderer(orderer) API.
Then, the rest of the steps can be followed from the tutorial on Fabric Node SDK site i.e. fetch the genesis block, create a request for joining the peer, and submit the Channel.joinChannel(request).
Please review ksachdeva's example code (link provided earlier in this response) for a complete end-to-end code sample.

While submitting transaction no ledger context error in hyperledger chaincode

I am converting a certificate signing request to self signed certificate using hyper ledger chaincode. But while storing information regarding the certificate, transaction is not being successful and it gives me no ledger context error.
Nodejs version : 8.9.4
My chaincode function is:
async registerDomain(ctx, csr) {
let buff = new Buffer(csr, 'base64')
let csrData = buff.toString('ascii')
pem.createPrivateKey(2048, {
aes128: "11223344"
}, async function (err, pk) {
let domain = new Domain(ctx, "abcd", "data.detail", "keys.certificate", "pk.key");
await ctx.stub.putState(domain.domainId, Buffer.from(JSON.stringify(domain)));
});
While transaction this is what I am getting inside peer docker logs:
HandleTransaction -> ERRO 09f [ddc81d1b] Failed to handle PUT_STATE. error: no ledger context
runtime.goexit
/opt/go/src/runtime/asm_amd64.s:1333
PUT_STATE failed: transaction ID: ddc81d1bcb69eecd6c6bbcf85ba16b2168486d4b232ef3c03fe5bbc7bb2adea1
github.com/hyperledger/fabric/core/chaincode.
runtime.goexit
Any help would be much appreciated.
I have also faced a similar issue. Though there is no any proper solution for this error.
As per my understanding, this error is thrown when tx takes more time to complete and lose the context instance provided by state db api's.
In your example, createPrivateKey might be taking more time to generate pk and thus causing "no ledger context" issue.
Reference:
https://jira.hyperledger.org/browse/FAB-17512?focusedCommentId=69269&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-69269

Error when Creating Channel Using Hyperledger Fabric Node JS

I'm trying to create a channel with the Fabric SDK node.js. When I create the channel through the bash commands, I have no problems (you can see the code below), but when I use the node.js SDK I got some errors.
I am using TLS and client authentication. I can't realize what the error means and how to solve it. Any help will be greatly appreciated.
Node JS code to create Channel, it was executed in host machine:
var Fabric_Client = require('fabric-client');
var fs=require('fs');
var fabric_client = new Fabric_Client();
// Obtain tls cert and key from client.
let clientcert = fs.readFileSync('/home/rosalva40/Documentos/Own2/Own/data/tls/peer1-org1-cli-client.crt');
let clientkey = fs.readFileSync('/home/rosalva40/Documentos/Own2/Own/data/tls/peer1-org1-cli-client.key');
fabric_client.setTlsClientCertAndKey(clientcert.toString(),clientkey.toString())
//Orderer configuration
let pem1 = fs.readFileSync('/home/rosalva40/Documentos/Own2/Own/data/org0-ca-chain.pem');
const connectionopts = {
pem: pem1.toString()
};
var order = fabric_client.newOrderer('grpcs://localhost:9101', connectionopts)
//setup identity admin
let cert = fs.readFileSync('/home/rosalva40/Documentos/Own2/Own/data/orgs/org1/admin/msp/signcerts/cert.pem');
let pk = fs.readFileSync('/home/rosalva40/Documentos/Own2/Own/data/orgs/org1/admin/msp/keystore/b17b8a06b4928a037e621cc784cac4f8a4913087c95c68162ecae6189993a1fa_sk');
const mspid = 'org1MSP';
fabric_client.setAdminSigningIdentity(pk, cert, mspid);
// Setup create channel
var chanelName = 'mychannel';
const envelope = fs.readFileSync('/home/rosalva40/Documentos/Own2/Own/data/channel.tx');
channelConfig = fabric_client.extractChannelConfig(envelope);
signature = fabric_client.signChannelConfig(channelConfig);
const request = {
name: chanelName,
orderer: order,
config: channelConfig,
signatures : [signature],
txId : fabric_client.newTransactionID(true)
};
//Create chanel
fabric_client.createChannel(request);
When I run createChannel.js, I get the following error in the console:
2019-01-17T14:30:42.278Z - error: [Remote.js]: Error: Failed to
connect before the deadline URL:grpcs://localhost:9101
2019-01-17T14:30:42.283Z - error: [Orderer.js]: Orderer
grpcs://localhost:9101 has an error Error: Failed to connect before
the deadline URL:grpcs://localhost:9101 (node:31051)
UnhandledPromiseRejectionWarning: Error: Failed to connect before the
deadline URL:grpcs://localhost:9101
at checkState (/home/rosalva40/fabric-samples/vote/node_modules/fabric-client/node_modules/grpc/src/client.js:720:16)
(node:31051) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). (rejection id: 2) (node:31051) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
And this is the orderer node log:
2019-01-17 16:08:40.977 UTC [grpc] Println -> DEBU 13a grpc:
Server.Serve failed to create ServerTransport: connection error: desc
= "transport: http2Server.HandleStreams failed to receive the preface from client: EOF" 2019-01-17 16:08:41.987 UTC [grpc] Println -> DEBU
13b grpc: Server.Serve failed to create ServerTransport: connection
error: desc = "transport: http2Server.HandleStreams failed to receive
the preface from client: EOF" 2019-01-17 16:08:43.572 UTC [grpc]
Println -> DEBU 13c grpc: Server.Serve failed to create
ServerTransport: connection error: desc = "transport:
http2Server.HandleStreams failed to receive the preface from client:
EOF"
This is the bash code executed in a container:
DATA=data
CHANNEL_TX_FILE=/$DATA/channel.tx
CHANNEL_NAME=mychannel
# ORDERER CONNECTION ARGUMENTS
ORDERER_HOST=orderer1-org0
ORDERER_PORT_INT=7050
INT_CA_CHAINFILE=/${DATA}/org0-ca-chain.pem
ORDERER_PORT_ARGS="-o $ORDERER_HOST:$ORDERER_PORT_INT --tls --cafile $INT_CA_CHAINFILE --clientauth"
export CORE_PEER_TLS_CLIENTCERT_FILE=/$DATA/tls/peer1-org1-cli-client.crt
export CORE_PEER_TLS_CLIENTKEY_FILE=/$DATA/tls/peer1-org1-cli-client.key
ORDERER_CONN_ARGS="$ORDERER_PORT_ARGS --keyfile $CORE_PEER_TLS_CLIENTKEY_FILE --certfile $CORE_PEER_TLS_CLIENTCERT_FILE"
#ORGANIZATION ADMIN ENVIROMENT ARGUMENTS
ORG_ADMIN_HOME=/${DATA}/orgs/org1/admin
export CORE_PEER_MSPCONFIGPATH=$ORG_ADMIN_HOME/msp
export CORE_PEER_LOCALMSPID=org1MSP
#CHANNEL CREATE COMMAND
peer channel create --logging-level=DEBUG -c $CHANNEL_NAME -f $CHANNEL_TX_FILE $ORDERER_CONN_ARGS
Its seems like the app has problems to connect to the orderer. Try using this method:
var Client = require('fabric-client');
var Channel = require('fabric-client').Channel;
const fs = require('fs');
var client = Client.loadFromConfig("config/configfile.yaml");
/**
* #param {String} channelName Channel name used in configtxgen to create the channel transaction (mychannel)
* #param {String} channelConfigPath Path of the channel transaction (/home/root/channel-artifacts/channel.tx)
* #param {String} orderer Orderer name (orderer.example.com)
* #description Create channel
*/
async createChannel(channelName,orderer, channelConfigPath) {
var envelope = fs.readFileSync(channelConfigPath);
var channelConfig = client.extractChannelConfig(envelope);
let signature = client.signChannelConfig(channelConfig);
let request = {
config: channelConfig,
orderer: client.getOrderer(orderer),
signatures: [signature],
name: channelName,
txId: client.newTransactionID(true)
};
const result = await client.createChannel(request)
return result;
}
You can check the structure of the configfile.yaml in this link.
Dont forget to set the client header in your configfile.yaml

Hyperledger Fabric Error: 2 UNKNOWN: access denied: channel [mychannel] creator org [Org1MSP]

I'm trying to interact with the peers from JavaScript and I keep getting
{ Error: 2 UNKNOWN: access denied: channel [mychannel] creator org [Org1MSP]
at Object.exports.createStatusError (/blockchain-api-js/node_modules/grpc/src/common.js:87:15)
at Object.onReceiveStatus (/blockchain-api-js/node_modules/grpc/src/client_interceptors.js:1188:28)
at InterceptingListener._callNext (/blockchain-api-js/node_modules/grpc/src/client_interceptors.js:564:42)
at InterceptingListener.onReceiveStatus (/blockchain-api-js/node_modules/grpc/src/client_interceptors.js:614:8)
at callback (/blockchain-api-js/node_modules/grpc/src/client_interceptors.js:841:24)
code: 2,
metadata: [Object],
details: 'access denied: channel [mychannel] creator org [Org1MSP]' }
I'm using the fabric-ca sample and I was able to execute transactions from cli and from cli through run-fabric.sh but I can't seem to do that from JS, I've created a new user and set the client and cert with client.setTlsClientCertAndKey(cert, key);, I even tried giving the admin cert and key from /data/orgs/org1/admin/msp/signcerts, /data/orgs/org1/admin/msp/admincerts and /data/orgs/org1/admin/msp/keystore as well as the ones from /data/tls/ but with no luck
And this is the portion of the code I use:
var channel = this.client.newChannel('mychannel')
let serverCert = fs.readFileSync('/data/org0-ca-chain.pem');
channel.addOrderer(
this.client.newOrderer(
config.orderers['orderer1-org0'].url,
{
pem: Buffer.from(serverCert).toString()
}
)
);
serverCert = fs.readFileSync('/data/org1-ca-chain.pem');
const peer1 = this.client.newPeer(
config.peers['peer1-org1'].url,
{
pem: Buffer.from(serverCert).toString()
}
);
channel.addPeer(peer1);
this.eventhubs = []
this.eventhubs.push(channel.newChannelEventHub(peer1));
serverCert = fs.readFileSync('/data/org2-ca-chain.pem');
const peer2 = this.client.newPeer(
config.peers['peer1-org2'].url,
{
'pem': Buffer.from(serverCert).toString()
}
);
channel.addPeer(peer2);
this.eventhubs.push(channel.newChannelEventHub(peer2));
this.channel = channel;
console.log(this.channel)
return this.channel.sendTransactionProposal(request);
Is there something wrong with my code or the way I do it? Can someone tell me what I am doing wrong? I've seen a few similar questions but those happened when composer was used mostly and I couldn't fix my problem with the answers from there,
You'd better check the user context of client I think.
user context has mspID. check whether mspId is Org1MSP or not.
The error could be because of the Certificates to sign the transaction.Double check your certificate received from CA and also checked the certificates and path used inside the docker container of peers.

Resources