Error instantiating chaincode in Hyperledger Fabric 1.1.0 - hyperledger-fabric

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.

Related

Hyperledger fabric - No response when using sendTransactionProposal() API

This is a tracing network with one channel composed of 3 Orgs, 1 anchor peer per organization, 1 MSP per org, and 1 CA for org3. And I'm not using TLS (because I couldn't find a dependable sample with TLS ON)
I'm trying to use Fabric-sdk-node to build a web front end for it, and I'm using fabcar sample. and when I use invoke.js (almost the same as the example), I find there is no reponse.
Store path:/root/hyperledger-fabric/test/webapp/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id: 8387c087b4b7b9210cdc68ff0ff7fda99c706bad052b9b5138c86df5463244be
Transaction proposal was bad
proposalResponses[0].response is bad
undefined
Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...
Failed to invoke successfully :: Error: Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...
and the code is
if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) {
isProposalGood = true;
console.log('Transaction proposal was good');
} else {
console.error('Transaction proposal was bad');
if (!proposalResponses) {
console.log('proposalResponses is bad');
}
if (!proposalResponses[0].response) {
console.log('proposalResponses[0].response is bad');
//console.log(proposalResponses[0].response.status);
}
}
When I check the the docker logs(in ca, peer0, orderer ), I find the only thing changed in orderer.trace.com
2021-05-04 07:41:41.136 UTC [comm.grpc.server] 1 -> INFO 007 streaming call completed {"grpc.start_time": "2021-05-04T07:40:41.77Z", "grpc.service": "orderer.AtomicBroadcast", "grpc.method": "Deliver", "grpc.peer_address": "172.21.0.8:39422", "error": "context finished before block retrieved: context canceled", "grpc.code": "Unknown", "grpc.call_duration": "59.36575566s"}
After several attempts, this error occurred on one occasion in peer0.sell.trace.com
2021-05-04 01:44:31.199 UTC [ConnProducer] NewConnection -> ERRO 034 Failed connecting to orderer.trace.com:7050 , error: context deadline exceeded
2021-05-04 01:44:31.200 UTC [deliveryClient] connect -> ERRO 035 Failed obtaining connection: Could not connect to any of the endpoints: [orderer.trace.com:7050]
2021-05-04 01:44:31.200 UTC [deliveryClient] try -> WARN 036 Got error: Could not connect to any of the endpoints: [orderer.trace.com:7050] , at 1 attempt. Retrying in 1s
I'm a very newbie in both fabric and nodejs, so any kind of help would be great. Thanks in advance.
NEW EDIT
My peer yaml
peer0.sell.trace.com:
container_name: peer0.sell.trace.com
image: hyperledger/fabric-peer:latest
environment:
- CORE_PEER_ID=peer0.sell.trace.com
- CORE_PEER_ADDRESS=peer0.sell.trace.com:7051
- CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.sell.trace.com:7051
- CORE_PEER_GOSSIP_BOOTSTRAP=peer1.sell.trace.com:7051
- CORE_PEER_LOCALMSPID=OrgSellMSP
- CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
- CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=test_default
- FABRIC_LOGGING_SPEC=INFO
#- FABRIC_LOGGING_SPEC=DEBUG
- CORE_PEER_GOSSIP_USELEADERELECTION=true
- CORE_PEER_GOSSIP_ORGLEADER=false
- CORE_PEER_PROFILE_ENABLED=true
##TLS
#- CORE_PEER_TLS_ENABLED=true
#- CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/fabric/tls/server.crt
#- CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/fabric/tls/server.key
#- CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/tls/ca.crt
- GODEBUG=netdns=go
working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
command: peer node start
volumes:
- /var/run/:/host/var/run/
- ./crypto-config/peerOrganizations/sell.trace.com/peers/peer0.sell.trace.com/msp:/etc/hyperledger/fabric/msp
- ./crypto-config/peerOrganizations/sell.trace.com/peers/peer0.sell.trace.com/tls:/etc/hyperledger/fabric/tls
#- ./crypto-config/peerOrganizations/sell.trace.com/users/Admin#sell.trace.com/tls:/etc/hyperledger/client/tls
ports:
- 1151:7051
- 1153:7053
networks:
default:
aliases:
- test
my connection.json
{
"name": "first-network-org_sell",
"version": "1.0.0",
"client": {
"organization": "org_sell",
"connection": {
"timeout": {
"peer": {
"endorser": "3000"
}
}
}
},
"organizations": {
"org_sell": {
"mspid": "OrgSellMSP",
"peers": [
"peer0.sell.trace.com",
"peer1.sell.trace.com"
]
}
},
"peers": {
"peer0.sell.trace.com": {
"url": "grpc://localhost:7051",
},
"peer1.sell.trace.com": {
"url": "grpc://localhost:7051",
}
}
}

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
}

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.

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

How to access a python file using chaincode in hyperledger fabric?

I am trying to run a python script using chaincode by this function:
cmd := exec.Command("python", "-c" ,"from land import *;print a.validate_proof(a.get_proof(1),'36e0fd847d927d68475f32a94efff30812ee3ce87c7752973f4dd7476aa2e97e','b8b1f39aa2e3fc2dde37f3df04e829f514fb98369b522bfb35c663befa896766')")
output, err := cmd.CombinedOutput()
if err != nil {
l := fmt.Sprint(err) + ": " + string(output)
return shim.Error(l)
} else {
return shim.Success([]byte(string(output)))
}
but I am getting the following error when trying to invoke the chaincode on the channel:
chaincode error (status: 500, message: exec: "python": executable file not found in $PATH:

Resources