Fabric node sdk use service discovery function - node.js

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.

Related

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

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

ENDORSEMENT_POLICY_FAILURE in hyperledger fabric in case of private data

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

Can't invoke chaincode from SDK

I can invoke chaincode from my peer by the following command:
peer chaincode invoke -o coreOrderer.dip.com:7050 --tls --cafile /etc/hyperledger/tlsca.dip.com-cert.pem --tlsRootCertFiles /etc/hyperledger/fabric/tls/ca.crt -C dipchannel -n mycc --peerAddresses peer0.core.dip.com:7051 -c '{"Args":["query","a"]}'
And it works, I can see in the peer logs:
Entry chaincode: name:"mycc"
Exit chaincode: name:"mycc" (2ms)
And I can see result of this invoke in my chaincode container.
But when I'm trying to invoke from my code by SDK
req := channel.Request{
ChaincodeID: "mycc",
Fcn: "query",
Args: [][]byte{[]byte("a")},
}
resp, err := client.Execute(req)
I have empty response, and in the peer log I see:
Entry chaincode: name:"cscc"
Exit chaincode: name:"cscc" (1ms)
Entry chaincode: name:"lscc"
Exit chaincode: name:"lscc" (1ms)
Why it is calling "cscc" and "lscc" chaincodes and doesn't call to "mycc" ?
check this below are System Chaincodes
LSCC Lifecycle system chaincode handles lifecycle requests described above. >>> Chaincode lifecycle
CSCC Configuration system chaincode handles channel configuration on the peer side. >>> which helps regulate access control
QSCC Query system chaincode provides ledger query APIs such as getting blocks and transactions.
Note: In particular, install, instantiate and upgrade do not apply to system chaincodes.
System chaincode is used in Hyperledger Fabric to implement a number of system behaviors so that they can be replaced or modified as appropriate by a system integrator.
Unlike a user chaincode, a system chaincode is not installed and instantiated using proposals from SDKs or CLI. It is registered and deployed by the peer at start-up
COMING to your query >>>>
Check whether you are providing identity or not, as it enters into CSCC which is a regulator for ACL
Check below my code snippet
func (setup *FabricSetup) Query() (string, error) {
// Channel client is used to query and execute transactions
clientContext := setup.sdk.ChannelContext(setup.ChannelID, fabsdk.WithUser(setup.OrgAdmin))
client, err := channel.New(clientContext)
setup.client = client
// Prepare arguments
var args []string
args = append(args, "queryRate")
args = append(args, "001")
response, err := setup.client.Query(
channel.Request{
ChaincodeID: setup.ChainCodeID,
Fcn: args[0],
Args: [][]byte{[]byte(args[1])},
},
)
if err != nil {
return "", fmt.Errorf("failed to query: %v", err)
}
return string(response.Payload), nil
}

Cannot get state in Hyperledger fabric correctly?

Problem:
I have developed a Hyperledger fabric network and after that, I install a chain code in there. This is my Initialize ledger methods looks like.
async initLedger(stub, args) {
console.info("============= START : Initialize Ledger ===========");
let drivers = [];
drivers.push({
nic: "123",
firstName: "Saman",
lastName: "Frenando",
status: "Not verified",
licenceNo: "1234"
});
drivers.push({
nic: "124",
firstName: "Janith",
lastName: "Bentharaarachchi",
status: "Not verified",
licenceNo: "1235"
});
for (let i = 0; i < drivers.length; i++) {
drivers[i].docType = "driver";
console.log(drivers[i].nic);
await stub.putState(
drivers[i].nic,
Buffer.from(JSON.stringify(drivers[i]))
);
console.info("Added <--> ", drivers[i]);
}
console.info("============= END : Initialize Ledger ===========");
}
This is how I am retrieving those data.
async selectNthDriver(stub, args) {
if (args.length != 1) {
throw new Error(
"Incorrect number of arguments. Expecting NIC ex: 123"
);
}
let nic = args[0];
console.log(`nic: ${nic}`);
let driverAsBytes = await stub.getState(nic);
console.log("hi"+driverAsBytes);
if (!driverAsBytes || driverAsBytes.toString().length <= 0) {
throw new Error("Driver with NIC" + nic + " does not exist");
}
console.log(driverAsBytes.toString());
return driverAsBytes;
}
When I am Issuing this command on peer it successfully initializes the ledger.
peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C myc -n mycc -c '{"Args":["initLedger"]}'
By Issuing the following command when I try to retrieve a driver it leaves me an error by saying this.
Error: endorsement failure during invoke. response: status:500 message:"transaction returned with failure: Error: Driver with NIC123 does not exist"
peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C myc -n mycc -c '{"Args":["selectNthDriver","123"]}
This is the chaincode logs.
2019-05-09T05:18:51.184Z info [lib/handler.js]
info: [myc-09f261c4] Calling chaincode Init() succeeded.
Sending COMPLETED message back to peer
{"timestamp":"2019-05-09T05:18:51.184Z"} { fcn: 'initLedger', params:
[] }
============= START : Initialize Ledger =========== 123 Added <--> { nic: '123', firstName: 'Saman', lastName: 'Fernando', status:
'Not verified', licenceNo: '1234', docType: 'driver' } 124 Added
<--> { nic: '124', firstName: 'Janith', lastName:
'Bentharaarachchi', status: 'Not verified', licenceNo: '1235',
docType: 'driver' }
============= END : Initialize Ledger =========== { fcn: 'selectNthDriver', params: [ '123' ] } nic: 123 hi
Error: Driver with NIC123 does not exist
at selectNthDriver (/usr/local/src/mycc.js:494:13)
at
at process._tickCallback (internal/process/next_tick.js:188:7) 2019-05-09T05:43:42.430Z error [lib/handler.js]
error: [myc-e7aef847] Calling chaincode Invoke() returned
error response [Error: Driver with NIC123 does not exist].
Sending ERROR message back to peer
{"timestamp":"2019-05-09T05:43:42.430Z"}
And when I go to the CouchDB through browser It is not showing the data I initialized. It only shows this data.
{
"_id": "mycc",
"_rev": "1-5c5ecfec35f65ec74cbe52a52be96048",
"~version": "\u0000CgMBBwA=",
"_attachments": {
"valueBytes": {
"content_type": "application/octet-stream",
"revpos": 1,
"digest": "md5-SkPMcpW++nrvo5v00rCdRQ==",
"length": 424,
"stub": true
}
}
}
Can someone help me to find where am I doing wrong? Thank you.
You should use "query" command for querying a state from the ledger using the peer binary, the invoke command which you have used is for generating a transaction, which is not required for a query operation.
You should just try replacing invoke with query and it should look something like this:
peer chaincode query -o orderer.example.com:7050 -C myc -n mycc -c '{"Args":["selectNthDriver","123"]}
EDIT: Also please check for the following condition in your if statement in the selectNthDriver Method:
if (!driverAsBytes.toString())
Also please console for the same(driverAsBytes.toString()) in the line just before this if statement in your code.

fabric-sdk-go dialing connection timed out

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

Resources