fabclient

package module
v1.4.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2021 License: MIT Imports: 27 Imported by: 0

README

fabric-go-client

Build Status codecov Go Report Card GoDoc MIT licensed

The aim of this client is to facilitate the development of solutions that interact with Hyperledger Fabric thanks to the fabric-sdk-go.

It is a wrapper around the fabric-sdk-go. The client has been designed for being able to manage multiple channels and interact with multiple chaincodes.

This version is built to be compliant with Hyperledger Fabric v1.4. It uses the legacy chaincode lifecycle.

If you wish to use the new chaincode lifecyle as well as the gateway programming model, please take a look at this version of the client.

⚠ For the moment, the client is only able to manage Go chaincodes, meaning you cannot install neither Node.js nor Java chaincodes with it.

Contribution

Each Contribution is welcomed and encouraged. I do not claim to cover each use cases neither completely master the Go nor Hyperledger Fabric. If you encounter a non sense or any trouble, you can open an issue and I will be happy to discuss about it 😄

Usage

❯ go get github.com/TommyStarK/fabric-go-client@v1.4.10

You will find an example of how to instantiate and use the client here. An example of how to configure the client is also available here.

Test

❯ ./hack/run-integration-tests.sh

Documentation

Overview

Package fabclient aims to facilitate the development of solutions that interact with Hyperledger Fabric thanks to the fabric-sdk-go.

Package fabclient enables the creation and update of a channel, for peers to join channels. It allows administrators to perform chaincode related operations on a peer. It uses the legacy chaincode lifecycle enabling to install, instantiate and upgrade a chaincode. Furthermore, package fabclient provides access to a channel on a Fabric network, allowing users to query/invoke chaincodes, register/unregister for chaincode events on specific channel and perform ledger queries.

It is a wrapper around the fabric-sdk-go. The client has been designed for being able to manage multiple channels and interact with multiple chaincodes.

Example
client, err := NewClientFromConfigFile("./testdata/client/client-config.yaml")
if err != nil {
	log.Fatal(err)
}

defer client.Close()

channel := client.Config().Channels[0]
chaincode := client.Config().Chaincodes[0]

if err := client.SaveChannel(channel.Name, channel.ConfigPath); err != nil {
	log.Fatal(err)
}

if err := client.JoinChannel(channel.Name); err != nil {
	log.Fatal(err)
}

if err := client.InstallChaincode(chaincode); err != nil {
	log.Fatal(err)
}

if err := client.InstantiateOrUpgradeChaincode(channel.Name, chaincode); err != nil {
	log.Fatal(err)
}

storeRequest := &ChaincodeRequest{
	ChaincodeID: chaincode.Name,
	Function:    "store",
	Args:        []string{"asset-test", `{"content": "this is a content test"}`},
}

storeResult, err := client.Invoke(storeRequest, WithOrdererResponseTimeout(2*time.Second))
if err != nil {
	log.Fatal(err)
}

log.Printf("store txID: %s", storeResult.TransactionID)

queryRequest := &ChaincodeRequest{
	ChaincodeID: chaincode.Name,
	Function:    "query",
	Args:        []string{"asset-test"},
}

queryResult, err := client.Query(queryRequest)
if err != nil {
	log.Fatal(err)
}

log.Printf("query content: %s", string(queryResult.Payload))
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Block

type Block struct {
	Header   *BlockHeader
	Data     *BlockData
	Metadata *BlockMetadata
}

Block is finalized block structure to be shared among the orderer and peer.

type BlockData

type BlockData struct {
	Data [][]byte
}

BlockData holds the transactions.

type BlockHeader

type BlockHeader struct {
	Number       uint64
	PreviousHash []byte
	DataHash     []byte
}

BlockHeader is the element of the block which forms the blockchain.

type BlockMetadata

type BlockMetadata struct {
	Metadata [][]byte
}

BlockMetadata defines metadata of the block.

type BlockchainInfo

type BlockchainInfo struct {
	Height            uint64
	CurrentBlockHash  []byte
	PreviousBlockHash []byte
}

BlockchainInfo contains information about the blockchain ledger such as height, current block hash, and previous block hash.

type Chaincode

type Chaincode struct {
	Collections []ChaincodeCollection `json:"collections,omitempty" yaml:"collections,omitempty"`
	InitArgs    []string              `json:"initArgs,omitempty" yaml:"initArgs,omitempty"`
	Name        string                `json:"name" yaml:"name"`
	Path        string                `json:"path" yaml:"path"`
	Policy      string                `json:"policy,omitempty" yaml:"policy,omitempty"`
	Version     string                `json:"version" yaml:"version"`
}

Chaincode describes info of a chaincode.

type ChaincodeCall

type ChaincodeCall struct {
	ID          string
	Collections []string
}

ChaincodeCall contains the ID of the chaincode as well as an optional set of private data collections that may be accessed by the chaincode.

type ChaincodeCollection

type ChaincodeCollection struct {
	BlockToLive       uint64 `json:"blockToLive" yaml:"blockToLive"`
	MaxPeerCount      int32  `json:"maxPeerCount" yaml:"maxPeerCount"`
	MemberOnlyRead    bool   `json:"memberOnlyRead" yaml:"memberOnlyRead"`
	Name              string `json:"name" yaml:"name"`
	Policy            string `json:"policy" yaml:"policy"`
	RequiredPeerCount int32  `json:"requiredPeerCount" yaml:"requiredPeerCount"`
}

ChaincodeCollection defines the configuration of a collection.

type ChaincodeEvent

type ChaincodeEvent struct {
	TxID        string
	ChaincodeID string
	EventName   string
	Payload     []byte
	BlockNumber uint64
	SourceURL   string
}

ChaincodeEvent contains the data for a chaincode event.

type ChaincodeRequest

type ChaincodeRequest struct {
	ChaincodeID     string
	Function        string
	Args            []string
	TransientMap    map[string][]byte
	InvocationChain []*ChaincodeCall
}

ChaincodeRequest contains the parameters to query and execute an invocation transaction.

type Channel

type Channel struct {
	AnchorPeerConfigPath string `json:"anchorPeerConfigPath,omitempty" yaml:"anchorPeerConfigPath,omitempty"`
	ConfigPath           string `json:"configPath" yaml:"configPath"`
	Name                 string `json:"name" yaml:"name"`
}

Channel describes a channel configuration.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client API enables to manage resources in a Fabric network, access to a channel, perform chaincode related operations.

func NewClient

func NewClient(cfg *Config) (*Client, error)

NewClient returns a Client instance.

func NewClientFromConfigFile

func NewClientFromConfigFile(configPath string) (*Client, error)

NewClientFromConfigFile returns a client instance from a config file.

func (*Client) Close

func (client *Client) Close()

Close frees up caches and connections being maintained by the SDK.

func (*Client) Config

func (client *Client) Config() *Config

Config returns the client configuration.

func (*Client) InstallChaincode

func (client *Client) InstallChaincode(chaincode Chaincode) error

InstallChaincode allows administrators to install chaincode onto the filesystem of a peer.

func (*Client) InstantiateOrUpgradeChaincode

func (client *Client) InstantiateOrUpgradeChaincode(channelID string, chaincode Chaincode) error

InstantiateOrUpgradeChaincode instantiates or upgrades chaincode.

func (*Client) Invoke

func (client *Client) Invoke(request *ChaincodeRequest, opts ...Option) (*TransactionResponse, error)

Invoke prepares and executes transaction using request and optional request options.

func (*Client) IsChaincodeInstalled

func (client *Client) IsChaincodeInstalled(chaincodeName string) bool

IsChaincodeInstalled returns whether the given chaincode has been installed or not.

func (*Client) IsChaincodeInstantiated

func (client *Client) IsChaincodeInstantiated(channelID, chaincodeName, chaincodeVersion string) bool

IsChaincodeInstantiated returns whether the given chaincode has been instantiated or not.

func (*Client) JoinChannel

func (client *Client) JoinChannel(channelID string) error

JoinChannel allows for peers to join existing channel.

func (*Client) Query

func (client *Client) Query(request *ChaincodeRequest, opts ...Option) (*TransactionResponse, error)

Query chaincode using request and optional request options.

func (*Client) QueryBlock

func (client *Client) QueryBlock(blockNumber uint64, opts ...Option) (*Block, error)

QueryBlock queries the ledger for Block by block number.

func (*Client) QueryBlockByHash

func (client *Client) QueryBlockByHash(blockHash []byte, opts ...Option) (*Block, error)

QueryBlockByHash queries the ledger for block by block hash.

func (*Client) QueryBlockByTxID

func (client *Client) QueryBlockByTxID(txID string, opts ...Option) (*Block, error)

QueryBlockByTxID queries for block which contains a transaction.

func (*Client) QueryInfo

func (client *Client) QueryInfo(opts ...Option) (*BlockchainInfo, error)

QueryInfo queries for various useful blockchain information on this channel such as block height and current block hash.

func (*Client) RegisterChaincodeEvent

func (client *Client) RegisterChaincodeEvent(chaincodeID, eventFilter string, opts ...Option) (<-chan *ChaincodeEvent, error)

RegisterChaincodeEvent registers for chaincode events. Unregister must be called when the registration is no longer needed.

func (*Client) SaveChannel

func (client *Client) SaveChannel(channelID, channelConfigPath string) error

SaveChannel creates or updates channel.

func (*Client) UnregisterChaincodeEvent

func (client *Client) UnregisterChaincodeEvent(eventFilter string, opts ...Option) error

UnregisterChaincodeEvent removes the given registration and closes the event channel.

type Config

type Config struct {
	Chaincodes        []Chaincode `json:"chaincodes" yaml:"chaincodes"`
	Channels          []Channel   `json:"channels" yaml:"channels"`
	ConnectionProfile string      `json:"connectionProfile" yaml:"connectionProfile"`
	Identities        struct {
		Admin Identity   `json:"admin" yaml:"admin"`
		Users []Identity `json:"users" yaml:"users"`
	} `json:"identities" yaml:"identities"`
	Organization string `json:"organization" yaml:"organization"`
}

Config holds the client configuration.

func NewConfigFromFile

func NewConfigFromFile(configPath string) (*Config, error)

NewConfigFromFile returns a new client config.

type Identity

type Identity struct {
	Certificate string `json:"certificate" yaml:"certificate"`
	PrivateKey  string `json:"privateKey" yaml:"privateKey"`
	Username    string `json:"username" yaml:"username"`
}

Identity holds crypto material for creating a signing identity.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option describes a functional parameter for the client.

func WithChannelContext

func WithChannelContext(channelID string) Option

WithChannelContext allows to target a specific channel.

func WithOrdererResponseTimeout

func WithOrdererResponseTimeout(timeout time.Duration) Option

WithOrdererResponseTimeout allows to specify a timeout for orderer response.

func WithUserContext

func WithUserContext(username string) Option

WithUserContext allows to specify a user context.

type TransactionResponse

type TransactionResponse struct {
	Payload       []byte
	Status        int32
	TransactionID string
}

TransactionResponse contains response parameters for query and execute an invocation transaction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL