Updated on 2023-03-07 GMT+08:00

Go SDK Demo

This section provides a Go SDK–based demo to help you develop your own Go client applications.

Preparations

  • Prepare an ECS.
  • Install the golang environment on the ECS. The Go version must be 1.12 or later, and earlier than 1.16.
  • Obtain the Go SDK source code. To obtain it, log in to the BCS console, click Use Cases and download the source code in the Go SDK Demo area.

Buying a BCS Instance

For details, see Deployment Using a CCE Cluster.

Installing and Instantiating a Chaincode

To obtain the chaincode used in this demo, go to the BCS console and choose Use Cases. Download the example Go chaincode in the Go SDK Demo area.

For details, see User Guide > Blockchain Management > Chaincode Management.

Downloading SDK Configurations and Certificates

  1. Log in to the BCS console.
  2. On the Instance Management page, click Download Client Configuration on an instance card.
  3. Select SDK Configuration File and set the parameters as described in the following table.

    Parameter

    Setting

    Chaincode Name

    Enter chaincode.

    NOTE:

    The chaincode name must be the same as the name specified during chaincode installation and instantiation.

    Certificate Root Path

    Enter /root/gosdkdemo/config.

    Channel

    Select channel.

    Organization & Peer

    Retain the default value.

    Select Orderer Certificate.

    Select Peer Certificates, select organization for Peer Organization, and select Administrator certificate.

  4. Click Download. The SDK configuration file and the administrator certificates for the orderer and organization organizations are downloaded.

Deploying the Application

  1. Download the Go SDK source code to the /root directory of the ECS and decompress the package.

    To obtain it, go to the BCS console and click Use Cases. Download the source code in the Go SDK Demo area.

  2. Decompress the .zip package obtained in Downloading SDK Configurations and Certificates and copy the orderer and peer folders and the sdk-config.json and sdk-config.yaml files from the configs folder to the /root/gosdkdemo/config/ directory.
  3. Find the /gosdkdemo/src/main.go file in the code and modify it as follows:
    1. Change the value of configFile to the actual name of the SDK configuration file, for example, demo-channel-sdk-config.yaml.
    2. Change the value of org to the hash value of organization.
      On the Channel Management page, click View Peer. The organization ID is the value of MSP ID without "MSP".
      var (    
          configFile = "/root/gosdkdemo/config/go-sdk-demo-channel-sdk-config.yaml"    
          org = " 9103f17cb6b4f69d75982eb48bececcc51aa3125"
       )
  4. Use go.mod to set GOPATH based on the actual installation path.
    1. Set the environment variable GO111MODULE to on.
      export GO111MODULE=on
    2. The following figure shows the go.mod file. Modify the "replace" line based on the actual installation path.
      module main  
      go 1.15
      //Specify the dependency to be imported and its version.
      require ( 
              github.com/bitly/go-simplejson v0.5.0 
              github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869// indirect 
              github.com/ghodss/yaml v1.0.0 
              github.com/hyperledger/fabric-sdk-go v1.0.0 
              github.com/pkg/errors v0.9.1 
              github.com/spf13/viper v1.7.1 
      )  
      //The project path /root/gosdkdemo/src is used as an example.
      replace github.com/hyperledger/fabric-sdk-go => /root/gosdkdemo/src/github.com/hyperledger/fabric-sdk-go
  5. Find the main.go file in the gosdkdemo/src directory and run the following command:
    go run main.go

Transferring Private Keys in Memory

Encrypt the private key file, decrypt it in the demo, and transfer it to Fabric SDK.

  1. For a TLS private key:

    In the initializeSdk function of the main.go file, invoke the function:

    encryptedtlsKey,err := GetTlsCryptoKey(org)  // Retrieve the encrypted TLSprivate key from the specified directory in the configuration file.
    // Decrypt encryptedtlsKey using the specified encryption and decryption method to obtain the decryptedTlsKey string.
    SetClientTlsKey(decryptedTlsKey)     // Transfer the decrypted TLS private key to Fabric SDK.
  2. For an MSP private key:

    In the insert function of the main.go file, invoke the function:

    encryptedbytekey,_:= GetPrivateKeyBytes(org)  // Retrieve the encrypted MSP private key from the specified directory in the configuration file.
    // Decrypt encryptedbytekey using the specified encryption and decryption method to obtain the decryptedKey string.
    SetPrivateKey(decryptedKey) //Assign the decrypted MSP private key to the global variable privateKey and import the variable.

Common APIs

fabric-sdk-go mainly uses the FabricSDK class, which can be constructed by using the NewSDK() method.

FabricClient, ChannelClient, ChannelMgmtClient, and ResourceMgmtClient can perform common operations of fabric-sdk-go.

  • FabricSDK

    FabricSDK uses the New() method to generate objects in pkg\fabsdk\fabsdk.go. The New() method has an Options parameter. The following is an example of generating FabricSDK:

    var opts []fabsdk.Option

    opts = append(opts, fabsdk.WithOrgid(org))

    opts = append(opts, fabsdk.WithUserName("Admin"))

    sdk, err = fabsdk.New(config.FromFile(configFile), opts...)

    configFile indicates the configuration file path. OrgId is the organization ID in the SDK configuration file.

    FabricSDK uses the NewSDK() method to generate objects in def/fabapi/fabapi.go. The NewSDK() method has an Options parameter. The following is an example of generating the Options parameter:

    deffab.Options{ConfigFile: configFile, LoggerFa
    logging.LoggerProvider(), UserName: sysadmin}

    ConfigFile indicates the configuration file path. LoggerFactory is optional. If it is not specified, logs are printed to the console by default.

  • FabricClient

    FabricClient provides the following common APIs:

    API

    Description

    Setting

    Returned Values

    CreateChannel

    Creates a channel.

    request

    CreateChannelRequest

    txn.TransactionID, error

    QueryChannelInfo

    Queries channel information.

    name string, peers

    []Peer

    Channel, error

    InstallChaincode

    Installs chaincodes in a blockchain.

    request

    InstallChaincodeRequest

    []*txn.TransactionPropos

    lResponse, string, error

    InstallChaincode

    Installs chaincodes in a blockchain.

    request

    InstallChaincodeRequest

    []*txn.TransactionPropos

    lResponse, string, error

    QueryChannels

    Queries created channels in a blockchain.

    peer Peer

    *pb.ChannelQueryResponse, error

    QueryInstalledChaincodes

    Queries installed chaincodes in a blockchain.

    peer Peer

    *pb.ChaincodeQueryResponse, error

  • ChannelClient

    ChannelClient provides chaincode query and invoking APIs.

    API

    Description

    Setting

    Returned Values

    Query

    Queries data by using the chaincode.

    request

    QueryRequest

    []byte, error

    QueryWithOpts

    Similar to the Query API, but can specify notifier, peers, and timeout with QueryOpts.

    request

    QueryRequest, opt

    QueryOpts

    []byte, error

    ExecuteTx

    Invokes the chaincode.

    request

    ExecuteTxRequest

    TransactionID,

    error

    ExecuteTxWithOpts

    Similar to the ExecuteTx API, but can specify notifier, peers, and timeout with the ExecuteTxOpts parameter.

    request

    ExecuteTxRequestopt ExecuteTxOpts

    TransactionID,

    error

  • ChannelMgmtCLient

    ChannelMgmtClient provides only two APIs: SaveChannel(req SaveChannelRequest) error and SaveChannelWithOpts(req SaveChannelRequest, opts SaveChannelOpts) error, which are used to create channels and need to invoke the createChannel() API of FabricClient.

  • ResourceMgmtClient

    ResourceMgmtClient provides chaincode lifecycle management APIs and an API for adding peers to a channel.

    The chaincode deleting API is provided by BCS and can only delete the chaincode installation package.

    API

    Description

    Setting

    Returned Values

    InstallCC

    Installs chaincodes.

    reqInstallCCRequest

    []InstallCCResponse, error

    InstallCCWithOpts

    Similar to the InstallCC API, but can specify peers with InstallCCOpts.

    reqInstallCCRequest,opts InstallCCOpts

    []InstallCCResponse, error

    InstantiateCC

    Instantiates chaincodes.

    channelID string,reqInstantiateCCRequest

    error

    InstantiateCCWithOpts

    Similar to the InstantiateCC API, but can specify peers and timeout with InstantiateCCOpts.

    channelID string,reqInstantiateCCRequest, optsInstantiateCCOpts

    error

    UpgradeCC

    Upgrades chaincodes.

    channelID string,reqUpgradeCCRequest

    error

    UpgradeCCWithOpts

    Similar to the UpgradeCC API, but can specify peers and timeout with UpgradeCCOpts.

    channelID string,reqUpgradeCCRequest, optsUpgradeCCOpts

    error

    DeleteCC

    Deletes chaincodes (only the chaincode installation packages).

    channelID string,reqDeleteCCRequest

    error

    DeleteCCWithOpts

    Similar to the DeleteCC API, but can specify peers and timeout with DeleteCCWithOpts.

    channelID string,reqDeleteCCRequest,opts DeleteCCOpts

    error

    JoinChannel

    Adds peers to a channel.

    channelID string

    error

    JoinChannelWithOpts

    Similar to the JoinChannel API, but can specify peers and timeout with JoinChannelOpts.

    channelID string,optsJoinChannelOpts

    error

    All APIs with options can specify peers. The peers can be generated through NewPeer(userName string, orgName string, url string, certificate string, serverHostOverride string, config config.Config) (fab.Peer, error) in def/fabapi/pkgfactory.go. Compared with the native NewPeer method, this method has two more parameters: userName and orgName, which are used by the peers to find the corresponding TLS certificate with bidirectional TLS.

Invoking a Contract

Main.go is a simple client application sample program, which is used to help you quickly get started with the client development process. The main steps are as follows:

//1. Import packages. The SDK package provides some APIs for user applications to access chaincodes.
import (
   "fmt"  
   "github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
   "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"    ......
)
//2. Create file configurations. This step encapsulates some common configurations required for application development, including the SDK configuration file path and organization name.
var (
   configFile = "/root/fabric-go-demo/config/go-sdk-demo-channel-sdk-config.yaml"
   org = "9103f17cb6b4f69d75982eb48bececcc51aa3125"
   ......
)
//3. Load the configuration file.
loadConfig()
//4. Initialize the SDK.
initializeSdk()
// 5. Execute the chaincode and write the data to the ledger. The key is "testuser", and the value is "100".
insert("insert",[][]byte{
   []byte("testuser"),
   []byte("100"),
})
// 6. Query the chaincode and output the query result. The key is "testuser".
query("query",
[][]byte{
[]byte("testuser"),
})
Table 1 Functions

Function

Description

getOptsToInitializeSDK

Parses the configuration file, and creates and returns the fabsdk.Option object.

GetDefaultChaincodeId

Parses the configuration file and returns chaincodeID.

GetDefaultChannel

Parses the configuration file and returns channelID.

UserIdentityWithOrgAndName

Verifies the identity of a user. The input parameters are the organization name and username. The verification result is returned.

ChannelClient

Create the *channel.Client object. The input parameters are the organization name, username, and channel ID. The *channel.Client object is returned.

insert

Writes data to the ledger. The input parameters are the method name of the chaincode and the key-value pair to be inserted. The write result is returned.

query

Queries chain data. The input parameters are the method name of the chaincode and the data to be queried. The query result is returned.