HyperLeger Fabric SDK開發(七)——ledger

HyperLeger Fabric SDK開發(七)——ledger

1、ledger簡介

一、ledger簡介

ledger包支持在Fabric網絡上的指定通道上啓用帳本查詢。若是應用程序須要對多個通道進行帳本查詢,須要爲每一個通道的帳本客戶端建立一個單獨實例。帳本客戶端支持如下查詢:QueryInfo,QueryBlock,QueryBlockByHash,QueryBlockByTxID,QueryTransaction和QueryConfig。
官方文檔:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/ledgergit

二、ledger使用流程

ledger使用的基本流程以下:
A、準備通道上下文
B、建立分類賬客戶端
C、查詢分類賬
使用示例:github

ctx := mockChannelProvider("mychannel")

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

block, err := c.QueryBlock(1)
if err != nil {
    fmt.Printf("failed to query block: %s\n", err)
}

if block != nil {
    fmt.Println("Retrieved block #1")
}
// output:
// Retrieved block #1

2、ledger經常使用接口

一、獲取帳本客戶端實例

type Client struct {
   ctx       context.Channel
   filter    fab.TargetFilter
   ledger    *channel.Ledger
   verifier  channel.ResponseVerifier
   discovery fab.DiscoveryService
}
func New(channelProvider context.ChannelProvider, opts ...ClientOption) (*Client, error)

New返回帳本客戶端實例。帳本客戶端實例提供處理程序以查詢指定通道上的各類信息。若是應用程序須要對多個通道進行帳本查詢,須要爲每一個通道的帳本客戶端建立一個單獨實例。帳本客戶端僅支持指定查詢。
使用示例:網絡

ctx := mockChannelProvider("mychannel")

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

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

二、查詢帳本

func (c *Client) QueryBlock(blockNumber uint64, options ...RequestOption) (*common.Block, error)
QueryBlock根據區塊編號查詢區塊的帳本。
參數:
blockNumber是必需的區塊號
options包含可選的請求選項
返回區塊信息
使用示例:ide

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

block, err := c.QueryBlock(1)
if err != nil {
    fmt.Printf("failed to query block: %s\n", err)
}

if block != nil {
    fmt.Println("Retrieved block #1")
}
// output:
// Retrieved block #1

func (c *Client) QueryBlockByHash(blockHash []byte, options ...RequestOption) (*common.Block, error)
QueryBlockByHash根據區塊hash查詢區塊帳本。
參數:
blockHash是區塊哈希
options包含可選的請求選項
返回區塊信息
使用示例:函數

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

block, err := c.QueryBlockByHash([]byte("hash"))
if err != nil {
    fmt.Printf("failed to query block by hash: %s\n", err)
}

if block != nil {
    fmt.Println("Retrieved block by hash")
}
// output:
// Retrieved block by hash

func (c *Client) QueryBlockByTxID(txID fab.TransactionID, options ...RequestOption) (*common.Block, error)
QueryBlockByTxID查詢包含交易的區塊
參數:
txID是交易ID
options包含可選的請求選項
返回區塊信息
使用示例:區塊鏈

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

block, err := c.QueryBlockByTxID("123")
if err != nil {
    fmt.Printf("failed to query block by transaction ID: %s\n", err)
}

if block != nil {
    fmt.Println("Retrieved block by transaction ID")
}
// output:
// Retrieved block by transaction ID

三、查詢通道配置

func (c *Client) QueryConfig(options ...RequestOption) (fab.ChannelCfg, error)
QueryConfig查詢通道配置。
參數:
options包含可選的請求選項
返回通道配置信息
使用示例:ui

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

cfg, err := c.QueryConfig(WithTargets(mockPeerWithConfigBlock()))
if err != nil {
    fmt.Printf("failed to query config: %s\n", err)
}

if cfg != nil {
    fmt.Println("Retrieved channel configuration")
}
// output:
// Retrieved channel configuration

四、查詢通道信息

func (c *Client) QueryInfo(options ...RequestOption) (*fab.BlockchainInfoResponse, error)
QueryInfo查詢此通道上的各類區塊鏈信息,例如區塊高度和當前區塊哈希。
參數:
options是可選的請求選項
返回區塊鏈信息
使用示例:url

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

bci, err := c.QueryInfo()
if err != nil {
    fmt.Printf("failed to query for blockchain info: %s\n", err)
}

if bci != nil {
    fmt.Println("Retrieved ledger info")
}
// output:
// Retrieved ledger info

五、查詢交易信息

func (c *Client) QueryTransaction(transactionID fab.TransactionID, options ...RequestOption) (*pb.ProcessedTransaction, error)
QueryTransaction經過交易ID查詢帳本上的已處理交易。
參數:
txID是必需的交易ID
options包含可選的請求選項
返回已經處理交易的信息
使用示例:code

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

t, err := c.QueryTransaction("123")
if err != nil {
    fmt.Printf("failed to query transaction: %s\n", err)
}

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

六、爲客戶端設置過濾器

type ClientOption func(*Client) error

// WithDefaultTargetFilter option to configure new
func WithDefaultTargetFilter(filter fab.TargetFilter) ClientOption 
使用示例:
ctx := mockChannelProvider("mychannel")

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

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

七、RequestOption參數構建

type RequestOption func(ctx context.Client, opts *requestOptions) error

//requestOptions contains options for operations performed by LedgerClient
type requestOptions struct {
   Targets       []fab.Peer                        // target peers
   TargetFilter  fab.TargetFilter                  // target filter
   MaxTargets    int                               // maximum number of targets to select
   MinTargets    int                               // min number of targets that have to respond with no error (or agree on result)
   Timeouts      map[fab.TimeoutType]time.Duration //timeout options for ledger query operations
   ParentContext reqContext.Context                //parent grpc context for ledger operations
}
func WithMaxTargets(maxTargets int) RequestOption

WithMaxTargets指定每一個請求選擇的最大目標數。最大目標數的默認值爲1.
func WithMinTargets(minTargets int) RequestOption
WithMinTargets指定必須響應且沒有錯誤(或贊成結果)的最小目標數。 最小目標數的默認值爲1。
func WithParentContext(parentContext reqContext.Context) RequestOption
WithParentContext封裝了grpc父上下文
使用示例:orm

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

channelContext, err := mockChannelProvider("mychannel")()
if err != nil {
    fmt.Println("failed to return channel context")
    return
}

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

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

if bci != nil {
    fmt.Println("Retrieved blockchain info")
}
// output:
// Retrieved blockchain info

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

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

block, err := c.QueryBlock(1, WithTargetFilter(&urlTargetFilter{url: "example.com"}))
if err != nil {
    fmt.Printf("failed to query block: %s\n", err)
}

if block != nil {
    fmt.Println("Retrieved block #1 from example.com")
}
// output:
// Retrieved block #1 from example.com

func WithTargets(targets ...fab.Peer) RequestOption
WithTargets容許每一個請求覆蓋目標Peer節點。
使用示例:

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

cfg, err := c.QueryConfig(WithTargets(mockPeerWithConfigBlock()))
if err != nil {
    fmt.Printf("failed to query config with target peer: %s\n", err)
}

if cfg != nil {
    fmt.Println("Retrieved config from target peer")
}
// output:
// Retrieved config from target peer

func WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption
WithTimeout封裝了超時類型、超時時間的鍵值對到Options選項,次選項用於QueryInfo,QueryBlock,QueryBlockByHash,QueryBlockByTxID,QueryTransaction,QueryConfig等函數。

3、ledger示例

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

// 帳本查詢
func queryBlockchain() {
   ctx := sdk.ChannelContext(channelName, fabsdk.WithOrg(org), fabsdk.WithUser(user))

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

   resp, err := cli.QueryInfo(ledger.WithTargetEndpoints("peer0.org1.example.com"))
   if err != nil {
      panic(err)
   }

   fmt.Println(resp)

   // 1
   cli.QueryBlockByHash(resp.BCI.CurrentBlockHash)

   // 2
   for i := uint64(0); i <= resp.BCI.Height; i++ {
      cli.QueryBlock(i)
   }
}
相關文章
相關標籤/搜索