1. 程式人生 > >HyperLeger Fabric SDK開發(四)——channel

HyperLeger Fabric SDK開發(四)——channel

HyperLeger Fabric SDK開發(四)——channel

一、channel簡介

1、channel 簡介

pkg/client/channel支援訪問Fabric網路上的通道。channel客戶端例項提供與指定通道上的Peer節點進行互動的處理函式。channel客戶端可以在指定通道上查詢鏈碼,執行鏈碼以及註冊或登出鏈碼事件。如果應用程式需要與Fabric網路的多條通道進行互動,需要為每條通道建立一個單獨的通道客戶端例項。
官方文件:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/channel

2、channel使用流程

channel使用流程如下:
A、準備通道客戶端上下文
B、建立通道客戶端
C、執行鏈碼
D、查詢鏈碼
channel使用示例如下:

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

response, err := c.Query(Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("query"), []byte("data")}})
if err != nil {
    fmt.Printf("failed to query chaincode: %s\n", err)
}

fmt.Println(string(response.Payload))
// output:
// abc

二、channel常用介面

1、型別定義

// Request 包含查詢和執行一個呼叫交易的引數 
type Request struct {
    ChaincodeID  string
    Fcn          string
    Args         [][]byte
    TransientMap map[string][]byte

    // InvocationChai包含元資料,某些選擇服務實現使用元資料來選擇滿足呼叫鏈中所有鏈碼的背書    
     // 策略的背書節點
    // Each chaincode may also be associated with a set of private data collection names
    // which are used by some Selection Services (e.g. Fabric Selection) to exclude endorsers
    // that do NOT have read access to the collections.
    // The invoked chaincode (specified by ChaincodeID) may optionally be added to the invocation
    // chain along with any collections, otherwise it may be omitted.
    InvocationChain []*fab.ChaincodeCall
}

//Response包含執行和查詢一個呼叫交易的響應引數
type Response struct {
    Proposal         *fab.TransactionProposal
    Responses        []*fab.TransactionProposalResponse
    TransactionID    fab.TransactionID
    TxValidationCode pb.TxValidationCode
    ChaincodeStatus  int32
    Payload          []byte
}

2、獲取客戶端例項

type Client struct {
    context      context.Channel
    membership   fab.ChannelMembership
    eventService fab.EventService
    greylist     *greylist.Filter
    clientTally  // nolint
}

通道客戶端支援訪問Fabric網路上的通道。為了與特定通道的Peer節點進行互動,通道客戶端例項提供了一個處理程式。 如果應用程式需要與多個通道進行互動,應該為每個通道建立一個單獨的通道客戶端例項。 通道客戶端只支援非管理功能。

type ClientOption func(*Client) error
func New(channelProvider context.ChannelProvider, opts ...ClientOption) (*Client, error)

返回通道Client例項。通道客戶端可以在特定通道上查詢鏈碼,執行鏈碼以及註冊/登出鏈碼事件。
使用示例:

ctx := mockChannelProvider("mychannel")

c, err := New(ctx)
if err != nil {
    fmt.Println(err)
}

if c != nil {
    fmt.Println("channel client created")
} else {
    fmt.Println("channel client is nil")
}
// output:
// channel client created   

3、執行交易

func (cc *Client) Execute(request Request, options ...RequestOption) (Response, error)
使用請求和可選的請求選項進行準備並執行事務。
引數: 
request包含必備鏈碼ID和函式的相關資訊
options包含可選的請求選項
返回Peer的提案回覆
使用示例:

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

_, err = c.Execute(Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("move"), []byte("a"), []byte("b"), []byte("1")}})
if err != nil {
    fmt.Println(err.Error())
}

fmt.Println("Chaincode transaction completed")
// output:
// Chaincode transaction completed   

4、呼叫交易處理

func (cc *Client) InvokeHandler(handler invoke.Handler, request Request, options ...RequestOption) (Response, error)
InvokeHandler使用提供的請求和可選請求選項來呼叫處理程式
引數:
handler為要呼叫的處理程式
request包含必備的鏈碼ID和函式的相關資訊
options包含可選的請求選項
返回Peer的提案回覆
使用示例:

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

response, err := c.InvokeHandler(&exampleHandler{}, Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("query"), []byte("data")}})
if err != nil {
    fmt.Printf("failed to query chaincode: %s\n", err)
}

fmt.Println(string(response.Payload))
// output:
// custom

5、查詢

func (cc *Client) Query(request Request, options ...RequestOption) (Response, error)
使用request 和可選請求選項options查詢鏈碼。
引數:
request包含必備鏈碼ID和函式的相關資訊
options包含可選的請求選項
返回值:Peer的提案回覆
使用示例:

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

response, err := c.Query(Request{ChaincodeID: "testCC", Fcn: "invoke", Args: [][]byte{[]byte("query"), []byte("b")}})
if err != nil {
    fmt.Printf("failed to query chaincode: %s\n", err)
}

if len(response.Payload) > 0 {
    fmt.Println("chaincode query success")
}
// output:
// chaincode query success

6、註冊鏈碼事件

func (cc *Client) RegisterChaincodeEvent(chainCodeID string, eventFilter string) (fab.Registration, <-chan *fab.CCEvent, error)
註冊鏈碼事件。當不再需要註冊時,必須呼叫取消註冊。
引數:
chaincodeID接收事件的鏈碼的鏈碼ID
eventFilter用於接收事件的鏈碼事件過濾器(正則表示式)
返回註冊和用於接收事件的通道。呼叫登出事件時,通道將關閉。
使用示例:

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

registration, _, err := c.RegisterChaincodeEvent("examplecc", "event123")
if err != nil {
    fmt.Println("failed to register chaincode event")
}
defer c.UnregisterChaincodeEvent(registration)

fmt.Println("chaincode event registered successfully")
// output:
// chaincode event registered successfully

7、登出鏈碼事件

func (cc *Client) UnregisterChaincodeEvent(registration fab.Registration)
刪除給定的鏈碼事件註冊並關閉事件通道。
引數:
registration是從RegisterChaincodeEvent方法返回的註冊控制代碼

8、RequestOption選項構建

type requestOptions struct {
   Targets       []fab.Peer // targets
   TargetFilter  fab.TargetFilter
   TargetSorter  fab.TargetSorter
   Retry         retry.Opts
   BeforeRetry   retry.BeforeRetryHandler
   Timeouts      map[fab.TimeoutType]time.Duration //timeout options for channel client operations
   ParentContext reqContext.Context                //parent grpc context for channel client operations (query, execute, invokehandler)
   CCFilter      invoke.CCFilter
}

// RequestOption func for each Opts argument
type RequestOption func(ctx context.Client, opts *requestOptions) error

func WithBeforeRetry(beforeRetry retry.BeforeRetryHandler) RequestOption
指定在重試前呼叫的函式
func WithChaincodeFilter(ccFilter invoke.CCFilter) RequestOption
新增一個鏈碼過濾器,用於計算額外的背書節點
func WithParentContext(parentContext reqContext.Context) RequestOption
WithParentContext封裝了grpc父上下文
func WithRetry(retryOpt retry.Opts) RequestOption
WithRetry生成用於配置重試的選項
func WithTargetEndpoints(keys ...string) RequestOption
WithTargetEndpoints允許為請求的覆蓋目標Peer節點。目標Peer節點由名稱或URL指定,SDK將建立底層的Peer節點物件。
func WithTargetFilter(filter fab.TargetFilter) RequestOption
WithTargetFilter指定每個請求的目標Peer節點的過濾器
func WithTargets(targets ...fab.Peer) RequestOption
WithTargets允許為請求覆蓋目標Peer節點
func WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption
WithTimeout封裝了超時型別的鍵值對
func WithTargetSorter(sorter fab.TargetSorter) RequestOption
指定每個請求的排序節點

三、chennel示例

ctx := sdk.ChannelContext(channelName, fabsdk.WithOrg(org), fabsdk.WithUser(user))

cli, err := channel.New(ctx)
if err != nil {
   return channel.Response{}, err
}

// 狀態的查詢
resp,err := cli.Query(channel.Request{
   ChaincodeID: chaincodeName,
   Fcn:         fcn,
   Args:        args,
}, channel.WithTargetEndpoints("peer0.org1.example.com"))