Fabric-sdk-go的测试案例分析(4)-在test-network案例中查询指定节点已安装的链码

准备工作

参考“Fabric-sdk-go的测试案例分析(3)-针对test-network编写1个SDK案例”,启动网络,创建1个通道,获取各节点的IP地址并配置/etc/hosts。

创建源程序文件

新建1个目录chaincodeDemo,新建2个文件。如下图。
Fabric-sdk-go的测试案例分析(4)-在test-network案例中查询指定节点已安装的链码_第1张图片
chaincodeDemo.go代码如下。

package main

import (
	"log"
	"strings"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config/lookup"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
	"github.com/pkg/errors"
)

const (
	channelID      = "mychannel"
	userName       = "User1"
	orgName        = "Org1"
	orgAdmin       = "Admin"
	ordererOrgName = "OrdererOrg"
	ccID           = "example_cc_e2e"
)

func main() {
	configPath := "./sdkdemo.yaml"
	configProvider := config.FromFile(configPath)
	sdk, err := fabsdk.New(configProvider)
	if err != nil {
		log.Fatalf("Failed to create new SDK: %s", err)
	}
	defer sdk.Close()

	found := queryChannel(sdk, channelID)
	if !found {
		panic("channel does not exist.\n")
	}

	configBackend, err := sdk.Config()
	targets, err := orgTargetPeers([]string{orgName}, configBackend)
	peer := targets[0]

	adminContext := sdk.Context(fabsdk.WithUser(orgAdmin), fabsdk.WithOrg(orgName))
	orgResMgmt, err := resmgmt.New(adminContext)
	resp, _ := orgResMgmt.QueryInstalledChaincodes(resmgmt.WithTargetEndpoints(peer))

	for _, ccInfo := range resp.Chaincodes {
		log.Printf("... found chaincode name:%s version:%s path:%s\n", ccInfo.Name, ccInfo.Version, ccInfo.Path)
	}
}

func orgTargetPeers(orgs []string, configBackend ...core.ConfigBackend) ([]string, error) {
	networkConfig := fab.NetworkConfig{}
	err := lookup.New(configBackend...).UnmarshalKey("organizations", &networkConfig.Organizations)
	if err != nil {
		return nil, errors.WithMessage(err, "failed to get organizations from config ")
	}

	var peers []string
	for _, org := range orgs {
		orgConfig, ok := networkConfig.Organizations[strings.ToLower(org)]
		if !ok {
			continue
		}
		peers = append(peers, orgConfig.Peers...)
	}
	return peers, nil
}

func queryChannel(sdk *fabsdk.FabricSDK, objChannelID string) bool {
	configBackend, err := sdk.Config()
	if err != nil {
		log.Fatalf("Failed to get config backend from SDK: %s", err)
	}
	targets, err := orgTargetPeers([]string{orgName}, configBackend)
	if err != nil {
		log.Fatalf("creating peers failed: %s", err)
	}

	clientContext := sdk.Context(fabsdk.WithUser(orgAdmin), fabsdk.WithOrg(orgName))
	resMgmtClient, err := resmgmt.New(clientContext)
	if err != nil {
		log.Fatalf("failed to query channel management client:%s", err)
	}
	channelQueryResponse, err := resMgmtClient.QueryChannels(
		resmgmt.WithTargetEndpoints(targets[0]),
		resmgmt.WithRetry(retry.DefaultResMgmtOpts))
	if err != nil {
		log.Fatalf("QueryChannels return error: %s", err)
	}
	found := false
	for _, channel := range channelQueryResponse.Channels {
		if channel.ChannelId == objChannelID {
			found = true
		}
	}
	return found
}

sdkdemo.yaml代码如下。

version: 1.0.0
client:
  organization: Org1
  logging:
    level: info
  cryptoconfig:
    path: /root/go/src/github.com/hyperledger/fabric/scripts/fabric-samples/test-network/organizations
  credentialStore:
    path: "/tmp/state-store"
    cryptoStore:
      path: /tmp/msp
  tlsCerts:
    client:
      key:
        path: /root/go/src/github.com/hyperledger/fabric/scripts/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/[email protected]/tls/client.key
      cert:
        path: /root/go/src/github.com/hyperledger/fabric/scripts/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/[email protected]/tls/client.crt
        
organizations:
  Org1:
    mspid: Org1MSP
    cryptoPath:  peerOrganizations/org1.example.com/users/{username}@org1.example.com/msp
    peers:
      - peer0.org1.example.com
  Org2:
    mspid: Org2MSP
    cryptoPath:  peerOrganizations/org2.example.com/users/{username}@org2.example.com/msp
    peers:
      - peer0.org2.example.com
      
peers:
  peer0.org1.example.com:
    url: peer0.org1.example.com:7051
    tlsCACerts:
      path: /root/go/src/github.com/hyperledger/fabric/scripts/fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem



编译并执行

分别执行go mod init,go build .,如下图。

Fabric-sdk-go的测试案例分析(4)-在test-network案例中查询指定节点已安装的链码_第2张图片
在这里插入图片描述

你可能感兴趣的:(Fabric,区块链)