How to access a python file using chaincode in hyperledger fabric? - 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:

Related

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
}

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.

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.

RSYNCWRAPPER: rsync exited with code 12

I'm using rsyncwrapper node module.
Here is my code:
rsync({
src: source_path,
dest: dest,
ssh: true,
recursive: true,
privateKey: keystring,
port: port,
args: ['--perms','--rsync-path="mkdir -p '+dest_path+' && rsync"']
},function (error,stdout,stderr,cmd) {
if ( error ) {
// failed
var data_response = {
'Status': 'Failed',
'Message': 'Rsync Failed=>'+error+stdout+stderr+cmd
};
logger.info("[Rsync] Response=>" + JSON.stringify(data_response));
console.log(error.message);
res.json(data_response);
} else {
console.log("Success");
var data_response = {
'Status': 'Success',
'Message': 'Rsync Success'
};
logger.info("[Rsync] Response=>" + JSON.stringify(data_response));
res.json(data_response);
}
});
However I get this error:
[2018-08-07 13:15:33.491] [INFO] JDWF-API - [Rsync] Response=>{"Status":"Failed","Message":"Rsync Failed=>Error: rsync exited with code 12WARNING : Unauthorized access to this system is forbidden and will be\nprosecuted by law. By accessing this system, you agree that your actions\nmay be monitored if unauthorized usage is suspected.\nmkdir: cannot create directory `/DATA/userWorkpace/devteam/7000003': Permission denied\nrsync: connection unexpectedly closed (0 bytes received so far) [sender]\nrsync error: error in rsync protocol data stream (code 12) at io.c(600) [sender=3.0.6]\nrsync /DATA/files/gs/7000003/input// wf-sync#192.168.1.23:/DATA/userWorkpace/devteam/7000003/input// --rsh \"ssh -p 47365 -i /DATA/jdwf-api/secure/wf-sync.dat\" --recursive --perms --rsync-path=\"mkdir -p /DATA/userWorkpace/devteam/7000003/input// && rsync\""}
rsync exited with code 12
I have given 777 permissions to the folder. It doesnt fix it. Can someone help me out please.

Groovy: Seems like a scope issue but cannot find where, can you?

I wrote some functions to help me writing Jenkins pipelines.
The following functions, are responsible to returning a shell command output:
def gen_uuid(){
randomUUID() as String
}
def sh_out(cmd){
String uuid = gen_uuid()
sh """( ${cmd} )> ${uuid}"""
String out = readFile(uuid).trim()
sh "set +x ; rm ${uuid}"
return out
}
That shown, here's another function:
Map get_started_by(){
withCredentials([ // Use Jenkins credentials ID of artifactory
[$class: 'UsernamePasswordMultiBinding', credentialsId: '0b8d591a-f4ce-XXXX-XXXX-faecb504d3d0', usernameVariable: 'J_USER', passwordVariable: 'J_PASS'],
]){
List startedBy = sh_out("""
set +x; curl -u ${J_USER}:${J_PASS} '${env.BUILD_URL}api/json' 2>/dev/null | \
python -mjson.tool | \
awk -F'"' '/(userId|userName)/{print \$4}'
""").split(/(\n)/)
return [
userId: startedBy[0],
userName: startedBy[1]
]
}
}
Which returns the userId and userName of the user who issue the job run.
Then, my problem is in this function:
def run_in_stage_func(String stage_name, Closure command, String sendTo){
String started_by = get_started_by()
String ulink = "<#${started_by['userId']}>"
String jlink = "(<${env.BUILD_URL}|Open>)"
println "============================================================"
stage (stage_name) {
try {
command()
if (currentBuild.result == 'FAILURE') {
error "Build failed, see log for further details."
}
println "============================================================"
} catch (Exception ex) {
def except = "${ex}"
slackSend channel: channel, color: 'danger', teamDomain: null, token: null,
message: " :${ulink} *Failed to build ${env.JOB_NAME}*! :x: ${jlink} (<!here|here>)"
echo "Pipeline failed at stage: ${stage_name}"
throw ex
}
}
}
When I run the job, I get the following error:
groovy.lang.MissingPropertyException: No such property: userId for class: java.lang.String
What could be the reason that the line ' String ulink = "<#${started_by['userId']}>" ' - is not working as intended?
You cast the result of get_started_by() to String explicitly. To fix it, change your code to
def started_by = get_started_by()
or
Map started_by = get_started_by()

Resources