HyperLeger Fabric SDK开发(七)——ledger

一、ledger简介

1、ledger简介

ledger包支持在Fabric网络上的指定通道上启用账本查询。如果应用程序需要对多个通道进行账本查询,需要为每个通道的账本客户端创建一个单独实例。账本客户端支持以下查询:QueryInfo,QueryBlock,QueryBlockByHash,QueryBlockByTxID,QueryTransaction和QueryConfig。
官方文档:
https://godoc.org/github.com/hyperledger/fabric-sdk-go/pkg/client/ledger

2、ledger使用流程

ledger使用的基本流程如下:
A、准备通道上下文
B、创建分类帐客户端
C、查询分类帐
使用示例:

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      

二、ledger常用接口

1、获取账本客户端实例

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        

2、查询账本

func (c *Client) QueryBlock(blockNumber uint64, options ...RequestOption) (*common.Block, error)
QueryBlock根据区块编号查询区块的账本。
参数:
blockNumber是必需的区块号
options包含可选的请求选项
返回区块信息
使用示例:

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   

3、查询通道配置

func (c *Client) QueryConfig(options ...RequestOption) (fab.ChannelCfg, error)
QueryConfig查询通道配置。
参数:
options包含可选的请求选项
返回通道配置信息
使用示例:

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   

4、查询通道信息

func (c *Client) QueryInfo(options ...RequestOption) (*fab.BlockchainInfoResponse, error)
QueryInfo查询此通道上的各种区块链信息,例如区块高度和当前区块哈希。
参数:
options是可选的请求选项
返回区块链信息
使用示例:

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  

5、查询交易信息

func (c *Client) QueryTransaction(transactionID fab.TransactionID, options ...RequestOption) (*pb.ProcessedTransaction, error)
QueryTransaction通过交易ID查询账本上的已处理交易。
参数:
txID是必需的交易ID
options包含可选的请求选项
返回已经处理交易的信息
使用示例:

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  

6、为客户端设置过滤器

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   

7、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父上下文
使用示例:

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等函数。

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