fabric-sdk-go dialing connection timed out - hyperledger-fabric

I want to connect to fabric using fabric-sdk-go,I query the chaincode,and it is correct,but when I invoke the chaincode,it is wrong.the logs blow:
```
$ go run main.go
100
Failed to invoke: CreateAndSendTransaction failed: SendTransaction failed: calling orderer 'orderer0.1530081632652.svc.cluster.local:32567' failed: Orderer Client Status Code: (2) CONNECTION_FAILED. Description: dialing connection timed out [orderer0.1530081632652.svc.cluster.local:32567]
```
I try change orderer0.1530081632652.svc.cluster.local to 9.115.76.16,but it is also the same problem.
blow is my congig.yaml about orderer:
```
orderers:
orderer0.1530081632652.svc.cluster.local:
url: orderer0.1530081632652.svc.cluster.local:32567
# these are standard properties defined by the gRPC library
# they will be passed in as-is to gRPC client constructor
grpcOptions:
ssl-target-name-override: orderer0.1530081632652.svc.cluster.local
# These parameters should be set in coordination with the keepalive policy on the server,
# as incompatible settings can result in closing of connection.
# When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
keep-alive-time: 20s
keep-alive-timeout: 400s
keep-alive-permit: false
fail-fast: false
# allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false
tlsCACerts:
# Certificate location absolute path
path: /Users/zhangyulong/Documents/gopath/src/github.com/hyperledger/DevOps/crypto-config/ordererOrganizations/1530081632652.svc.cluster.local/tlsca/tlsca.1530081632652.svc.cluster.local-cert.pem
```
and
```
orderer:
- pattern: (\w*)orderer0.1530081632652.svc.cluster.local(\w*)
urlSubstitutionExp: orderer0.1530081632652.svc.cluster.local:32567
sslTargetOverrideUrlSubstitutionExp: orderer0.1530081632652.svc.cluster.local
mappedHost: orderer0.1530081632652.svc.cluster.local
```
my main.go about invoke is :
```
package main
import (
"fmt"
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)
const (
channelID = "devopschannel"
orgName = "org1"
orgAdmin = "Admin"
ordererOrgName = "Orderer"
ccID = "devopschannel-example_cc2"
)
func main() {
configPath := "./config1.yaml"
configOpt := config.FromFile(configPath)
sdk, err := fabsdk.New(configOpt)
if err != nil {
fmt.Println("Failed to create new SDK: %s", err)
}
defer sdk.Close()
org1ChannelClientContext := sdk.ChannelContext(channelID, fabsdk.WithUser("Admin"), fabsdk.WithOrg("Org1"))
channelClient, err := channel.New(org1ChannelClientContext)
if err != nil {
fmt.Printf("Failed to create new channel client: %s\n", err)
}
var args = [][]byte{[]byte("query"),
[]byte("a"),
}
res, err := channelClient.Query(channel.Request{
ChaincodeID: ccID,
Fcn: "invoke",
Args: args,
})
if err != nil {
fmt.Printf("Failed to query: %s\n", err)
}
fmt.Println(string(res.Payload))
// eventID := ".*"
// // // Register chaincode event (pass in channel which receives event details when the event is complete)
// reg, notifier, err := channelClient.RegisterChaincodeEvent(ccID, eventID)
// if err != nil {
// fmt.Printf("Failed to register cc event: %s", err)
// }
// defer channelClient.UnregisterChaincodeEvent(reg)
res, err = channelClient.Execute(channel.Request{
ChaincodeID: ccID,
Fcn: "invoke",
Args: [][]byte{
[]byte("move"),
[]byte("a"),
[]byte("b"),
[]byte("100"),
},
})
if err != nil {
fmt.Printf("Failed to invoke: %s\n", err)
}
fmt.Println(string(res.Payload))
// select {
// case ccEvent := <-notifier:
// log.Printf("Received CC event: %#v\n", ccEvent)
// case <-time.After(time.Second * 20):
// log.Printf("Did NOT receive CC event for eventId(%s)\n", eventID)
// }
}
```

Your need to put the IP of the orderer in the config.yaml (orderer0.1530081632652.svc.cluster.local is unknown):
orderers:
orderer0.1530081632652.svc.cluster.local:
url: 9.115.76.16:32567
# these are standard properties defined by the gRPC library
# they will be passed in as-is to gRPC client constructor
grpcOptions:
ssl-target-name-override: orderer0.1530081632652.svc.cluster.local
# These parameters should be set in coordination with the keepalive policy on the server,
# as incompatible settings can result in closing of connection.
# When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
keep-alive-time: 20s
keep-alive-timeout: 400s
keep-alive-permit: false
fail-fast: false
# allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false
tlsCACerts:
# Certificate location absolute path
path: /Users/zhangyulong/Documents/gopath/src/github.com/hyperledger/DevOps/crypto-config/ordererOrganizations/1530081632652.svc.cluster.local/tlsca/tlsca.1530081632652.svc.cluster.local-cert.pem
And override the hostname in the configuration too, like that:
orderer:
- pattern: (\w*)orderer0.1530081632652.svc.cluster.local(\w*)
urlSubstitutionExp: 9.115.76.16:32567
sslTargetOverrideUrlSubstitutionExp: orderer0.1530081632652.svc.cluster.local
mappedHost: orderer0.1530081632652.svc.cluster.local

Related

2022-09-21T11:36:52.296Z - error: [Channel.js]: Error: 14 UNAVAILABLE: failed to connect to all addresses

Help me please! I have hyperledger fabric network with configuration:
ca-tls
rca-org0
rca-org1
rca-org2
orderer1-org0 (solo)
peer1-org1
peer2-org1
peer1-org2
peer2-org2
I have this config.yaml file:
name: "Network"
version: "1.0"
channels:
mychannel:
orderers:
- orderer1-org0
peers:
peer1-org1:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true
discover: true
peer2-org1:
endorsingPeer: false
chaincodeQuery: true
ledgerQuery: true
eventSource: true
discover: false
peer1-org2:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true
discover: true
peer2-org2:
endorsingPeer: false
chaincodeQuery: true
ledgerQuery: true
eventSource: true
discover: false
organizations:
org0:
mspid: org0MSP
orderers:
- orderer1-org0
certificateAuthorities:
- rca-org0
adminPrivateKey:
path: path/to/org0/admin/msp/keystore/key.pem
signCert:
path: path/to/org0/admin/msp/signcerts/cert.pem
org1:
mspid: org1MSP
peers:
- peer1-org1
# - peer2-org1
certificateAuthorities:
- rca-org1
adminPrivateKey:
path: path/to/org1/admin/msp/keystore/key.pem
signedCert:
path: path/to/org1/admin/msp/signcerts/cert.pem
org2:
mspid: org2MSP
peers:
- peer1-org2
# - peer2-org2
certificateAuthorities:
- rca-org2
adminPrivateKey:
path: path/to/org2/admin/msp/keystore/key.pem
signedCert:
path: path/to/org2/admin/msp/signcerts/cert.pem
orderers:
orderer1-org0:
url: grpcs://orderer1-org0:7050
grpcOptions:
ssl-target-name-override: orderer1-org0
grpc-max-send-message-length: 4194304
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
peers:
peer1-org1:
url: grpcs://172.19.0.9:7051
grpcOptions:
ssl-target-name-override: peer1-org1
grpc.keepalive_time_ms: 600000
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
peer2-org1:
url: grpcs://172.19.0.9:7051
grpcOptions:
ssl-target-name-override: peer2-org1
grpc.keepalive_time_ms: 600000
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
peer1-org2:
url: grpcs://172.19.0.9:7051
grpcOptions:
ssl-target-name-override: peer1-org2
grpc.keepalive_time_ms: 600000
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
peer2-org2:
url: grpcs://172.19.0.9:7051
grpcOptions:
ssl-target-name-override: peer2-org2
grpc.keepalive_time_ms: 600000
tlsCACerts: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
certificateAuthorities:
ca-tls:
url: https://0.0.0.0:7062
httpOptions:
verify: false
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
registrar:
- enrollId: tls-ca-admin
enrollSecret: tls-ca-adminpw
caName: ca-tls
rca-org0:
url: https://0.0.0.0:7063
httpOptions:
verify: false
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
registrar:
- enrollId: rca-org0-admin
enrollSecret: rca-org0-adminpw
caName: rca-org0
rca-org1:
url: https://0.0.0.0:7064
httpOptions:
verify: false
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
registrar:
- enrollId: rca-org1-admin
enrollSecret: rca-org1-adminpw
caName: rca-org1
rca-org2:
url: https://0.0.0.0:7065
httpOptions:
verify: false
tlsCACerts:
path: path/to/org0/msp/tlscacerts/tls-ca-cert.pem
registrar:
- enrollId: rca-org2-admin
enrollSecret: rca-org2-adminpw
caName: rca-org2
My API code below:
// create mychannel instance
let channel = new Channel('mychannel', client1);
// get certificates from couchdb wallet
let couchdbWallet = await Wallets.newCouchDBWallet("http://xxxxx:xxxxxxx#localhost:5984");
let user5 = await couchdbWallet.get('user5');
if (user5) {
let user5Cert = user5.credentials.certificate;
let user5Key = user5.credentials.privateKey;
let mspId = 'org1MSP';
await client1.initCredentialStores();
let cryptoSuite = client1.getCryptoSuite();
let keyObj = await cryptoSuite.importKey(user5Key);
let user5PubKey = keyObj._key.pubKeyHex;
let user5PrvKeyHex = keyObj._key.prvKeyHex;
let signer = new Signer(cryptoSuite, keyObj);
// create instance of signing identity
let signingIdentity = new SigningIdentity(
user5Cert,
user5PubKey,
'org1MSP',
cryptoSuite,
signer
);
// 1. generate unsigned transaction proposal
let transactionProposal = {
fcn: 'Mint',
args: ['1000'],
chaincodeId: 'token-erc-20',
channelId: 'mychannel'
}
let { proposal, txId } = await channel.generateUnsignedProposal(
transactionProposal,
mspId,
user5Cert,
true
);
console.log('*******proposal*****:\n', proposal);
console.log('*******Tx Id******\n', txId);
// now we have the 'unsigned proposal' for this tx
// 2. calculate the hash of the tx proposal bytes
let proposalBytes = proposal.toBuffer(); // the proposal comes from step 1
// 3. calculate the signature for this tx proposal
let signedProposal = signingIdentity.sign(proposalBytes);
console.log('********signedProposal********\n:', signedProposal);
// 4. send the signed tx proposal to peer(s)
let tlscaRootCert = readFileSync(tlscaRootCertPATH, { encoding: 'utf-8' });
console.log('tlscaRootCert: ', typeof tlscaRootCert);
let peer1org1 = client1.newPeer('grpcs://172.19.0.9:7051',
{
pem: tlscaRootCert,
}
);
let targets = new Array();
targets.push(peer1org1);
let sendSignedProposalReq = { signedProposal, targets };
let proposalResponses = await channel.sendSignedProposal(sendSignedProposalReq);
// check the proposal responces, if all good, commit the tx
// 5. similar to step 1, generate an unsigned tx
let commitReq = {
proposalResponses,
proposal,
};
let commitProposal = await channel.generateUnsignedTransaction(commitReq);
/// 6. similar to step 3, sign the unsigned tx with the user's private key
let commitProposalBytes = commitProposal.toBuffer();
let signedCommitProposal = signingIdentity.sign(commitProposalBytes);
// 7. commit the signed tx
let response = await channel.sendSignedTransaction({
signedTransaction: signedCommitProposal,
request: commitReq,
});
console.log('**********response from orderer after commit signed tx********\n', response);
// response.status should be 'SUCCESS' if the commit succeed
if (response.status === 'SUCCESS') {
// connect to event channel hub
let eventChannelHub = new ChannelEventHub(channel);
// 8. similar to step 1, generate an unsigned eventHub registration for the ChannelEventHub
let unsigneEvent = eventChannelHub.generateUnsignedRegistration({
certificate: user5Cert,
mspId
});
// 9. similar to step 3, sign the unsigned eventhub registration with the user's private key
let unsignEventBytes = unsigneEvent.toBuffer();
let signedEvent = signingIdentity.sign(unsignEventBytes);
// 10. register this ChannelEventHub at peer
let connectEventChannel = eventChannelHub.connect({ signedEvent });
console.log('***********connectEventChannel*********\n', connectEventChannel);
}
}
I try to submit transaction.
But every time I receive this error:
docker-compose.yaml logs
2022-09-21T11:36:52.296Z - error: [Channel.js]: Error: 14 UNAVAILABLE: failed to connect to all addresses
peer1-org1 container logs:
2022-09-21 11:25:08.606 UTC 0062 WARN [endorser] ProcessProposal -> Failed to preProcess proposal error="error validating proposal: access denied: channel [mychannel] creator org [org1MSP]"
2022-09-21 11:25:08.606 UTC 0063 INFO [comm.grpc.server] 1 -> unary call completed grpc.service=protos.Endorser grpc.method=ProcessProposal grpc.peer_address=172.19.0.1:59086 error="error validating proposal: access denied: channel [mychannel] creator org [org1MSP]" grpc.code=Unknown grpc.call_duration=15.47295ms
Also I receive this error now:
2022-09-21T13:01:10.858Z - error: [Channel.js]: sendTransaction - no valid endorsements found
How can I resolve this problem?
From peer logs, it seems like transaction submitter is not having access to the channel. Make sure the user identify is valid and the user's organization joined the channel. This error may come also if the MSP name given is wrong. MSP name is case sensitive.

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 instantiating chaincode in Hyperledger Fabric 1.1.0

I am trying to instantiate chaincode in Hyperledger Fabric peer 1.1.0. I have downloaded 1.1.0 version fabric samples and docker containers. The fabcar application got instantiated successfully.
However when I instantiate my chaincode, the peer quits with the following error.
2019-06-29 12:01:47.916 UTC [kvledger] CommitWithPvtData -> INFO 042 Channel [mychannel]: Committed block [3] with 1 transaction(s)
panic: assignment to entry in nil map
goroutine 569 [running]:
github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb.createCouchdbDocJSON(0xc422170890, 0x6, 0x0, 0x0, 0xc422170898, 0x4, 0x4, 0xc422170ae0, 0xc42001e000, 0xc42001e070, ...)
/opt/gopath/src/github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb.go:984 +0x1d8
github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb.(*VersionedDB).processUpdateBatch(0xc4215691d0, 0xc4217c7df0, 0x0, 0x0, 0x0, 0xc422170898, 0x4)
/opt/gopath/src/github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb.go:669 +0x550
github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb.(*VersionedDB).ApplyUpdates.func1(0xc422170eb0, 0xc42000eb68, 0xc4215691d0, 0xc422197140, 0xc422170870, 0x7)
/opt/gopath/src/github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb.go:577 +0x8a5
created by github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb.(*VersionedDB).ApplyUpdates
/opt/gopath/src/github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb.go:509 +0x11d
As I can see above, it is not taking go code from $GOPATH which is /home/ubuntu/software/golang.
I have installed the fabric and samples using the command.
as mentioned in
https://hyperledger-fabric.readthedocs.io/en/release-1.4/install.html
passing arguments "1.1.0 1.1.0 0.4.15"
I could see that the chaincode init method gets executed from the application logs.
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("Init firing.")
// Initialize the collection of commercial paper keys
fmt.Println("Initializing user accounts")
//t.createUser(stub, []string{"importerBank", "importerBank", "Importer Bank"})
//t.createUser(stub, []string{"customs", "customs", "Customs"})
//t.createUser(stub, []string{"exporterBank", "exporterBank", "Exporter Bank"})
//t.createUser(stub, []string{"exporter", "exporter", "Exporter"})
fmt.Println("Initializing LC keys collection if not present")
valAsbytes, err := stub.GetState("LCKeys")
if err == nil {
var keys []string
err = json.Unmarshal(valAsbytes, &keys)
fmt.Println("Existing LC : %v", keys);
if len(keys) > 0 {
for _, key := range keys {
valAsbytes, err := stub.GetState(key)
if err == nil {
var lc LC
err = json.Unmarshal(valAsbytes, &lc)
if err == nil {
if lc.CurrentStatus == "" {
lc.CurrentStatus = "Created"
keysBytesToWrite, _ := json.Marshal(lc)
if err == nil {
err = stub.PutState(key, keysBytesToWrite)
if err != nil {
fmt.Println("Error writing LC to chain" + err.Error())
}
}
}
}
}
}
}
}
fmt.Println("Initialization complete")
I would like to know why the peer quits?
orderer.example.com:
container_name: orderer.example.com
image: hyperledger/fabric-orderer
environment:
ORDERER_GENERAL_LOGLEVEL=debug
ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
ORDERER_GENERAL_GENESISMETHOD=file
ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
ORDERER_GENERAL_LOCALMSPID=OrdererMSP
ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/msp/orderer/msp
GODEBUG=netdns=go
working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
command: orderer
ports:
7050:7050
volumes:
./config/:/etc/hyperledger/configtx
./crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/:/etc/hyperledger/msp/orderer
./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/msp/peerOrg1
networks:
basic
Try adding - GODEBUG=netdns=go in the environment section of the docker compose file for every peer and orderer.

Error initializing the network channel from node sdk in hyperledger fabric

Background:
I have modified the first-network files (to a network with 2 Orgs and 1 peer in each of them) and installed my own chaincode on it. Additionally I have made a connection.yaml file to interact with the network.
Problem:
But when I try to get the network channel & establish the gateway from nodeSDK, I encounter this error:
error: [Network]: _initializeInternalChannel: Unable to initialize
channel. Attempted to contact 2 Peers. Last error was Error: 2
UNKNOWN: Stream removed
Failed to evaluate transaction: Error: Unable to initialize channel.
Attempted to contact 2 Peers. Last error was Error: 2 UNKNOWN: Stream
removed
Below you can find the code on my client side. The error probably arises when gateway.getNetwork('mychannel') is executed.
let connectionProfile = yaml.safeLoad(fs.readFileSync('./connection.yaml', 'utf8'));
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(connectionProfile, { wallet, identity: 'user1', discovery: { enabled: false } });
// 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('bankpeerContract');
var result = await contract.evaluateTransaction('queryAllStamps');
This is my connection.yaml file:
---
name: mychannel.firstnetwork.connectionprofile
x-type: "hlfv1"
description: "BankPeerContract methods will be used through this profile"
version: "1.0"
channels:
mychannel:
orderers:
- orderer.example.com
peers:
peer0.org1.example.com:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true
peer0.org2.example.com:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true
organizations:
Org1:
mspid: Org1MSP
peers:
- peer0.org1.example.com
certificateAuthorities:
- certificate-authority-org1
adminPrivateKey:
path: ../first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin#org1.example.com/msp/keystore/63145b12cd86abb07b6b5797c5e9506faa8f799e81d3c71d11a6a60840e3b6ae_sk
signedCert:
path: ../first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin#org1.example.com/msp/signcerts/Admin#org1.example.com-cert.pem
Org2:
mspid: Org2MSP
peers:
- peer0.org2.example.com
certificateAuthorities:
- certificate-authority-org2
adminPrivateKey:
path: ../first-network/crypto-config/peerOrganizations/org2.example.com/users/Admin#org2.example.com/msp/keystore/4d9b19fdcce70620b45760f5d62c7c877200ab38553b7a8b85245b04ca0e8bdd_sk
signedCert:
path: ../first-network/crypto-config/peerOrganizations/org2.example.com/users/Admin#org2.example.com/msp/signcerts/Admin#org2.example.com-cert.pem
orderers:
orderer.example.com:
url: grpc://localhost:7050
grpcOptions:
ssl-target-name-override: orderer.example.com
tlsCACerts:
path: ../first-network/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
peers:
peer0.org1.example.com:
url: grpc://localhost:7051
grpcOptions:
ssl-target-name-override: peer0.org1.example.com
request-timeout: 120001
tlsCACerts:
path: ../first-network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
peer0.org2.example.com:
url: grpc://localhost:9051
grpcOptions:
ssl-target-name-override: peer0.org2.example.com
request-timeout: 120001
tlsCACerts:
path: ../first-network/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/msp/tlscacerts/tlsca.org2.example.com-cert.pem
certificateAuthorities:
ca-org1:
url: http://localhost:7054
httpOptions:
verify: false
tlsCACerts:
path: ../first-network/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem
registrar:
- enrollId: admin
enrollSecret: adminpw
caName: certificate-authority-org1
ca-org2:
url: http://localhost:8054
httpOptions:
verify: false
tlsCACerts:
path: ../first-network/crypto-config/peerOrganizations/org2.example.com/ca/ca.org2.example.com-cert.pem
registrar:
- enrollId: admin
enrollSecret: adminpw
caName: certificate-authority-org2
I have been unable to figure out whether there is some problem with connection.yaml file or there is something wrong within the network.
BYFN/EFYN enable TLS on all of the Fabric nodes (peers, orderers, certificate authorities) to secure communications. Your connection profile has "grpc://" and "http://" URLs - these should be changed to "grpcs://" and "https://". It looks like the TLS CA certificates are correct.

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