1. 程式人生 > >HyperLeger Fabric SDK開發(六)——resmgmt

HyperLeger Fabric SDK開發(六)——resmgmt

HyperLeger Fabric SDK開發(六)——resmgmt

一、resmgmt簡介

1、resmgmt簡介

resmgmt支援在Fabric網路上建立和更新資源。resmgmt允許管理員建立、更新通道,並允許Peer節點加入通道。管理員還可以在Peer節點上執行與鏈碼相關的操作,例如安裝,例項化和升級鏈碼。
官方文件:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt

2、resmgmt使用流程

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

// 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

二、resmgmt常用介面

1、型別定義

定義鏈碼提案型別

type chaincodeProposalType int

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

定義安裝鏈碼請求

// 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
}

定義例項化鏈碼響應

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

定義升級鏈碼請求

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

定義升級鏈碼響應

// 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
}

2、配置簽名介面

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

3、獲取資源管理客戶端例項

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

4、建立簽名配置

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()選項傳遞此新例項以進行通道更新

5、安裝鏈碼

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     

6、例項化鏈碼

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

7、加入通道

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    

8、查詢通道

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        

9、獲取通道配置

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

10、查詢已安裝鏈碼

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      

11、查詢已例項化鏈碼

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      

12、建立通道

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

13、升級鏈碼

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

14、為客戶端設定過濾器

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   

15、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的預設超時配置。

三、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())
}