client

package
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2024 License: Apache-2.0 Imports: 20 Imported by: 52

README

Hyperledger Fabric Gateway Client API for Go

The Fabric Gateway client API allows applications to interact with a Hyperledger Fabric blockchain network. It implements the Fabric programming model, providing a simple API to submit transactions to a ledger or query the contents of a ledger with minimal code.

How to use

Samples showing how to create client applications that connect to and interact with a Hyperledger Fabric network, are available in the fabric-samples repository:

API documentation

The Gateway client API documentation for Go is available here:

Installation

Add a package dependency to your project with the command:

go get github.com/hyperledger/fabric-gateway

Compatibility

This API requires Fabric v2.4 (or later) with a Gateway enabled Peer. Additional compatibility information is available in the documentation:

Documentation

Overview

Package client enables Go developers to build client applications using the Hyperledger Fabric programming model.

Client applications interact with the blockchain network using a Fabric Gateway. A client connection to a Fabric Gateway is established by calling client.Connect() with a client identity, client signing implementation, and client connection details. The returned Gateway can be used to transact with smart contracts deployed to networks accessible through the Fabric Gateway.

Example
package main

import (
	"crypto/x509"
	"fmt"
	"os"

	"github.com/hyperledger/fabric-gateway/pkg/client"
	"github.com/hyperledger/fabric-gateway/pkg/identity"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

func main() {
	// Create gRPC client connection, which should be shared by all gateway connections to this endpoint.
	clientConnection, err := NewGrpcConnection()
	panicOnError(err)
	defer clientConnection.Close()

	// Create client identity and signing implementation based on X.509 certificate and private key.
	id := NewIdentity()
	sign := NewSign()

	// Create a Gateway connection for a specific client identity.
	gateway, err := client.Connect(id, client.WithSign(sign), client.WithClientConnection(clientConnection))
	panicOnError(err)
	defer gateway.Close()

	// Obtain smart contract deployed on the network.
	network := gateway.GetNetwork("channelName")
	contract := network.GetContract("chaincodeName")

	// Submit transactions that store state to the ledger.
	submitResult, err := contract.SubmitTransaction("transactionName", "arg1", "arg2")
	panicOnError(err)
	fmt.Printf("Submit result: %s", string(submitResult))

	// Evaluate transactions that query state from the ledger.
	evaluateResult, err := contract.EvaluateTransaction("transactionName", "arg1", "arg2")
	panicOnError(err)
	fmt.Printf("Evaluate result: %s", string(evaluateResult))
}

// NewGrpcConnection creates a new gRPC client connection
func NewGrpcConnection() (*grpc.ClientConn, error) {
	tlsCertificatePEM, err := os.ReadFile("tlsRootCertificate.pem")
	panicOnError(err)

	tlsCertificate, err := identity.CertificateFromPEM(tlsCertificatePEM)
	panicOnError(err)

	certPool := x509.NewCertPool()
	certPool.AddCert(tlsCertificate)
	transportCredentials := credentials.NewClientTLSFromCert(certPool, "")

	return grpc.NewClient("dns:///gateway.example.org:1337", grpc.WithTransportCredentials(transportCredentials))
}

// NewIdentity creates a client identity for this Gateway connection using an X.509 certificate.
func NewIdentity() *identity.X509Identity {
	certificatePEM, err := os.ReadFile("certificate.pem")
	panicOnError(err)

	certificate, err := identity.CertificateFromPEM(certificatePEM)
	panicOnError(err)

	id, err := identity.NewX509Identity("mspID", certificate)
	panicOnError(err)

	return id
}

// NewSign creates a function that generates a digital signature from a message digest using a private key.
func NewSign() identity.Sign {
	privateKeyPEM, err := os.ReadFile("privateKey.pem")
	panicOnError(err)

	privateKey, err := identity.PrivateKeyFromPEM(privateKeyPEM)
	panicOnError(err)

	sign, err := identity.NewPrivateKeySign(privateKey)
	panicOnError(err)

	return sign
}

func panicOnError(err error) {
	if err != nil {
		panic(err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithCheckpoint added in v1.1.0

func WithCheckpoint(checkpoint Checkpoint) eventOption

WithCheckpoint reads events starting at the checkpoint position. This can be used to resume a previous eventing session. The zero value is ignored and a start position specified by other options or the default position is used.

func WithStartBlock

func WithStartBlock(blockNumber uint64) eventOption

WithStartBlock reads events starting at the specified block number.

Types

type BlockAndPrivateDataEventsRequest added in v1.1.0

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

BlockAndPrivateDataEventsRequest delivers block and private data events.

func (*BlockAndPrivateDataEventsRequest) Bytes added in v1.1.0

func (events *BlockAndPrivateDataEventsRequest) Bytes() ([]byte, error)

Bytes of the serialized block events request.

func (*BlockAndPrivateDataEventsRequest) Digest added in v1.1.0

func (events *BlockAndPrivateDataEventsRequest) Digest() []byte

Digest of the block events request. This is used to generate a digital signature.

func (*BlockAndPrivateDataEventsRequest) Events added in v1.1.0

Events returns a channel from which block and private data events can be read.

type BlockEventsOption added in v1.1.0

type BlockEventsOption eventOption

BlockEventsOption implements an option for a block events request.

type BlockEventsRequest added in v1.1.0

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

BlockEventsRequest delivers block events.

func (*BlockEventsRequest) Bytes added in v1.1.0

func (events *BlockEventsRequest) Bytes() ([]byte, error)

Bytes of the serialized block events request.

func (*BlockEventsRequest) Digest added in v1.1.0

func (events *BlockEventsRequest) Digest() []byte

Digest of the block events request. This is used to generate a digital signature.

func (*BlockEventsRequest) Events added in v1.1.0

func (events *BlockEventsRequest) Events(ctx context.Context, opts ...grpc.CallOption) (<-chan *common.Block, error)

Events returns a channel from which block events can be read.

type ChaincodeEvent

type ChaincodeEvent struct {
	BlockNumber   uint64
	TransactionID string
	ChaincodeName string
	EventName     string
	Payload       []byte
}

ChaincodeEvent emitted by a transaction function.

type ChaincodeEventsOption

type ChaincodeEventsOption eventOption

ChaincodeEventsOption implements an option for a chaincode events request.

If both a start block and checkpoint are specified, and the checkpoint has a valid position set, the checkpoint position is used and the specified start block is ignored. If the checkpoint is unset then the start block is used.

If no start position is specified, eventing begins from the next committed block.

type ChaincodeEventsRequest

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

ChaincodeEventsRequest delivers events emitted by transaction functions in a specific chaincode.

func (*ChaincodeEventsRequest) Bytes

func (events *ChaincodeEventsRequest) Bytes() ([]byte, error)

Bytes of the serialized chaincode events request.

func (*ChaincodeEventsRequest) Digest

func (events *ChaincodeEventsRequest) Digest() []byte

Digest of the chaincode events request. This is used to generate a digital signature.

func (*ChaincodeEventsRequest) Events

func (events *ChaincodeEventsRequest) Events(ctx context.Context, opts ...grpc.CallOption) (<-chan *ChaincodeEvent, error)

Events returns a channel from which chaincode events can be read.

type Checkpoint added in v1.1.0

type Checkpoint interface {
	// BlockNumber in which the next event is expected.
	BlockNumber() uint64
	// TransactionID of the last successfully processed event within the current block.
	TransactionID() string
}

Checkpoint provides the current position for event processing.

type Commit

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

Commit provides access to a committed transaction.

func (*Commit) Bytes

func (commit *Commit) Bytes() ([]byte, error)

Bytes of the serialized commit.

func (*Commit) Digest

func (commit *Commit) Digest() []byte

Digest of the commit status request. This is used to generate a digital signature.

func (*Commit) Status

func (commit *Commit) Status(opts ...grpc.CallOption) (*Status, error)

Status of the committed transaction. If the transaction has not yet committed, this call blocks until the commit occurs.

func (*Commit) StatusWithContext

func (commit *Commit) StatusWithContext(ctx context.Context, opts ...grpc.CallOption) (*Status, error)

StatusWithContext uses the supplied context to get the status of the committed transaction. If the transaction has not yet committed, this call blocks until the commit occurs.

func (*Commit) TransactionID

func (commit *Commit) TransactionID() string

TransactionID of the transaction.

type CommitError added in v0.2.0

type CommitError struct {
	TransactionID string
	Code          peer.TxValidationCode
	// contains filtered or unexported fields
}

CommitError represents a transaction that fails to commit successfully.

func (*CommitError) Error added in v0.2.0

func (e *CommitError) Error() string

type CommitStatusError added in v0.2.0

type CommitStatusError struct {
	*TransactionError
}

CommitStatusError represents a failure obtaining the commit status of a transaction.

func (CommitStatusError) GRPCStatus added in v0.2.0

func (e CommitStatusError) GRPCStatus() *status.Status

func (CommitStatusError) Unwrap added in v0.2.0

func (e CommitStatusError) Unwrap() error

type ConnectOption

type ConnectOption = func(gateway *Gateway) error

ConnectOption implements an option that can be used when connecting to a Fabric Gateway.

func WithClientConnection

func WithClientConnection(clientConnection grpc.ClientConnInterface) ConnectOption

WithClientConnection uses the supplied gRPC client connection to a Fabric Gateway. This should be shared by all Gateway instances connecting to the same Fabric Gateway. The client connection will not be closed when the Gateway is closed.

func WithCommitStatusTimeout

func WithCommitStatusTimeout(timeout time.Duration) ConnectOption

WithCommitStatusTimeout specifies the default timeout for retrieving transaction commit status.

func WithEndorseTimeout

func WithEndorseTimeout(timeout time.Duration) ConnectOption

WithEndorseTimeout specifies the default timeout for endorsements.

func WithEvaluateTimeout

func WithEvaluateTimeout(timeout time.Duration) ConnectOption

WithEvaluateTimeout specifies the default timeout for evaluating transactions.

func WithHash

func WithHash(hash hash.Hash) ConnectOption

WithHash uses the supplied hashing implementation to generate digital signatures.

func WithSign

func WithSign(sign identity.Sign) ConnectOption

WithSign uses the supplied signing implementation to sign messages sent by the Gateway.

func WithSubmitTimeout

func WithSubmitTimeout(timeout time.Duration) ConnectOption

WithSubmitTimeout specifies the default timeout for submit of transactions to the orderer.

func WithTLSClientCertificateHash added in v1.5.0

func WithTLSClientCertificateHash(certificateHash []byte) ConnectOption

WithTLSClientCertificateHash specifies the SHA-256 hash of the TLS client certificate. This option is required only if mutual TLS authentication is used for the gRPC connection to the Gateway peer.

type Contract

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

Contract represents a smart contract, and allows applications to:

- Evaluate transactions that query state from the ledger using the EvaluateTransaction() method.

- Submit transactions that store state to the ledger using the SubmitTransaction() method.

For more complex transaction invocations, such as including transient data, transactions can be evaluated or submitted using the Evaluate() or Submit() methods respectively. The result of a submitted transaction can be accessed prior to its commit to the ledger using SubmitAsync().

A finer-grained transaction flow can be employed by using NewProposal(). This allows retry of individual steps in the flow in response to errors.

By default, proposal, transaction and commit status messages will be signed using the signing implementation specified when connecting the Gateway. In cases where an external client holds the signing credentials, a signing implementation can be omitted when connecting the Gateway and off-line signing can be carried out by:

1. Returning the serialized proposal, transaction or commit status message along with its digest to the client for them to generate a signature.

2. With the serialized message and signature received from the client to create a signed proposal, transaction or commit using the Gateway's NewSignedProposal(), NewSignedTransaction() or NewSignedCommit() methods respectively.

Example (OfflineSign)
var gateway *client.Gateway
var contract *client.Contract // Obtained from Network.
var sign identity.Sign        // Signing function.

// Create a transaction proposal.
unsignedProposal, err := contract.NewProposal("transactionName", client.WithArguments("one", "two"))
panicOnError(err)

// Off-line sign the proposal.
proposalBytes, err := unsignedProposal.Bytes()
panicOnError(err)
proposalDigest := unsignedProposal.Digest()
proposalSignature, err := sign(proposalDigest)
panicOnError(err)
signedProposal, err := gateway.NewSignedProposal(proposalBytes, proposalSignature)
panicOnError(err)

// Endorse proposal to create an endorsed transaction.
unsignedTransaction, err := signedProposal.Endorse()
panicOnError(err)

// Off-line sign the transaction.
transactionBytes, err := unsignedTransaction.Bytes()
panicOnError(err)
digest := unsignedTransaction.Digest()
transactionSignature, err := sign(digest)
panicOnError(err)
signedTransaction, err := gateway.NewSignedTransaction(transactionBytes, transactionSignature)
panicOnError(err)

// Submit transaction to the orderer.
unsignedCommit, err := signedTransaction.Submit()
panicOnError(err)

// Off-line sign the transaction commit status request
commitBytes, err := unsignedCommit.Bytes()
panicOnError(err)
commitDigest := unsignedCommit.Digest()
commitSignature, err := sign(commitDigest)
panicOnError(err)
signedCommit, err := gateway.NewSignedCommit(commitBytes, commitSignature)
panicOnError(err)

// Wait for transaction commit.
status, err := signedCommit.Status()
panicOnError(err)
if !status.Successful {
	panic(fmt.Errorf("transaction %s failed to commit with status code %d", status.TransactionID, int32(status.Code)))
}

fmt.Printf("Result: %s\n", signedTransaction.Result())
Output:

func (*Contract) ChaincodeName

func (contract *Contract) ChaincodeName() string

ChaincodeName of the chaincode that contains this smart contract.

func (*Contract) ContractName

func (contract *Contract) ContractName() string

ContractName of the contract within the chaincode, or an empty string for the default smart contract.

func (*Contract) Evaluate

func (contract *Contract) Evaluate(transactionName string, options ...ProposalOption) ([]byte, error)

Evaluate a transaction function and return its result. This method provides greater control over the transaction proposal content and the endorsing peers on which it is evaluated. This allows transaction functions to be evaluated where the proposal must include transient data.

Example
package main

import (
	"fmt"

	"github.com/hyperledger/fabric-gateway/pkg/client"
)

func main() {
	var contract *client.Contract // Obtained from Network.

	result, err := contract.Evaluate(
		"transactionName",
		client.WithArguments("one", "two"),
		// Specify additional proposal options, such as transient data
	)

	fmt.Printf("Result: %s, Err: %v", result, err)
}
Output:

Example (ErrorHandling)
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/hyperledger/fabric-gateway/pkg/client"
	"google.golang.org/grpc/status"
)

func main() {
	var contract *client.Contract // Obtained from Network.

	result, err := contract.Evaluate("transactionName")
	if err != nil {
		if errors.Is(err, context.DeadlineExceeded) {
			panic(fmt.Errorf("timeout: %w", err))
		} else {
			panic(fmt.Errorf("gRPC status %v: %w", status.Code(err), err))
		}
	}

	fmt.Printf("Result: %s, Err: %v", result, err)
}
Output:

func (*Contract) EvaluateTransaction

func (contract *Contract) EvaluateTransaction(name string, args ...string) ([]byte, error)

EvaluateTransaction will evaluate a transaction function and return its results. A transaction proposal will be evaluated on endorsing peers but the transaction will not be sent to the ordering service and so will not be committed to the ledger. This can be used for querying the world state.

This method is equivalent to:

contract.Evaluate(name, WithArguments(args...))

func (*Contract) EvaluateWithContext added in v1.2.0

func (contract *Contract) EvaluateWithContext(ctx context.Context, transactionName string, options ...ProposalOption) ([]byte, error)

EvaluateWithContext evaluates a transaction function in the scope of a specific context and return its result. This method provides greater control over the transaction proposal content and the endorsing peers on which it is evaluated. This allows transaction functions to be evaluated where the proposal must include transient data.

func (*Contract) NewProposal

func (contract *Contract) NewProposal(transactionName string, options ...ProposalOption) (*Proposal, error)

NewProposal creates a proposal that can be sent to peers for endorsement. Supports off-line signing transaction flow.

Example
var contract *client.Contract // Obtained from Network.

proposal, err := contract.NewProposal("transactionName", client.WithArguments("one", "two"))
panicOnError(err)

transaction, err := proposal.Endorse()
panicOnError(err)

commit, err := transaction.Submit()
panicOnError(err)

status, err := commit.Status()
panicOnError(err)

fmt.Printf("Commit status code: %d, Result: %s\n", int32(status.Code), transaction.Result())
Output:

func (*Contract) Submit

func (contract *Contract) Submit(transactionName string, options ...ProposalOption) ([]byte, error)

Submit a transaction to the ledger and return its result only after it has been committed to the ledger. This method provides greater control over the transaction proposal content and the endorsing peers on which it is evaluated. This allows transaction functions to be submitted where the proposal must include transient data.

This method may return different error types depending on the point in the transaction invocation that a failure occurs. The error can be inspected with errors.Is or errors.As.

Example
package main

import (
	"fmt"

	"github.com/hyperledger/fabric-gateway/pkg/client"
)

func main() {
	var contract *client.Contract // Obtained from Network.

	result, err := contract.Submit(
		"transactionName",
		client.WithArguments("one", "two"),
		// Specify additional proposal options, such as transient data.
	)

	fmt.Printf("Result: %s, Err: %v", result, err)
}
Output:

Example (ErrorHandling)
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/hyperledger/fabric-gateway/pkg/client"
	"google.golang.org/grpc/status"
)

func main() {
	var contract *client.Contract // Obtained from Network.

	result, err := contract.Submit("transactionName")
	if err != nil {
		switch err := err.(type) {
		case *client.EndorseError:
			panic(fmt.Errorf("transaction %s failed to endorse with gRPC status %v: %w", err.TransactionID, status.Code(err), err))
		case *client.SubmitError:
			panic(fmt.Errorf("transaction %s failed to submit to the orderer with gRPC status %v: %w", err.TransactionID, status.Code(err), err))
		case *client.CommitStatusError:
			if errors.Is(err, context.DeadlineExceeded) {
				panic(fmt.Errorf("timeout waiting for transaction %s commit status: %w", err.TransactionID, err))
			} else {
				panic(fmt.Errorf("transaction %s failed to obtain commit status with gRPC status %v: %w", err.TransactionID, status.Code(err), err))
			}
		case *client.CommitError:
			panic(fmt.Errorf("transaction %s failed to commit with status %d: %w", err.TransactionID, int32(err.Code), err))
		default:
			panic(err)
		}
	}

	fmt.Printf("Result: %s, Err: %v", result, err)
}
Output:

Example (PrivateData)
package main

import (
	"fmt"

	"github.com/hyperledger/fabric-gateway/pkg/client"
)

func main() {
	var contract *client.Contract // Obtained from Network.

	privateData := map[string][]byte{
		"price": []byte("3000"),
	}

	result, err := contract.Submit(
		"transactionName",
		client.WithArguments("one", "two"),
		client.WithTransient(privateData),
		client.WithEndorsingOrganizations("Org1MSP", "Org3MSP"),
	)

	fmt.Printf("Result: %s, Err: %v", result, err)
}
Output:

func (*Contract) SubmitAsync

func (contract *Contract) SubmitAsync(transactionName string, options ...ProposalOption) ([]byte, *Commit, error)

SubmitAsync submits a transaction to the ledger and returns its result immediately after successfully sending to the orderer, along with a Commit that can be used to wait for it to be committed to the ledger.

This method may return different error types depending on the point in the transaction invocation that a failure occurs. The error can be inspected with errors.Is or errors.As.

Example
var contract *client.Contract // Obtained from Network.

// Submit transaction to the orderer.
result, commit, err := contract.SubmitAsync("transactionName", client.WithArguments("one", "two"))
panicOnError(err)

// Use transaction result to update UI or return REST response after successful submit to the orderer.
fmt.Printf("Result: %s", result)

// Wait for transaction commit.
status, err := commit.Status()
panicOnError(err)
if !status.Successful {
	panic(fmt.Errorf("transaction %s failed to commit with status code %d", status.TransactionID, int32(status.Code)))
}
Output:

func (*Contract) SubmitAsyncWithContext added in v1.2.0

func (contract *Contract) SubmitAsyncWithContext(ctx context.Context, transactionName string, options ...ProposalOption) ([]byte, *Commit, error)

SubmitAsyncWithContext submits a transaction to the ledger in the scope of a specific context and returns its result immediately after successfully sending to the orderer, along with a Commit that can be used to wait for it to be committed to the ledger.

This method may return different error types depending on the point in the transaction invocation that a failure occurs. The error can be inspected with errors.Is or errors.As.

func (*Contract) SubmitTransaction

func (contract *Contract) SubmitTransaction(name string, args ...string) ([]byte, error)

SubmitTransaction will submit a transaction to the ledger and return its result only after it is committed to the ledger. The transaction function will be evaluated on endorsing peers and then submitted to the ordering service to be committed to the ledger.

This method may return different error types depending on the point in the transaction invocation that a failure occurs. The error can be inspected with errors.Is or errors.As.

This method is equivalent to:

contract.Submit(name, client.WithArguments(args...))

func (*Contract) SubmitWithContext added in v1.2.0

func (contract *Contract) SubmitWithContext(ctx context.Context, transactionName string, options ...ProposalOption) ([]byte, error)

SubmitWithContext submit a transaction to the ledger in the scope of a specific Context and return its result only after it has been committed to the ledger. This method provides greater control over the transaction proposal content and the endorsing peers on which it is evaluated. This allows transaction functions to be submitted where the proposal must include transient data.

This method may return different error types depending on the point in the transaction invocation that a failure occurs. The error can be inspected with errors.Is or errors.As.

type EndorseError added in v0.2.0

type EndorseError struct {
	*TransactionError
}

EndorseError represents a failure endorsing a transaction proposal.

func (EndorseError) GRPCStatus added in v0.2.0

func (e EndorseError) GRPCStatus() *status.Status

func (EndorseError) Unwrap added in v0.2.0

func (e EndorseError) Unwrap() error

type FileCheckpointer added in v1.1.0

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

FileCheckpointer is a Checkpoint implementation backed by persistent file storage. It can be used to checkpoint progress after successfully processing events, allowing eventing to be resumed from this point.

Instances should be created using the NewFileCheckpointer() constructor function. Close() should be called when the checkpointer is no longer needed to free resources.

func NewFileCheckpointer added in v1.1.0

func NewFileCheckpointer(name string) (*FileCheckpointer, error)

NewFileCheckpointer creates a properly initialized FileCheckpointer.

func (*FileCheckpointer) BlockNumber added in v1.1.0

func (c *FileCheckpointer) BlockNumber() uint64

BlockNumber in which the next event is expected.

func (*FileCheckpointer) CheckpointBlock added in v1.1.0

func (c *FileCheckpointer) CheckpointBlock(blockNumber uint64) error

CheckpointBlock records a successfully processed block.

func (*FileCheckpointer) CheckpointChaincodeEvent added in v1.1.0

func (c *FileCheckpointer) CheckpointChaincodeEvent(event *ChaincodeEvent) error

CheckpointChaincodeEvent records a successfully processed chaincode event.

func (*FileCheckpointer) CheckpointTransaction added in v1.1.0

func (c *FileCheckpointer) CheckpointTransaction(blockNumber uint64, transactionID string) error

CheckpointTransaction records a successfully processed transaction within a given block.

func (*FileCheckpointer) Close added in v1.1.0

func (c *FileCheckpointer) Close() error

Close the checkpointer when it is no longer needed to free resources.

func (*FileCheckpointer) Sync added in v1.1.0

func (c *FileCheckpointer) Sync() error

Sync commits the current state to stable storage.

func (*FileCheckpointer) TransactionID added in v1.1.0

func (c *FileCheckpointer) TransactionID() string

TransactionID of the last successfully processed event within the current block.

type FilteredBlockEventsRequest added in v1.1.0

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

FilteredBlockEventsRequest delivers filtered block events.

func (*FilteredBlockEventsRequest) Bytes added in v1.1.0

func (events *FilteredBlockEventsRequest) Bytes() ([]byte, error)

Bytes of the serialized block events request.

func (*FilteredBlockEventsRequest) Digest added in v1.1.0

func (events *FilteredBlockEventsRequest) Digest() []byte

Digest of the block events request. This is used to generate a digital signature.

func (*FilteredBlockEventsRequest) Events added in v1.1.0

func (events *FilteredBlockEventsRequest) Events(ctx context.Context, opts ...grpc.CallOption) (<-chan *peer.FilteredBlock, error)

Events returns a channel from which filtered block events can be read.

type Gateway

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

Gateway representing the connection of a specific client identity to a Fabric Gateway.

func Connect

func Connect(id identity.Identity, options ...ConnectOption) (*Gateway, error)

Connect to a Fabric Gateway using a client identity, gRPC connection and signing implementation.

func (*Gateway) Close

func (gw *Gateway) Close() error

Close a Gateway when it is no longer required. This releases all resources associated with Networks and Contracts obtained using the Gateway, including removing event listeners.

func (*Gateway) GetNetwork

func (gw *Gateway) GetNetwork(name string) *Network

GetNetwork returns a Network representing the named Fabric channel.

func (*Gateway) Identity

func (gw *Gateway) Identity() identity.Identity

Identity used by this Gateway.

func (*Gateway) NewBlockAndPrivateDataEventsRequest added in v1.1.0

func (gw *Gateway) NewBlockAndPrivateDataEventsRequest(bytes []byte) (*BlockAndPrivateDataEventsRequest, error)

NewBlockAndPrivateDataEventsRequest recreates a request to read block and private data events from serialized data.

func (*Gateway) NewBlockEventsRequest added in v1.1.0

func (gw *Gateway) NewBlockEventsRequest(bytes []byte) (*BlockEventsRequest, error)

NewBlockEventsRequest recreates a request to read block events from serialized data.

func (*Gateway) NewChaincodeEventsRequest added in v1.1.0

func (gw *Gateway) NewChaincodeEventsRequest(bytes []byte) (*ChaincodeEventsRequest, error)

NewChaincodeEventsRequest recreates a request to read chaincode events from serialized data.

func (*Gateway) NewCommit added in v1.1.0

func (gw *Gateway) NewCommit(bytes []byte) (*Commit, error)

NewCommit recreates a commit from serialized data.

func (*Gateway) NewFilteredBlockEventsRequest added in v1.1.0

func (gw *Gateway) NewFilteredBlockEventsRequest(bytes []byte) (*FilteredBlockEventsRequest, error)

NewFilteredBlockEventsRequest recreates a request to read filtered block events from serialized data.

func (*Gateway) NewProposal added in v1.1.0

func (gw *Gateway) NewProposal(bytes []byte) (*Proposal, error)

NewProposal recreates a proposal from serialized data.

func (*Gateway) NewSignedBlockAndPrivateDataEventsRequest added in v1.1.0

func (gw *Gateway) NewSignedBlockAndPrivateDataEventsRequest(bytes []byte, signature []byte) (*BlockAndPrivateDataEventsRequest, error)

NewSignedBlockAndPrivateDataEventsRequest creates a signed request to read block and private data events.

func (*Gateway) NewSignedBlockEventsRequest added in v1.1.0

func (gw *Gateway) NewSignedBlockEventsRequest(bytes []byte, signature []byte) (*BlockEventsRequest, error)

NewSignedBlockEventsRequest creates a signed request to read block events.

func (*Gateway) NewSignedChaincodeEventsRequest added in v0.2.0

func (gw *Gateway) NewSignedChaincodeEventsRequest(bytes []byte, signature []byte) (*ChaincodeEventsRequest, error)

NewSignedChaincodeEventsRequest creates a signed request to read events emitted by a specific chaincode.

func (*Gateway) NewSignedCommit added in v0.2.0

func (gw *Gateway) NewSignedCommit(bytes []byte, signature []byte) (*Commit, error)

NewSignedCommit creates an commit with signature, which can be used to access a committed transaction.

func (*Gateway) NewSignedFilteredBlockEventsRequest added in v1.1.0

func (gw *Gateway) NewSignedFilteredBlockEventsRequest(bytes []byte, signature []byte) (*FilteredBlockEventsRequest, error)

NewSignedFilteredBlockEventsRequest creates a signed request to read filtered block events.

func (*Gateway) NewSignedProposal added in v0.2.0

func (gw *Gateway) NewSignedProposal(bytes []byte, signature []byte) (*Proposal, error)

NewSignedProposal creates a transaction proposal with signature, which can be sent to peers for endorsement.

func (*Gateway) NewSignedTransaction added in v0.2.0

func (gw *Gateway) NewSignedTransaction(bytes []byte, signature []byte) (*Transaction, error)

NewSignedTransaction creates an endorsed transaction with signature, which can be submitted to the orderer for commit to the ledger.

func (*Gateway) NewTransaction added in v1.1.0

func (gw *Gateway) NewTransaction(bytes []byte) (*Transaction, error)

NewTransaction recreates a transaction from serialized data.

type InMemoryCheckpointer added in v1.1.0

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

InMemoryCheckpointer is a non-persistent Checkpoint implementation. It can be used to checkpoint progress after successfully processing events, allowing eventing to be resumed from this point.

func (*InMemoryCheckpointer) BlockNumber added in v1.1.0

func (c *InMemoryCheckpointer) BlockNumber() uint64

BlockNumber in which the next event is expected.

func (*InMemoryCheckpointer) CheckpointBlock added in v1.1.0

func (c *InMemoryCheckpointer) CheckpointBlock(blockNumber uint64)

CheckpointBlock records a successfully processed block.

func (*InMemoryCheckpointer) CheckpointChaincodeEvent added in v1.1.0

func (c *InMemoryCheckpointer) CheckpointChaincodeEvent(event *ChaincodeEvent)

CheckpointChaincodeEvent records a successfully processed chaincode event.

func (*InMemoryCheckpointer) CheckpointTransaction added in v1.1.0

func (c *InMemoryCheckpointer) CheckpointTransaction(blockNumber uint64, transactionID string)

CheckpointTransaction records a successfully processed transaction within a given block.

func (*InMemoryCheckpointer) TransactionID added in v1.1.0

func (c *InMemoryCheckpointer) TransactionID() string

TransactionID of the last successfully processed event within the current block.

type Network

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

Network represents a network of nodes that are members of a specific Fabric channel. The Network can be used to access deployed smart contracts, and to listen for events emitted when blocks are committed to the ledger. Network instances are obtained from a Gateway using the Gateway's GetNetwork() method.

To safely handle connection errors during eventing, it is recommended to use a checkpointer to track eventing progress. This allows eventing to be resumed with no loss or duplication of events.

func (*Network) BlockAndPrivateDataEvents added in v1.1.0

func (network *Network) BlockAndPrivateDataEvents(ctx context.Context, options ...BlockEventsOption) (<-chan *peer.BlockAndPrivateData, error)

BlockAndPrivateDataEvents returns a channel from which block and private data events can be read.

Example
var network *client.Network // Obtained from Gateway

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

events, err := network.BlockAndPrivateDataEvents(ctx, client.WithStartBlock(101))
panicOnError(err)

for event := range events {
	fmt.Printf("Received block number %d\n", event.GetBlock().GetHeader().GetNumber())
	// Break and cancel the context when done reading.
}
Output:

func (*Network) BlockEvents added in v1.1.0

func (network *Network) BlockEvents(ctx context.Context, options ...BlockEventsOption) (<-chan *common.Block, error)

BlockEvents returns a channel from which block events can be read.

Example
var network *client.Network // Obtained from Gateway

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

events, err := network.BlockEvents(ctx, client.WithStartBlock(101))
panicOnError(err)

for event := range events {
	fmt.Printf("Received block number %d\n", event.GetHeader().GetNumber())
	// Break and cancel the context when done reading.
}
Output:

Example (Checkpoint)
var network *client.Network // Obtained from Gateway.

checkpointer := new(client.InMemoryCheckpointer)

for {
	func() {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		events, err := network.BlockEvents(
			ctx,
			client.WithStartBlock(101), // Ignored if the checkpointer has checkpoint state
			client.WithCheckpoint(checkpointer),
		)
		panicOnError(err)

		for event := range events {
			// Process then checkpoint block
			checkpointer.CheckpointBlock(event.GetHeader().GetNumber())
		}

		_ = ctx.Err() // Reason events channel closed
	}()
}
Output:

func (*Network) ChaincodeEvents

func (network *Network) ChaincodeEvents(ctx context.Context, chaincodeName string, options ...ChaincodeEventsOption) (<-chan *ChaincodeEvent, error)

ChaincodeEvents returns a channel from which chaincode events emitted by transaction functions in the specified chaincode can be read.

Example
var network *client.Network // Obtained from Gateway.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

events, err := network.ChaincodeEvents(ctx, "chaincodeName", client.WithStartBlock(101))
panicOnError(err)

for event := range events {
	fmt.Printf("Received event: %#v\n", event)
	// Break and cancel the context when done reading.
}
Output:

Example (Checkpoint)
var network *client.Network // Obtained from Gateway.

checkpointer := new(client.InMemoryCheckpointer)

for {
	func() {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		events, err := network.ChaincodeEvents(
			ctx,
			"chaincodeName",
			client.WithStartBlock(101), // Ignored if the checkpointer has checkpoint state
			client.WithCheckpoint(checkpointer),
		)
		panicOnError(err)

		for event := range events {
			// Process event
			checkpointer.CheckpointChaincodeEvent(event)
		}

		_ = ctx.Err() // Reason events channel closed
	}()
}
Output:

func (*Network) FilteredBlockEvents added in v1.1.0

func (network *Network) FilteredBlockEvents(ctx context.Context, options ...BlockEventsOption) (<-chan *peer.FilteredBlock, error)

FilteredBlockEvents returns a channel from which filtered block events can be read.

Example
var network *client.Network // Obtained from Gateway

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

events, err := network.FilteredBlockEvents(ctx, client.WithStartBlock(101))
panicOnError(err)

for event := range events {
	fmt.Printf("Received block number %d\n", event.GetNumber())
	// Break and cancel the context when done reading.
}
Output:

func (*Network) GetContract

func (network *Network) GetContract(chaincodeName string) *Contract

GetContract returns a Contract representing the default smart contract for the named chaincode.

func (*Network) GetContractWithName

func (network *Network) GetContractWithName(chaincodeName string, contractName string) *Contract

GetContractWithName returns a Contract representing a smart contract within a named chaincode.

func (*Network) Name

func (network *Network) Name() string

Name of the Fabric channel this network represents.

func (*Network) NewBlockAndPrivateDataEventsRequest added in v1.1.0

func (network *Network) NewBlockAndPrivateDataEventsRequest(options ...BlockEventsOption) (*BlockAndPrivateDataEventsRequest, error)

NewBlockAndPrivateDataEventsRequest creates a request to read block and private data events. Supports off-line signing flow.

func (*Network) NewBlockEventsRequest added in v1.1.0

func (network *Network) NewBlockEventsRequest(options ...BlockEventsOption) (*BlockEventsRequest, error)

NewBlockEventsRequest creates a request to read block events. Supports off-line signing flow.

func (*Network) NewChaincodeEventsRequest

func (network *Network) NewChaincodeEventsRequest(chaincodeName string, options ...ChaincodeEventsOption) (*ChaincodeEventsRequest, error)

NewChaincodeEventsRequest creates a request to read events emitted by the specified chaincode. Supports off-line signing flow.

func (*Network) NewFilteredBlockEventsRequest added in v1.1.0

func (network *Network) NewFilteredBlockEventsRequest(options ...BlockEventsOption) (*FilteredBlockEventsRequest, error)

NewFilteredBlockEventsRequest creates a request to read filtered block events. Supports off-line signing flow.

type Proposal

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

Proposal represents a transaction proposal that can be sent to peers for endorsement or evaluated as a query.

func (*Proposal) Bytes

func (proposal *Proposal) Bytes() ([]byte, error)

Bytes of the serialized proposal message.

func (*Proposal) Digest

func (proposal *Proposal) Digest() []byte

Digest of the proposal. This is used to generate a digital signature.

func (*Proposal) Endorse

func (proposal *Proposal) Endorse(opts ...grpc.CallOption) (*Transaction, error)

Endorse the proposal and obtain an endorsed transaction for submission to the orderer.

func (*Proposal) EndorseWithContext

func (proposal *Proposal) EndorseWithContext(ctx context.Context, opts ...grpc.CallOption) (*Transaction, error)

EndorseWithContext uses ths supplied context to endorse the proposal and obtain an endorsed transaction for submission to the orderer.

func (*Proposal) Evaluate

func (proposal *Proposal) Evaluate(opts ...grpc.CallOption) ([]byte, error)

Evaluate the proposal and obtain a transaction result. This is effectively a query.

func (*Proposal) EvaluateWithContext

func (proposal *Proposal) EvaluateWithContext(ctx context.Context, opts ...grpc.CallOption) ([]byte, error)

EvaluateWithContext uses ths supplied context to evaluate the proposal and obtain a transaction result. This is effectively a query.

func (*Proposal) TransactionID

func (proposal *Proposal) TransactionID() string

TransactionID for the proposal.

type ProposalOption

type ProposalOption = func(builder *proposalBuilder) error

ProposalOption implements an option for a transaction proposal.

func WithArguments

func WithArguments(args ...string) ProposalOption

WithArguments appends to the transaction function arguments associated with a transaction proposal.

func WithBytesArguments

func WithBytesArguments(args ...[]byte) ProposalOption

WithBytesArguments appends to the transaction function arguments associated with a transaction proposal.

func WithEndorsingOrganizations

func WithEndorsingOrganizations(mspids ...string) ProposalOption

WithEndorsingOrganizations specifies the organizations that should endorse the transaction proposal. No other organizations will be sent the proposal. This is usually used in combination with WithTransient for private data scenarios, or for state-based endorsement when specific organizations have to endorse the proposal.

func WithTransient

func WithTransient(transient map[string][]byte) ProposalOption

WithTransient specifies the transient data associated with a transaction proposal. This is usually used in combination with WithEndorsingOrganizations for private data scenarios

type Status

type Status struct {
	Code          peer.TxValidationCode
	Successful    bool
	TransactionID string
	BlockNumber   uint64
}

Status of a committed transaction.

type SubmitError added in v0.2.0

type SubmitError struct {
	*TransactionError
}

SubmitError represents a failure submitting an endorsed transaction to the orderer.

func (SubmitError) GRPCStatus added in v0.2.0

func (e SubmitError) GRPCStatus() *status.Status

func (SubmitError) Unwrap added in v0.2.0

func (e SubmitError) Unwrap() error

type Transaction

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

Transaction represents an endorsed transaction that can be submitted to the orderer for commit to the ledger.

func (*Transaction) Bytes

func (transaction *Transaction) Bytes() ([]byte, error)

Bytes of the serialized transaction.

func (*Transaction) Digest

func (transaction *Transaction) Digest() []byte

Digest of the transaction. This is used to generate a digital signature.

func (*Transaction) Result

func (transaction *Transaction) Result() []byte

Result of the proposed transaction invocation.

func (*Transaction) Submit

func (transaction *Transaction) Submit(opts ...grpc.CallOption) (*Commit, error)

Submit the transaction to the orderer for commit to the ledger.

func (*Transaction) SubmitWithContext

func (transaction *Transaction) SubmitWithContext(ctx context.Context, opts ...grpc.CallOption) (*Commit, error)

SubmitWithContext uses the supplied context to submit the transaction to the orderer for commit to the ledger.

func (*Transaction) TransactionID

func (transaction *Transaction) TransactionID() string

TransactionID of the transaction.

type TransactionError added in v0.2.0

type TransactionError struct {
	TransactionID string
	// contains filtered or unexported fields
}

TransactionError represents an error invoking a transaction. This is a gRPC status error.

func (TransactionError) GRPCStatus added in v0.2.0

func (e TransactionError) GRPCStatus() *status.Status

func (TransactionError) Unwrap added in v0.2.0

func (e TransactionError) Unwrap() error

Jump to

Keyboard shortcuts

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