An application process of fabric-sdk-go, a fabric-sdk-go implementation based on the technology route of Tongji

In one of my articles, I introduced the deployment test process of the Hyperledger Fabric v1.4.1 national secret version, but that article used the CLI when testing the Fabric. We know that the national secret transformation of a complete Fabric Hyperledger includes the three parts of the national secret transformation of Fabric source code, Fabric SDK and Fabric CA. Among them, the urgency of Fabric CA's requirements is not very high, but the requirements of the Fabric SDK's national secret transformation are real. Without it, there is no way to write programs to interact with Fabric. Therefore, this article takes a fabric-sdk-go-gm version open source on the Internet as an example, and takes the Fabric v1.4.1 (v1.4.6 also works) version of the national secret transformation as the underlying alliance chain, and briefly introduces the national secret fabric-sdk-go The use process.

1. Preparation

1. Refer to my article Fabric Hyperledger 1.4.1 National Secret Modification Version Centos Stand-alone Deployment and Test Process Deploy a national secret version of Fabric on this machine. After the deployment is complete, enter the first-networkdirectory and ./byfn.sh upstart a test network. Although that article talks about the operation in the Centos environment, it is also possible under Mac OS and Windows.
2. Download bolenzhang as an open source go-sdk. There is no requirement for the downloaded directory. It can be placed in the $GOPATH/src/github.com/hyperledgerdirectory and put together with Fabric.

cd $GOPATH/src/github.com/hyperledger/
git clone [email protected]:bolenzhang/fabric-go-sdk-gm.git

3. Run to go envcheck GO111MODULEwhether the environment variable is auto. It is not necessary to change it and make it take effect (under windows, check whether it takes effect several times, it may need to log out or restart)

2. Create a new application project

We use the national secret version of go-sdk, which cannot be used directly go modto manage dependencies. All dependencies need to be placed in the vendor directory, but we can use it first go modto download the dependent library.

cd $GOPATH/src
mkdir sdk_test
cd sdk_test
go mod init sdktest

Three, create a configuration file

Directly quote the sample SDK configuration file config.yaml given in this article using fabric-sdk-go operation chain code and save it as sdk_test/config.yaml, but there are the following points to note:

3.1、BCCSP

When applying the national secret go-sdk, this item should be commented out.

  # [Optional] BCCSP config for the client. Used by GO SDK.
  # BCCSP:
  #   security:
  #     enabled: true
  #     default:
  #       provider: "GM"
  #     hashAlgorithm: "GMSM3"
  #     softVerify: true
  #     level: 256

Because the SDK will automatically convert the algorithm, we don’t need to set it to GM. Of course, SWthere is no problem if you set it as the original configuration file . Here we use the default settings by default.

3.2、tlsCerts

  tlsCerts:
    # [Optional]. Use system certificate pool when connecting to peers, orderers (for negotiating TLS) Default: false
    systemCertPool: true

If you are using a Windows operating system, change it to false here. Note that there is a space between the colon and "true". If you are a system such as Centos or Ubuntu, you don't need to change it; if you are a Mac operating system, there will be some problems if you don't change it here, but we can modify sm2the source code to solve it. I'll talk about this later when you use it.

3.3, all paths

All path-related in the configuration file /Users/shitaibin/go/src/github.com/hyperledger/fabric/fabric-samplesshould be replaced with your local real path. Note that there is no under Windows /, it is estimated that it should be used \\(this is not sure).

Fourth, write test files

This article uses a simple main.gotest file as the test file. The writing method of the test file also refers to the article "Using fabric-sdk-go to operate chain code" mentioned above. Use your editor or vimcreate one in the project root directory with the main.gofollowing content:

package main

import (
	"fmt"
	"log"
	"time"

	"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 (
	org1CfgPath = "./config.yaml"
	ChannelID   = "mychannel"

	peer0Org1 = "peer0.org1.example.com"
	peer0Org2 = "peer0.org2.example.com"
)

func main() {
    
    
	sdk, err := fabsdk.New(config.FromFile(org1CfgPath))
	if err != nil {
    
    
		log.Panicf("failed to create fabric sdk: %s", err)
	}

	ccp := sdk.ChannelContext(ChannelID, fabsdk.WithUser("User1"))
	cc, err := channel.New(ccp)
	if err != nil {
    
    
		log.Panicf("failed to create channel client: %s", err)
	}

	query(cc)
	execute(cc)
	time.Sleep(5 * time.Second)
	query(cc)
}

func query(cc *channel.Client) {
    
    
	// new channel request for query
	req := channel.Request{
    
    
		ChaincodeID: "mycc",
		Fcn:         "query",
		Args:        packArgs([]string{
    
    "a"}),
	}
	// send request and handle response
	reqPeers := channel.WithTargetEndpoints(peer0Org1)

	response, err := cc.Query(req, reqPeers)
	if err != nil {
    
    
		fmt.Printf("failed to query chaincode: %s\n", err)
	}

	if len(response.Payload) > 0 {
    
    
		fmt.Printf("chaincode query success,the value is %s\n", string(response.Payload))
	}
}

func execute(cc *channel.Client) {
    
    
	args := packArgs([]string{
    
    "a", "b", "10"})
	req := channel.Request{
    
    
		ChaincodeID: "mycc",
		Fcn:         "invoke",
		Args:        args,
	}
	peers := []string{
    
    peer0Org1, peer0Org2}
	reqPeers := channel.WithTargetEndpoints(peers...)
	response, err := cc.Execute(req, reqPeers)
	if err != nil {
    
    
		fmt.Printf("failed to Execute chaincode: %s\n", err)
	}
	fmt.Printf("Execute chaincode success,txId:%s\n", response.TransactionID)
}

func packArgs(paras []string) [][]byte {
    
    
	var args [][]byte
	for _, k := range paras {
    
    
		args = append(args, []byte(k))
	}
	return args
}

The test file is very simple, first initialize the SDK and establish a channel, then query the contract, execute the transaction, and then query the contract to see if the value is updated.

Five, installation dependencies

Here comes the point: there are many operations here. We assume that you sdk_testare operating in the project root directory , and the SDK of the national secret version is also placed in the $GOPATH/src/github.com/hyperledger/directory as recommended :

go run main.go

The dependency will be installed first, and then an error will be reported when parsing the x509 certificate. Ignore it and the result is normal.
Then execute:

go mod vendor

Copy all dependencies to the vendor directory of the project.
Then execute:

rm go.mod
rm go.sum
rm -rf vendor/github.com/hyperledger/fabric-sdk-go
cp -r $GOPATH/src/github.com/hyperledger/fabric-go-sdk-gm vendor/github.com/hyperledger/fabric-sdk-go

The meaning of the above command is to delete go modthe relevant content, and use the national secret SDK to replace the native SDK.

Six, run the test

Let's run it again go run main.go. If you are prompted that some libraries are missing, you can open a new terminal and download it by referring to the following command:

mkdir -p $GOPATH/src/golang.org/x
cd $GOPATH/src/golang.org/x
git clone https://github.com/golang/crypto.git

After the download is complete, run the program in the original terminal. Here, there will be different results according to different operating systems:

1. Centos or Ubuntu

The operation is successful. From the output log, we can see that the value of a in the chain code is correct.

2、windows

An error will be reported when running under the windows environment (note that the systemCertPool in the configuration file under windows must be false):

# chaincodedemo/vendor/github.com/google/certificate-transparency-go/x509
vendor\github.com\google\certificate-transparency-go\x509\root_windows.go:112:3: cannot use uintptr(unsafe.Pointer(sslPara)) (type uintptr) as type syscall.Pointer in field value

This is because a library is too old and we need to update it manually.

git clone [email protected]:google/certificate-transparency-go.git

Copy the downloaded library to the directory corresponding to the vendor to replace it. Run go run main.goit again and it will succeed.

3 、 Mac OS

Because the Mac under the configuration file systemCertPoolis truein the country close version will find the files that do not correspond and initialized nil, thereby error. After testing, the original Fabric with the original fabric-sdk-go will not have this problem. This problem is because in the sm2/cert_pool.gofile, the possible file locations under Mac OS are not listed. According to the error message, we open it vendor/github.com/fabric-sdk-go/internal/github.com/tjfoc/gmsm/sm2/cert_pool.go(vscode is recommended) and you can see that there are two definitions:

// Possible certificate files; stop after finding one.
var certFiles = []string{
    
    
	"/etc/ssl/certs/ca-certificates.crt",                // Debian/Ubuntu/Gentoo etc.
	"/etc/pki/tls/certs/ca-bundle.crt",                  // Fedora/RHEL 6
	"/etc/ssl/ca-bundle.pem",                            // OpenSUSE
	"/etc/pki/tls/cacert.pem",                           // OpenELEC
	"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
}

// Possible directories with certificate files; stop after successfully
// reading at least one file from a directory.
var certDirectories = []string{
    
    
	"/etc/ssl/certs",               // SLES10/SLES11, https://golang.org/issue/12139
	"/system/etc/security/cacerts", // Android
}

The program initializes the system certificate pool in the file or path listed above.

Although there is a "/etc/ssl/certs"directory in Mac OS , it is empty. Therefore, after google it, certFilesa definition under Mac OS needs to be added "/usr/local/etc/openssl/cert.pem", // Macto it to change to:

// Possible certificate files; stop after finding one.
var certFiles = []string{
    
    
	"/etc/ssl/certs/ca-certificates.crt",                // Debian/Ubuntu/Gentoo etc.
	"/etc/pki/tls/certs/ca-bundle.crt",                  // Fedora/RHEL 6
	"/etc/ssl/ca-bundle.pem",                            // OpenSUSE
	"/etc/pki/tls/cacert.pem",                           // OpenELEC
	"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
	"/usr/local/etc/openssl/cert.pem",                   // Mac
}

Save and exit, and then run again go run main.go, the value of a will be output correctly.

Seven, summary

Well, from the perspective of this article, it is quite simple to test the national secret fabric-sdk-go with the national secret fabric (mainly the go-sdk application, the national secret sdk has been written by others). Thank you very much for the bolenzhangrelease of the national secret fabric-go-sdk-gm warehouse. Readers who use it can githubgive him an order star.

So far, the state secret transformation of Fabric Hyperledger based on the online open source version of the application is currently only one Fabric CA. After this CA etc. find a suitable open source national secret version, I will write an article to introduce its usage.

In order to test the CA, my local environment has been changed to the original Fabric. Therefore, most of the content of this article is written from memory, and there is no actual control step. If there are omissions or errors, please leave a message for correction or discussion.

Guess you like

Origin blog.csdn.net/weixin_39430411/article/details/108171042