I am new to hyperledger fabric and trying some hands on. I am trying to add and joined the peer into the channel using fabric SDK but I am getting ""[Remote.js]: Error: Failed to connect before the deadline URL:grpcs://localhost:7088"" this error.
I have used addPeer function of channel and after addition I tried to join the peer to channel using join channel operation. But after running the code I got the error I mentioned above. If any one can suggest how to add and join the peer using fabric API.
import { FileSystemWallet, Gateway } from 'fabric-network';
import * as path from 'path';
import { Peer } from 'fabric-client';
import { request } from 'https';
const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');
async function main() {
try {
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.ts application before retrying');
return;
}
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');
var opts ={
name: 'peer4.org1.example.com',
request_timeout: '5252',
'pem': '-----BEGIN CERTIFICATE-----\nMIICVzCCAf2gAwIBAgIQfdwd3s8+f0YvH2esgpia7TAKBggqhkjOPQQDAjB2MQsw\nCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy\nYW5jaXNjbzEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEfMB0GA1UEAxMWdGxz\nY2Eub3JnMS5leGFtcGxlLmNvbTAeFw0xOTEwMjIwNjA3MDBaFw0yOTEwMTkwNjA3\nMDBaMHYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH\nEw1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBvcmcxLmV4YW1wbGUuY29tMR8wHQYD\nVQQDExZ0bHNjYS5vcmcxLmV4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0D\nAQcDQgAEJBq3JFLV0LdNLxOBLS/BH1jh2AMjg6awzO5fz9faB0rIBj7xZg4sCwq4\nwA5M3y5kOjVDTZaEe/t+8o4DMZmBmaNtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1Ud\nJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1Ud\nDgQiBCB6UC4NGyvuVZ0Bmi7aWkju7bRm3jZvU9kNXrVgFeBa6TAKBggqhkjOPQQD\nAgNIADBFAiEArR3BiLVpA0z3K53wr+2Cjjtq0gmx2un9Nlgl352bhAoCIEh9dZCK\ny+JcrTBTWM57WZvmieVvf2uUN9UgJ2xHyK9o\n-----END CERTIFICATE-----\n',
sslcerti: 'peer4.org1.example.com',
}
var peer = new Peer('grpcs://localhost:7088', opts);
var channel = network.getChannel();
channel.addPeer(peer,'Org1MSP')
var request ={
target:[peer],
block :await channel.getGenesisBlock(),
txId :gateway.getClient().newTransactionID(true)
}
channel.joinChannel(request, 5252)
}
Failed to connect before the deadline URL:grpcs://localhost:7088 --> defines that it is trying to connect to server with respective port ,but it is failing .seems to be the service is not running or port is not properly bounded.
Make sure that either service is properly running or port is enabled.If any issue let me know
Related
I am trying to use GetTransactionByID from qscc.
Using the code from one of the examples, I tried running this :-
import fs from 'fs';
import yaml from 'js-yaml';
import path from 'path';
import { Wallets, Gateway } from 'fabric-network';
export async function submitTransaction(txnName: string, args: Array<any>) {
const walletPath = path.join(
process.cwd(),
'../identity/user/isabella/wallet',
);
const wallet = await Wallets.newFileSystemWallet(walletPath);
const gateway = new Gateway();
try {
const userName = 'isabella';
const yamlFile = path.join(
process.cwd(),
'../gateway/connection-org2.yaml',
);
let connectionProfile: any = yaml.load(
fs.readFileSync(yamlFile, 'utf8'),
);
let connectionOptions = {
identity: userName,
wallet: wallet,
discovery: { enabled: true, asLocalhost: true },
};
console.log('Connect to Fabric gateway.');
await gateway.connect(connectionProfile, connectionOptions);
console.log('Use network channel: mychannel.');
const network = await gateway.getNetwork('mychannel');
const contract = await network.getContract('qscc');
console.log('Submitting transaction');
const response = await contract.submitTransaction(txnName, ...args);
console.log('Transaction Response :-');
console.log(response);
} catch (error) {
console.log(`Error processing transaction. ${error}`);
console.log(error.stack);
} finally {
console.log('Disconnection from gateway');
gateway.disconnect();
}
}
submitTransaction('GetTransactionByID', [
'mychannel',
'f02954ae3723721459596f3ccdd89b36f8eca11d851f1aa7aeb4cb0bab148ab9',
]);
But I get the following error:-
2021-02-11T17:25:46.564Z - warn: [TransactionEventHandler]: strategyFail: commit failure for transaction "476873023684d8af68f5e05c965fee91be06255659eabd961601dad05501de03": TransactionError: Commit of transaction 476873023684d8af68f5e05c965fee91be06255659eabd961601dad05501de03 failed on peer peer0.org2.example.com:9051 with status INVALID_CHAINCODE
I can invoke the same using peer cli :-
peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile "$ORDERER_CA" -C mychannel -n qscc -c '{"function":"GetTransactionByID","Args":["mychannel", "f02954ae3723721459596f3ccdd89b36f8eca11d851f1aa7aeb4cb0bab148ab9"]}'
How can I invode this chaincode in node js application?
If you are just trying to query the ledger, you may want to use contract.evaluateTransaction instead of contract.submitTransaction.
From Fabric Node SDK doc for Fabric NetworkContract interface:
The Contract allows applications to:
Submit transactions that store state to the ledger using submitTransaction.
Evaluate transactions that query state from the ledger using evaluateTransaction.
I'm using the node-module basic-ftp to try to establish a secure connection via TLS/ SSL.
The server uses a wildcard CA-signed certificate as it's hostname. I can't seem to find an answer for the followig error code.
Connected to 1.1.1.1:21
< 220 Welcome to ftp.foo.com
> AUTH TLS
< 234 Using authentication type TLS
{ Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
at TLSSocket.emit (events.js:189:13)
at TLSSocket._finishInit (_tls_wrap.js:633:8) code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
}
Below you find the sample code:
const ftp = require("basic-ftp");
async establishFtpsConnection() {
const client = new ftp.Client();
client.ftp.verbose = true;
try {
await client.access({
host: "ftp.foo.com",
user: "bar",
password: "1234",
port: 21,
secure: true
});
const list = await client.list();
console.log(list);
} catch (err) {
console.log(err);
}
client.close();
}
NOTE: I'm trying to get it to work for my production environment. So disabling or rejecting unauthorization is NO option for me.
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
OR
rejectUnauthorized: false
Try this :
const ftp = require("basic-ftp");
async establishFtpsConnection() {
const client = new ftp.Client();
client.ftp.verbose = true;
const tlsOptions = {
cert: fs.readFileSync('fullchain.pem', 'ascii')
// a PEM containing the SERVER and ALL INTERMEDIATES
}
try {
await client.access({
host: "ftp.foo.com",
user: "bar",
password: "1234",
port: 21,
secure: true,
secureOptions:tlsOptions
});
const list = await client.list();
console.log(list);
} catch (err) {
console.log(err);
}
client.close();
}
If you are still getting an error then try to inject root SSL certificates
var sslRootCAs = require('ssl-root-cas/latest')
sslRootCAs.inject()
I am currently using IBM Blockchain Platform 2.0. I am connecting to it with fabric-network 1.4.0 and fabric-client 1.4.0.
When I listen for events from a simple node.js script on my machine, it works perfectly well. Here is the sample script:
const ccpPath = path.resolve('C:/Users/FlorianCastelain/Documents/GitHub/blockchain-code/node-red/fabric-server/config/org1/ibp2/user1/connection.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
const walletPath = path.resolve('C:/Users/FlorianCastelain/Documents/GitHub/blockchain-code/IBP2/CHAINCODE/public-resource/profile/wallet');
const wallet = new FileSystemWallet(walletPath);
const gateway = new Gateway();
const options = { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: false } };
await gateway.connect(ccp, options);
const network = await gateway.getNetwork('CHANNELNAME');
const contract = network.getContract('CCNAME');
const channel = network.getChannel();
const eventHub = channel.newChannelEventHub('IP:PORT');
let event = eventHub.registerChaincodeEvent('CCNAME', 'EVENTREGEX', (event, number, txid, status) => {
console.log(event);
console.log(event.payload.toString());
console.log(number);
}, (error) => {
console.log(error);
}, { startBlock: 0 });
eventHub.connect(true);
However, my goal is to include this code into node-red nodes (check here.
A bit of context: currently these nodes do not handle discovery, which may be needed. The purpose of my work is to include this into these nodes.
As a consequence, I tried to insert the code above into my nodes code, which gives the following: (same code, it is just a copy/paste)
else if (actionType === 'event') {
node.log('EVENT');
const ccPath = path.resolve('C:/Users/FlorianCastelain/Documents/GitHub/blockchain-code/node-red/fabric-server/config/org1/ibp2/user1/connection.json');
const ccp = JSON.parse(fs.readFileSync(ccPath, 'utf8'));
const walletPath = path.resolve('C:/Users/FlorianCastelain/Documents/GitHub/blockchain-code/IBP2/CHAINCODE/public-resource/profile/wallet');
const wallet = new FileSystemWallet(walletPath);
const gateway = new Gateway();
const options = { wallet, identity: 'user1', discovery: { enabled: true, asLocalHost: false } };
await gateway.connect(ccp, options);
const network = await gateway.getNetwork('CHANEL NAME');
const channel = network.getChannel();
const eventHub = channel.newChannelEventHub('IP:PORT');
let event = eventHub.registerChaincodeEvent('CCNAME', 'REGEX', (event, number, txid, status) => {
console.log(event);
console.log(event.payload.toString());
console.log(number);
}, (error) => {
console.log(error);
}, { startBlock: 0 });
eventHub.connect(true);
// const networkInfo = await connect(identityName, node.connection.discoveryEnabled, node.connection.discoveryAsLocalhost, channelName, contractName, node);
// const channel = networkInfo.network.getChannel();
// await subscribeToEvent(channel, contractName, msg.payload.peerName, msg.payload.startBlock,
// msg.payload.endBlock, msg.payload.timeout, msg.payload.eventName, node, msg);
} else if
It produces the following error:
{ Error: 14 UNAVAILABLE: Connect Failed
at Object.exports.createStatusError (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\common.js:91:15)
at ClientDuplexStream._emitStatusIfDone (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\client.js:233:26)
at ClientDuplexStream._receiveStatus (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\client.js:211:8)
at Object.onReceiveStatus (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\client_interceptors.js:1306:15)
at InterceptingListener._callNext (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\client_interceptors.js:618:8)
at C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\grpc\src\client_interceptors.js:1123:18
code: 14, metadata: Metadata { _internal_repr: {} }, details:
'Connect Failed' }
I checked fabric-network version on both "environment", it is 1.4.0
Does anyone has a clue on what can be the difference and/or what can cause this error?
Edit:
When testing the package when linking it to node-red via npm install PATH instead of using npm link, I get the following error:
{ Error: 14 UNAVAILABLE: failed to connect to all addresses
at Object.exports.createStatusError (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\common.js:91:15)
at ClientDuplexStream._emitStatusIfDone (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\client.js:233:26)
at ClientDuplexStream._receiveStatus (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\client.js:211:8)
at Object.onReceiveStatus (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:1306:15)
at InterceptingListener._callNext (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:618:8)
at C:\Users\FlorianCastelain\Documents\GitHub\node-red-contrib-fabric\node_modules\fabric-network\node_modules\fabric-client\node_modules\grpc\src\client_interceptors.js:1123:18
code: 14,
metadata: Metadata { _internal_repr: {} },
details: 'failed to connect to all addresses' }
Edit: More info from HLF logging. You can find the entire logs here
All addresses have been changed to ADDRESS or ADDRESS:PORT (depending on what was written), except localhost addresses, for security.
The current default (1.4.0-1.4.4) when discovery is used is for all returned ip addresses to be converted to localhost. You need to explicitly disable this. In your code I see you have tried but got the property name slightly wrong. It should be asLocalhost with a small h whereas you have used a capital H
joinChannel.js gives the following error:
Successfully loaded peeradmin from persistence
{ block:
{ header:
{ number: [Object],
previous_hash: [Object],
data_hash: [Object] },
data: { data: [Array] },
metadata: { metadata: [Array] } } }
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: access denied for [JoinChain][mychannel]: [Failed verifying that proposal's creator satisfies local MSP principal during channelless check policy with policy [Admins]: [This identity is not an admin]]
not good
Exactly, what is the error complaining about? I am having trouble pinpointing whether it's the peer admin private key, peer admin cert, peer tls cert, or some other configuration. I took the peer admin cert and added it to the IBP dashboard and did "Sync Certificates". What some things to check to make sure I am indeed specifying the correct credentials for the admin?
var Fabric_Client = require('fabric-client');
var path = require('path');
var fs = require('fs');
var fabric_client = new Fabric_Client();
var ordererTLSCert = fs.readFileSync('./orderercert.pem');
var peerAdminKey = Buffer.from(fs.readFileSync('./keystore-1.pem')).toString();
// var peerAdminCert = Buffer.from(fs.readFileSync('./admincert-1.pem')).toString()
var peerAdminCert = Buffer.from(fs.readFileSync('./signcert-1.pem')).toString();
fabric_client.setAdminSigningIdentity(peerAdminKey, peerAdminCert, 'org2');
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpcs://169.xx.xx.xx:xxxxx', {
pem: peerTlsCert,
'ssl-target-name-override': null,
});
var orderer = fabric_client.newOrderer(
'grpcs://nfxxx-orderer.us08.blockchain.ibm.com:xxxxx',
{
pem: Buffer.from(ordererTLSCert).toString(),
'ssl-target-name-override': null,
}
);
channel.addPeer(peer);
channel.addOrderer(orderer);
var tx_id = null;
tx_id = fabric_client.newTransactionID(true);
let g_request = {
txId: tx_id,
// orderer,
};
channel
.getGenesisBlock(g_request)
.then(block => {
console.log({ block });
tx_id = fabric_client.newTransactionID(true);
let j_request = {
targets: peer,
block,
txId: tx_id,
};
return channel.joinChannel(j_request, 30000);
})
.then(results => {
console.log(results);
if (results && results[0].response && results[0].response.status == 200) {
// good
console.log('good');
} else {
console.log('not good');
// not good
}
})
.catch(err => {
console.error(err);
});
When you join a peer to a channel, the transaction needs to be signed using the peer local admin. The local admin is identified by its certificate residing in the peer's msp/admincerts folder.
Try this:
tx_id = fabric_client.newTransactionID(true);
You need admin privileges to create or join to a channel
I am unable to install node chaincode using fabric-node-sdk.
I am getting the following error:
installChaincode error No identity has been assigned to this client
I am using following script
const Client = require("fabric-client");
const path = require("path");
const os = require("os");
const client = new Client();
const deploy = async () => {
const connectionOpts = {
name: "peer1",
"request-timeout": 7000,
pem: path.resolve(
os.homedir,
"/fabric-samples/chaincode-docker-devmode/msp/signcerts/peer.pem"
),
"ssl-target-name-override": "peer"
};
const peer = client.newPeer("grpc://172.18.0.3:7052", connectionOpts);
const request = {
targets: peer,
chaincodePath: path.resolve(
os.homedir + "/fabric-samples/chaincode/chaincode_example02/node"
),
chaincodeId: "myc",
chaincodeVersion: "v0",
chaincodeType: "node"
};
const result = await client.installChaincode(request, 6000);
console.log(await result);
};
deploy();
How do I assign identity to client?
In the documentation, it is not demonstrated what arguments it required and how to assign identity.
Peer node want to know who is making the transaction. Try using this method before the install chincode transaction:
client.setAdminSigningIdentity(private_key, certificate, mspid)
Where:
private_key: the private key PEM string
certificate: the PEM-encoded string of certificate
mspid: The Member Service Provider id for the local signing identity (i.e 'Org1MSP')
In the chaincode install request, you need the txId:
client.setAdminSigningIdentity(private_key, certificate, mspid)
const request = {
targets: peer,
chaincodePath: path.resolve(
os.homedir + "/fabric-samples/chaincode/chaincode_example02/node"
),
chaincodeId: "myc",
chaincodeVersion: "v0",
chaincodeType: "node",
txId: client.newTransactionID(true)
};
const result = await client.installChaincode(request, 6000);
console.log(await result);
I faced the same issue as well and it is resolved after adding the below line, i.e., channel initialization.
await channel.initialize({ discover: true });
source: https://fabric-sdk-node.github.io/master/tutorial-discovery.html