HyperLeger Fabric SDK開發(六)——resmgmt

HyperLeger Fabric SDK開發(六)——resmgmt

1、resmgmt簡介

一、resmgmt簡介

resmgmt支持在Fabric網絡上建立和更新資源。resmgmt容許管理員建立、更新通道,並容許Peer節點加入通道。管理員還能夠在Peer節點上執行與鏈碼相關的操做,例如安裝,實例化和升級鏈碼。
官方文檔:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmtgit

二、resmgmt使用流程

resmgmt使用基本流程以下:
A、準備客戶端上下文
B、建立資源管理客戶端
C、建立新通道
D、將Peer節點加入通道
E、將鏈碼安裝到Peer節點的文件系統
F、在通道上實例化鏈碼
G、查詢通道上的Peer節點,已安裝/實例化的鏈碼等
使用示例:github

// Create new resource management client
c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

// Read channel configuration
r, err := os.Open(channelConfig)
if err != nil {
    fmt.Printf("failed to open channel config: %s\n", err)
}
defer r.Close()

// Create new channel 'mychannel'
_, err = c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r})
if err != nil {
    fmt.Printf("failed to save channel: %s\n", err)
}

peer := mockPeer()

// Peer joins channel 'mychannel'
err = c.JoinChannel("mychannel", WithTargets(peer))
if err != nil {
    fmt.Printf("failed to join channel: %s\n", err)
}

// Install example chaincode to peer
installReq := InstallCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Package: &resource.CCPackage{Type: 1, Code: []byte("bytes")}}
_, err = c.InstallCC(installReq, WithTargets(peer))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

// Instantiate example chaincode on channel 'mychannel'
ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
instantiateReq := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}
_, err = c.InstantiateCC("mychannel", instantiateReq, WithTargets(peer))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

fmt.Println("Network setup completed")
// output:
// Network setup completed

2、resmgmt經常使用接口

一、類型定義

定義鏈碼提案類型網絡

type chaincodeProposalType int

// Define chaincode proposal types
const (
   InstantiateChaincode chaincodeProposalType = iota
   UpgradeChaincode
)

定義安裝鏈碼請求ide

// InstallCCRequest contains install chaincode request parameters
type InstallCCRequest struct {
   Name    string
   Path    string
   Version string
   Package *resource.CCPackage
}

定義安裝鏈碼響應工具

// InstallCCResponse contains install chaincode response status
type InstallCCResponse struct {
   Target string
   Status int32
   Info   string
}

定義實例化鏈碼請求區塊鏈

// InstantiateCCRequest contains instantiate chaincode request parameters
type InstantiateCCRequest struct {
   Name       string
   Path       string
   Version    string
   Args       [][]byte
   Policy     *common.SignaturePolicyEnvelope
   CollConfig []*common.CollectionConfig
}

定義實例化鏈碼響應this

// InstantiateCCResponse contains response parameters for instantiate chaincode
type InstantiateCCResponse struct {
   TransactionID fab.TransactionID
}

定義升級鏈碼請求url

// UpgradeCCRequest contains upgrade chaincode request parameters
type UpgradeCCRequest struct {
   Name       string
   Path       string
   Version    string
   Args       [][]byte
   Policy     *common.SignaturePolicyEnvelope
   CollConfig []*common.CollectionConfig
}

定義升級鏈碼響應code

// UpgradeCCResponse contains response parameters for upgrade chaincode
type UpgradeCCResponse struct {
   TransactionID fab.TransactionID
}

定義建立通道請求對象

//SaveChannelRequest holds parameters for save channel request
type SaveChannelRequest struct {
   ChannelID         string
   ChannelConfig     io.Reader             // ChannelConfig data source
   ChannelConfigPath string                // Convenience option to use the named file as ChannelConfig reader
   SigningIdentities []msp.SigningIdentity // Users that sign channel configuration
}

定義建立通道響應

// SaveChannelResponse contains response parameters for save channel
type SaveChannelResponse struct {
   TransactionID fab.TransactionID
}

二、配置簽名接口

func MarshalConfigSignature(signature *common.ConfigSignature) ([]byte, error)
MarshalConfigSignature爲由[]byte級聯的給定客戶端打包一個ConfigSignature(配置簽名)。
func UnmarshalConfigSignature(reader io.Reader) (*common.ConfigSignature, error)
UnmarshalConfigSignature將從reader讀取1個ConfigSignature爲[]byte並將其解碼。

三、獲取資源管理客戶端實例

type Client struct {
   ctx              context.Client
   filter           fab.TargetFilter
   localCtxProvider context.LocalProvider
}
func New(ctxProvider context.ClientProvider, opts ...ClientOption) (*Client, error)

New返回資源管理客戶端實例。
使用示例:

ctx := mockClientProvider()

c, err := New(ctx)
if err != nil {
    fmt.Println("failed to create client")
}

if c != nil {
    fmt.Println("resource management client created")
}
// output:
// resource management client created

四、建立簽名配置

func (rc *Client) CreateConfigSignature(signer msp.SigningIdentity, channelConfigPath string) (*common.ConfigSignature, error)
CreateConfigSignature爲指定的客戶端、自定義簽名者、channelConfigPath參數的通道配置建立一個簽名。
返回由SDK在內部簽名的ConfigSignature對象,能夠傳遞給WithConfigSignatures()選項。
func (rc *Client) CreateConfigSignatureData(signer msp.SigningIdentity, channelConfigPath string) (signatureHeaderData resource.ConfigSignatureData, e error)
CreateConfigSignatureData將準備一個SignatureHeader和用於簽名通道配置的完整簽名數據。
一旦SigningBytes在外部簽名(使用OpenSSL等外部工具簽署signatureHeaderData.SigningBytes),須要執行如下操做:
 A、建立一個common.ConfigSignature {}實例
 B、使用返回的字段'signatureHeaderData.signatureHeader'爲其SignatureHeader字段賦值。
 C、使用外部工具生成的'signatureHeaderData.signingBytes'簽名爲其Signature字段賦值。
  D、而後使用WithConfigSignatures()選項傳遞此新實例以進行通道更新

五、安裝鏈碼

func (rc *Client) InstallCC(req InstallCCRequest, options ...RequestOption) ([]InstallCCResponse, error)
InstallCC容許管理員將鏈代碼安裝到Peer節點的文件系統上。若是未在選項中指定Peer節點,默認屬於管理員MSP的全部Peer節點。
參數:
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關信息
options包含可選的請求選項
返回:Peer回覆的安裝鏈碼提案的響應
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

req := InstallCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Package: &resource.CCPackage{Type: 1, Code: []byte("bytes")}}
responses, err := c.InstallCC(req, WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

if len(responses) > 0 {
    fmt.Println("Chaincode installed")
}
// output:
// Chaincode installed

六、實例化鏈碼

func (rc *Client) InstantiateCC(channelID string, req InstantiateCCRequest, options ...RequestOption) (InstantiateCCResponse, error)
InstantiateCC使用可選的自定義選項(指定Peer節點,過濾的Peer節點,超時)實例化鏈碼。若是未在選項中指定Peer節點,則默認爲全部通道Peer。
參數:
channelID是必備的通道名稱
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關信息
options包含可選的請求選項
返回:帶有交易ID的實例化鏈碼響應
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
req := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}

resp, err := c.InstantiateCC("mychannel", req)
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to instantiate chaincode")
}

fmt.Println("Chaincode instantiated")
// output:
// Chaincode instantiated

七、加入通道

func (rc *Client) JoinChannel(channelID string, options ...RequestOption) error
JoinChannel容許Peer節點使用可選的自定義選項(指定Peer節點,已過濾的Peer節點)加入現有通道。若是未在選項中指定Peer節點,則將默認爲屬於客戶端MSP的全部Peer節點。
參數:
channelID是必備的通道名稱
options包含可選的請求選項
返回:若是加入通道失敗,返回錯誤
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

err = c.JoinChannel("mychannel", WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to join channel: %s\n", err)
}

fmt.Println("Joined channel")
// output:
// Joined channel

八、查詢通道

func (rc *Client) QueryChannels(options ...RequestOption) (*pb.ChannelQueryResponse, error)
QueryChannels查詢Peer節點已加入的全部通道的名稱。
參數:
options包含可選的請求選項,注意,必須使用WithTargetURLs或WithTargets請求選項指定一個目標Peer節點。
返回:Peer節點加入的全部通道
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryChannels(WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query channels: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved channels")
}
// output:
// Retrieved channels

九、獲取通道配置

func (rc *Client) QueryConfigFromOrderer(channelID string, options ...RequestOption) (fab.ChannelCfg, error)
QueryConfigFromOrderer從orderer節點返回通道配置。若是沒有使用選項提供orderer節點,則將默認爲通道的orderer節點(若是已配置)或隨機從配置中選取orderer節點。
參數:
channelID是必備的通道ID
options包含可選的請求選項
返回通道的配置

十、查詢已安裝鏈碼

func (rc *Client) QueryInstalledChaincodes(options ...RequestOption) (*pb.ChaincodeQueryResponse, error)
QueryInstalledChaincodes查詢Peer節點上已安裝的鏈碼。
參數:
options包含可選的請求選項。注意,必須使用WithTargetURLs或WithTargets請求選項指定一個目標Peer節點。
返回:指定Peer節點上已安裝的鏈碼列表
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryInstalledChaincodes(WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query installed chaincodes: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved installed chaincodes")
}
// output:
// Retrieved installed chaincodes

十一、查詢已實例化鏈碼

func (rc *Client) QueryInstantiatedChaincodes(channelID string, options ...RequestOption) (*pb.ChaincodeQueryResponse, error)
QueryInstantiatedChaincodes在指定的通道的Peer節點上的查詢實例化鏈碼。若是沒有在選項中指定Peer節點,則將在此通道上隨機查詢一個Peer節點。
參數:
channelID是必填通道名稱
options包含可選的請求選項
返回實例化鏈碼列表
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryInstantiatedChaincodes("mychannel", WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query instantiated chaincodes: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved instantiated chaincodes")
}
// output:
// Retrieved instantiated chaincodes

十二、建立通道

func (rc *Client) SaveChannel(req SaveChannelRequest, options ...RequestOption) (SaveChannelResponse, error)
SaveChannel建立或更新通道。
參數:
req包含必備的通道名稱和配置的相關信息
options包含可選的請求選項
 若是選項有簽名(WithConfigSignatures()或1個或多個WithConfigSignature()調用),則SaveChannel將使用選項的簽名而不是爲req中找到的SigningIdentities建立一個簽名。
確保req.ChannelConfigPath / req.ChannelConfig具備與簽名匹配的通道配置。
返回帶有交易ID的保存通道響應
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Printf("failed to create client: %s\n", err)
}

r, err := os.Open(channelConfig)
if err != nil {
    fmt.Printf("failed to open channel config: %s\n", err)
}
defer r.Close()

resp, err := c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r})
if err != nil {
    fmt.Printf("failed to save channel: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to save channel")
}

fmt.Println("Saved channel")
// output:
// Saved channel

使用WithOrdererEndpoint

c, err := New(mockClientProvider())
if err != nil {
    fmt.Printf("failed to create client: %s\n", err)
}

r, err := os.Open(channelConfig)
if err != nil {
    fmt.Printf("failed to open channel config: %s\n", err)
}
defer r.Close()

resp, err := c.SaveChannel(SaveChannelRequest{ChannelID: "mychannel", ChannelConfig: r}, WithOrdererEndpoint("example.com"))
if err != nil {
    fmt.Printf("failed to save channel: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to save channel")
}

fmt.Println("Saved channel")
// output:
// Saved channel

1三、升級鏈碼

func (rc *Client) UpgradeCC(channelID string, req UpgradeCCRequest, options ...RequestOption) (UpgradeCCResponse, error)
UpgradeCC使用可選的自定義選項(指定Peer節點,過濾的Peer節點,超時)升級鏈碼。若是沒有在選項中指定Peer節點,則將默認爲通道的全部Peer節點。
參數:
channelID是必備的通道名稱
req包含必備的鏈碼名稱,路徑,版本和背書策略的相關信息
options包含可選的請求選項
返回帶有交易ID的升級鏈碼響應
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
req := UpgradeCCRequest{Name: "ExampleCC", Version: "v1", Path: "path", Policy: ccPolicy}

resp, err := c.UpgradeCC("mychannel", req, WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to upgrade chaincode: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to upgrade chaincode")
}

fmt.Println("Chaincode upgraded")
// output:
// Chaincode upgraded

1四、爲客戶端設置過濾器

type ClientOption func(*Client) error

// WithDefaultTargetFilter option to configure default target filter per client
func WithDefaultTargetFilter(filter fab.TargetFilter) ClientOption

WithDefaultTargetFilter選項爲每一個客戶端配置默認目標過濾器
使用示例:

ctx := mockClientProvider()

c, err := New(ctx, WithDefaultTargetFilter(&urlTargetFilter{url: "example.com"}))
if err != nil {
    fmt.Println("failed to create client")
}

if c != nil {
    fmt.Println("resource management client created with url target filter")
}
// output:
// resource management client created with url target filter

1五、RequestOption參數構建

//RequestOption func for each Opts argument
type RequestOption func(ctx context.Client, opts *requestOptions) error
type requestOptions struct {
   Targets       []fab.Peer                        // target peers
   TargetFilter  fab.TargetFilter                  // target filter
   Orderer       fab.Orderer                       // use specific orderer
   Timeouts      map[fab.TimeoutType]time.Duration //timeout options for resmgmt operations
   ParentContext reqContext.Context                //parent grpc context for resmgmt operations
   Retry         retry.Opts
   // signatures for channel configurations, if set, this option will take precedence over signatures of SaveChannelRequest.SigningIdentities
   Signatures []*common.ConfigSignature
}

func WithConfigSignatures(signatures ...*common.ConfigSignature) RequestOption

WithConfigSignatures容許爲resmgmt客戶端的SaveChannel調用提供預約義的簽名。
func WithOrderer(orderer fab.Orderer) RequestOption
WithOrderer容許爲請求指定一個orderer節點。
func WithOrdererEndpoint(key string) RequestOption
WithOrdererEndpoint容許爲請求指定一個orderer節點。orderer將根據key參數查找。key參數能夠是名稱或url。
func WithParentContext(parentContext reqContext.Context) RequestOption
WithParentContext封裝了grpc父對象上下文
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

clientContext, err := mockClientProvider()()
if err != nil {
    fmt.Println("failed to return client context")
    return
}

// get parent context and cancel
parentContext, cancel := sdkCtx.NewRequest(clientContext, sdkCtx.WithTimeout(20*time.Second))
defer cancel()

channels, err := c.QueryChannels(WithParentContext(parentContext), WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query for blockchain info: %s\n", err)
}

if channels != nil {
    fmt.Println("Retrieved channels that peer belongs to")
}
// output:
// Retrieved channels that peer belongs to

func WithRetry(retryOpt retry.Opts) RequestOption
WithRetry設置重試選項
func WithTargets(targets ...fab.Peer) RequestOption
WithTargets容許覆蓋請求的目標Peer節點。
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

response, err := c.QueryChannels(WithTargets(mockPeer()))
if err != nil {
    fmt.Printf("failed to query channels: %s\n", err)
}

if response != nil {
    fmt.Println("Retrieved channels")
}
// output:
// Retrieved channels

func WithTargetEndpoints(keys ...string) RequestOption
WithTargetEndpoints容許覆蓋請求的目標Peer節點。目標由名稱或URL指定,SDK將建立底層Peer節點對象。
func WithTargetFilter(targetFilter fab.TargetFilter) RequestOption
WithTargetFilter爲請求啓用目標過濾器。
使用示例:

c, err := New(mockClientProvider())
if err != nil {
    fmt.Println("failed to create client")
}

ccPolicy := cauthdsl.SignedByMspMember("Org1MSP")
req := InstantiateCCRequest{Name: "ExampleCC", Version: "v0", Path: "path", Policy: ccPolicy}

resp, err := c.InstantiateCC("mychannel", req, WithTargetFilter(&urlTargetFilter{url: "http://peer1.com"}))
if err != nil {
    fmt.Printf("failed to install chaincode: %s\n", err)
}

if resp.TransactionID == "" {
    fmt.Println("Failed to instantiate chaincode")
}

fmt.Println("Chaincode instantiated")
// output:
// Chaincode instantiated

func WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption
WithTimeout封裝了超時類型、超時時間的鍵值對到選項,若是未提供,則使用config的默認超時配置。

3、resmgmt示例

var (
   sdk           *fabsdk.FabricSDK
   org           = "org1"
   user          = "Admin"
)

// 區塊鏈管理
func manageBlockchain() {
   // 代表身份
   ctx := sdk.Context(fabsdk.WithOrg(org), fabsdk.WithUser(user))

   cli, err := resmgmt.New(ctx)
   if err != nil {
      panic(err)
   }

   // 具體操做
   cli.SaveChannel(resmgmt.SaveChannelRequest{}, resmgmt.WithOrdererEndpoint("orderer.example.com"), resmgmt.WithTargetEndpoints())
}
相關文章
相關標籤/搜索