gohfc

package module
v0.0.0-...-358a52c Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2018 License: Apache-2.0 Imports: 47 Imported by: 0

README

GOHFC - Golang Hyperledger Fabric Client

This is SDK for Hyperledger Fabric written in pure Golang using minimum requirements. This is not official SDK and does not follow official SDK API guidelines provided by Hyperledger team. For the list of official SDK's refer to the official Hyperledger documentation.

It is designed to be easy to use and to be fast as possible. Currently, it outperforms the official Go SDK by far.

We are using it in our production applications, but no guarantees are provided.

This version will be updated and supported, so pull requests and reporting any issues are more than welcome.

Recommended Go version is >=1.9

This SDK is tested for Hyperledger Fabric 1.1.x.

Versions 1.0.x should work, but some features will not be available. We are not planning to support 1.0.x anymore. We are planning to keep backward comparability for versions >=1.1.x

For examples see examples folder.

Dependency

go get -u golang.org/x/crypto/sha3
go get -u gopkg.in/yaml.v2

Installation

go get -u github.com/CognitionFoundry/gohfc

Basic concepts

Gohfc provide two high level clients, one for FabricCA and one for Fabric. They work together but user may use them separately.

FabricCAClient is client to work with Fabric certificate authority (CA) and allows you to register, enroll, revoke certificates, manage affiliations and attributes.

Every operation in Fabric MUST be signed by proper certificate. You can generate this certificates using openssl or other tools, but FabricCA server makes this procedure much more streamline and hides a lot of the complexity.

FabricCAClient can be used to generate complete MSP structure if you do not want to use cryptogen tool for some reason.

FabricClient expose high level API's for working with blockchain, ledger, chaincodes, channels and events.

General flow is like this:

  • Start Fabric using docker-compose or any other tool appropriate for you. Running Fabric is not responsibility of gohfc.
  • Create one or many channels by sending channels config to orderer. This is done using gohfc.CreateUpdateChannel
  • Join one or more peers to one or more channels. This is done using gohfc.JoinChannel
  • Install one or many chaincodes in one or many peers. This can be done using gohfc.InstallChainCode
  • Instantiate one or more already installed chaincodes. This can be dine using gohfc.InstantiateChainCode
  • Query chaincode using gohfc.Query. This is readonly operation. No changes to blockchain or ledger will be made.
  • Invoke chaincode using gohfc.Invoke. This operation may update the blockchain and the ledger.
  • Listen for events using gohfc.ListenForFullBlock or gohfc.ListenForFilteredBlock

There are many more methods to get particular block, list channels, get chaincodes etc.

See examples folder.

Initialization

Both clients can be initialised from yaml file or manually.

FabricCAClient config file:


---
url: http://ca.example.com:7052 # URL for the CA server
skipTLSValidation: true         # skip TLS verification in case when you are not providing custom transport
mspId: comp1Msp                 # this value will be added automatically to any gohfc.Identity returned from this CA  
crypto:                         # cryptographic settings 
  family: ecdsa                 
  algorithm: P256-SHA256         
  hash: SHA2-256
  

FabricCAClient initialization from config file:

caClient, err := gohfc.NewCAClient("./ca.yaml", nil)
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}

About MSPId

Every peer and orderer in Fabric must have set of cryptographic materials like root CA certificates, intermediate certificates, list of revoked certificates and more. This set of certificates is associated with ID and this ID is called MSP (member service provider). In every operation MSPID must be provided so the peer and orderer know which set of crypto materials to load and to use for verification of the request.

In general MSP define a organization and entities inside organization with there roles. Couple of MSP's are combined to form a consortium so multiple organizations, each one with own set of certificates, can work together.

So when any request to fabric is send this request must be signed by Ecert (user certificate hold in gohfc.Identity) and MSPID must be provided so Fabric loads MSP by ID, make verification that this request is coming from member of the organization and that this member has the appropriate access.

Because (in general case) one FabricCa is serving one organization (one MSP) it makes sense to put this ID in config and to auto populate it when new gohfc.Identity is generated (enroll or reenroll). This is for convenience, user can always overwrite this value.

FabricClient config file:


---
crypto:
  family: ecdsa
  algorithm: P256-SHA256
  hash: SHA2-256
orderers:
  orderer0:
    host: orderer0.example.com:7050
    useTLS: false
    tlsPath: /path/to/tls/server.pem
  orderer1:
    host: orderer0.example.com:7048
    useTLS: false
    tlsPath: /path/to/tls/server.pem
peers:
  peer01:
    host: peer0.example.com:7051
    useTLS: false
    tlsPath: /path/to/tls/server.pem
  peer11:
    host: peer1.example.com:8051
    useTLS: false
    tlsPath: /path/to/tls/server.pem
  peer02:
    host: peer0.example.com:9051
    useTLS: false
    tlsPath: /path/to/tls/server.pem
  peer12:
      host: peer1.example.com:10051
      useTLS: false
      tlsPath: /path/to/tls/server.pem
eventPeers:
  peer0:
    host: peer0.example.com:7051
    useTLS: false
    tlsPath: /path/to/tls/server.pem


FabricClient initialization from config file:

c, err := gohfc.NewFabricClient("./client.yaml")
if err != nil {
    fmt.Printf("Error loading file: %v", err)
	os.Exit(1)
}

Install chaincode

When new chaincode is installed a struct of type gohfc.InstallRequest must be provided:


request := &gohfc.InstallRequest{
    ChainCodeType:    gohfc.ChaincodeSpec_GOLANG,
    ChannelId:        "testchannel",
    ChainCodeName:    "samplechaincode",
    ChainCodeVersion: "1.0",
    Namespace:        "github.com/hyperledger/fabric-samples/chaincode/chaincode_example02/go/",
    SrcPath:          "/absolute/path/to/folder/containing/chaincode",
    Libraries: []gohfc.ChaincodeLibrary{
        {
            Namespace: "namespace",
            SrcPath:   "path",
        },
    },
}

Fabric will support chaincode written in different languages, so language type must be specified using ChainCodeType Gohfc for now support only Go. Other chaincode languages will be added later when Fabric officially start support them.

ChannelId is the channel name where the chaincode must be installed.

ChainCodeName is the name of the chaincode. This name will be used in future requests (query, invoke, etc..) to specify which chaincode must be executed. One channel may have multiple chaincodes. name must be unique in context of a channel.

ChainCodeVersion specify the version.

Gohfc is designed to work without need of Go environment. So when user try to install chaincode he/she must provide Namespace,SrcPath and optional Libraries

Namespace is the Go namespace where chaincode will be "installed" in Fabric runtime. Like github.com/some/code

SrcPath is the absolute path where source code is located, from where it must be red, packed and prepared for install.

This separation allows gohfc to run without any external runtime dependencies, also this is very flexible in context of CI,CD systems.

Libraries is a optional list of libraries that will be included in packing of the chaincode. They follow the same logic of Namespace and SrcPath.

Vendoring the dependencies is an option, but in more complex chaincodes is much better to have some library installed as library and not as vendored dependencies in multiple places.

Note about names

Many operations require specific peer or orderer to be specified. Gohfc use name alias for this, and names are taken from config file. For example, if you want to query specific peers:

client.Query(*identity, *chaincode, []string{"peer01","peer11"})

In this example "peer01" and "peer11" are names given to peers in config file and query operation will be send to this two peers.

TODO

  • full block decoding. For now user can take raw block data, but will be much better to provide utility functions to decode block
  • specify policy in InstantiateChainCode. Waiting for official tool from Fabric and decide how to integrate it.
  • gencrl call for FabricCA
  • easy mutual TLS configuration
Available cryptographic algorithms
Family Algorithm Description
ecdsa P256-SHA256 Elliptic curve is P256 and signature uses SHA256
ecdsa P384-SHA384 Elliptic curve is P384 and signature uses SHA384
ecdsa P521-SHA512 Elliptic curve is P521 and signature uses SHA512
rsa ---- RSA is not supported in Fabric
Hash
Family
SHA2-256
SHA2-384
SHA3-256
SHA3-384

Documentation

Overview

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Copyright: Cognition Foundry. All Rights Reserved. License: Apache License Version 2.0

Index

Constants

View Source
const (
	EventTypeFullBlock = iota
	EventTypeFiltered
)
View Source
const CSCC = "cscc"
View Source
const LSCC = "lscc"
View Source
const QSCC = "qscc"

Variables

View Source
var (
	ErrInvalidAlgorithmFamily       = errors.New("invalid algorithm family")
	ErrInvalidAlgorithm             = errors.New("invalid algorithm for ECDSA")
	ErrInvalidHash                  = errors.New("invalid hash algorithm")
	ErrInvalidKeyType               = errors.New("invalid key type is provided")
	ErrEnrollmentIdMissing          = errors.New("enrollment id is empty")
	ErrEnrolmentMissing             = errors.New("enrollment ID is missing")
	ErrAffiliationMissing           = errors.New("affiliation is missing")
	ErrTypeMissing                  = errors.New("type is missing")
	ErrCertificateEmpty             = errors.New("certificate cannot be nil")
	ErrInvalidDataForParcelIdentity = errors.New("invalid data for parsing identity")
	ErrInvalidOrdererName           = errors.New("orderer with this name is not found")
	ErrOrdererTimeout               = errors.New("orderer response timeout")
	ErrBadTransactionStatus         = errors.New("transaction status is not 200")
	ErrEndorsementsDoNotMatch       = errors.New("endorsed responses are different")
	ErrNoValidEndorsementFound      = errors.New("invocation was not endorsed")
	ErrPeerNameNotFound             = errors.New("peer name is not found")
	ErrUnsupportedChaincodeType     = errors.New("this chainCode type is not currently supported")
	ErrMspMissing                   = errors.New("mspid cannot be empty")
	ErrCollectionNameMissing        = errors.New("collection must have name")
	ErrCollectionNameExists         = errors.New("collection name must be unique")
	ErrRequiredPeerCountNegative    = errors.New("required peers count cannot be negative")
	ErrMaxPeerCountNegative         = errors.New("required peers count cannot be negative")
	ErrMaxPeerCountLestThanMinimum  = errors.New("maximum peers count cannot be lower than minimum")
	ErrAtLeastOneOrgNeeded          = errors.New("at least one organization is needed")
	ErrOrganizationNameMissing      = errors.New("organization must have name")
	ErrAffiliationNameMissing       = errors.New("affiliation must have name")
	ErrAffiliationNewNameMissing    = errors.New("affiliation must have new name")
	ErrIdentityNameMissing          = errors.New("identity must have  name")
)

Functions

func CollectionConfigToPolicy

func CollectionConfigToPolicy(col []CollectionConfig) ([]*common.CollectionConfig, error)

func MarshalIdentity

func MarshalIdentity(i *Identity) (string, error)

MarshalIdentity marshal identity to string

Types

type CAAddAffiliationRequest

type CAAddAffiliationRequest struct {
	// Name is the name of the affiliation. Hierarchical structure is created using .(dot) like `org1.department1`.
	Name string `json:"name"`
	// Force forces creation of missing parent affiliation. If `force` is false and parent/s is missing error will be returned.
	Force bool `json:"force"`
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string `json:"caname,omitempty"`
}

CAAddAffiliationRequest contains needed data for creating new affiliation

type CAAffiliationInfo

type CAAffiliationInfo struct {
	// Name is the name of the affiliation
	Name string `json:"name"`
	// Affiliations is list of affiliations that are child to current one
	Affiliations []CAAffiliationInfo `json:"affiliations,omitempty"`
}

CAAffiliationInfo represent affiliation returned from FabricCA

type CAAffiliationResponse

type CAAffiliationResponse struct {
	CAAffiliationInfo
	CAName string `json:"caname,omitempty"`
}

CAAffiliationResponse holds response for all operations with affiliation.

type CAConfig

type CAConfig struct {
	CryptoConfig      `yaml:"crypto"`
	Uri               string `yaml:"url"`
	SkipTLSValidation bool   `yaml:"skipTLSValidation"`
	MspId             string `yaml:"mspId"`
}

CAConfig holds config for Fabric CA

func NewCAConfig

func NewCAConfig(path string) (*CAConfig, error)

NewCAConfig create new Fabric CA config from provided yaml file in path

type CAGetCertsResponse

type CAGetCertsResponse struct {
	// RootCertificates is list of pem encoded certificates
	RootCertificates []*pem.Block
	// IntermediateCertificates is list of pem encoded intermediate certificates
	IntermediateCertificates []*pem.Block
	// CAName is the name of the CA server that returns this certificates
	CAName string
	// Version is the version of server that returns this certificates
	Version string
}

CAGetCertsResponse holds response from `GetCaCertificateChain`

type CAGetIdentityResponse

type CAGetIdentityResponse struct {
	CaIdentityResponse
	// Name is the name of the affiliation
	CAName string `json:"caname"`
}

CAGetIdentityResponse holds response from `GetIdentity` call

type CAListAllIdentitiesResponse

type CAListAllIdentitiesResponse struct {
	// Name is the name of the affiliation
	CAName string `json:"caname"`
	// Affiliations is list of affiliations that are child to current one
	Identities []CaIdentityResponse `json:"identities,omitempty"`
}

CAListAllIdentitiesResponse hold response for `ListAllIdentities` call

type CAModifyAffiliationRequest

type CAModifyAffiliationRequest struct {
	// Name is the name of the affiliation to be updated like `org1.department1`.
	Name string
	// New name is the new name of the affiliation.
	NewName string `json:"name"`
	// Force will force identities using old affiliation to use new affiliation.
	Force bool `json:"force"`
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string `json:"caname,omitempty"`
}

CAModifyAffiliationRequest holds data needed to update existing affiliation stored in FabricCa server

type CAModifyIdentityRequest

type CAModifyIdentityRequest struct {
	ID             string                `json:"-"`
	Type           string                `json:"type"`
	Affiliation    string                `json:"affiliation"`
	Attributes     []CaRegisterAttribute `json:"attrs"`
	MaxEnrollments int                   `json:"max_enrollments"`
	Secret         string                `json:"secret,omitempty"`
	CAName         string                `json:"caname,omitempty"`
}

CAModifyIdentityRequest holds data that will be used to update existing identity

type CARegistrationRequest

type CARegistrationRequest struct {
	// EnrolmentId is unique name that identifies identity
	EnrolmentId string `json:"id"`
	// Type defines type of this identity (user,client, auditor etc...)
	Type string `json:"type"`
	// Secret is password that will be used for enrollment. If not provided random password will be generated
	Secret string `json:"secret,omitempty"`
	// MaxEnrollments define maximum number of times that identity can enroll. If not provided or is 0 there is no limit
	MaxEnrollments int `json:"max_enrollments,omitempty"`
	// Affiliation associates identity with particular organisation.
	// for example org1.department1 makes this identity part of organisation `org1` and department `department1`
	// Hierarchical structure can be created using .(dot). For example org1.dep1 will create dep1 as part of org1
	Affiliation string `json:"affiliation"`
	// Attrs are attributes associated with this identity
	Attrs []CaRegisterAttribute `json:"attrs"`
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string `json:"caname,omitempty"`
}

RegistrationRequest holds all data needed for new registration of new user in Certificate Authority

type CARemoveAffiliationRequest

type CARemoveAffiliationRequest struct {
	// Name is the name of the affiliation to be removed. Dot can be used to specify child like `org1.department1`.
	Name string
	// Force will force removal of child affiliations and any identity associated with them
	Force bool
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string
}

CARemoveAffiliationRequest contains needed data for removing existing affiliation

type CARemoveIdentityRequest

type CARemoveIdentityRequest struct {
	// Name is the id of the identity to be removed.
	Name string
	// Force will force removal of your own identity
	Force bool
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string
}

CARemoveIdentityRequest contains needed data for removing existing identity

type CARevocationRequest

type CARevocationRequest struct {
	// EnrollmentId of the identity whose certificates should be revoked
	// If this field is omitted, then Serial and AKI must be specified.
	EnrollmentId string `json:"id,omitempty"`
	// Serial number of the certificate to be revoked
	// If this is omitted, then EnrollmentId must be specified
	Serial string `json:"serial,omitempty"`
	// AKI (Authority Key Identifier) of the certificate to be revoked
	AKI string `json:"aki,omitempty"`
	// Reason is the reason for revocation.  See https://godoc.org/golang.org/x/crypto/ocsp for
	// valid values.  The default value is 0 (ocsp.Unspecified).
	Reason int `json:"reason,omitempty"`
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string `json:"caname,omitempty"`
	// GenCRL specifies whether to generate a CRL. CRL will be returned only when AKI and Serial are provided.
	GenCRL bool `json:"gencrl,omitempty"`
}

CARevocationRequest holds data needed to revoke certificate in fabric-ca If AKI and Serial are provided this will revoke specific certificate. If EnrolmentID is provided all certificated for this EnrollmentID will be revoked and all his/hers future attempts to enroll will fail.

type CaEnrollAttribute

type CaEnrollAttribute struct {
	// Name is the name of the attribute
	Name string `json:"name"`
	// Optional define behaviour when required attribute is not available to user. If `true` then request will continue,
	// but attribute will not be included in ECert. If `false` and attribute is missing, request will fail.
	// If false and attribute is available, request will continue and attribute will be added in ECert
	Optional bool `json:"optional,omitempty"`
}

CaEnrollAttribute describe attribute that must be included in enrollment request

type CaEnrollmentRequest

type CaEnrollmentRequest struct {
	// EnrollmentId is the unique entity identifies
	EnrollmentId string
	// Secret is the password for this identity
	Secret string
	// Profile define which CA profile to be used for signing. When this profile is empty default profile is used.
	// This is the common situation when issuing and ECert.
	// If request is fo generating TLS certificates then profile must be `tls`
	// If operation is related to parent CA server then profile must be `ca`
	// In FabricCA custom profiles can be created. In this situation use custom profile name.
	Profile string `json:"profile,omitempty"`
	// Label is used for hardware secure modules.
	Label string `json:"label,omitempty"`
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string `json:"caname,omitempty"`
	// Host is the list of valid host names for this certificate. If empty default hosts will be used
	Hosts []string `json:"hosts"`
	// Attrs are the attributes that must be included in ECert. This is subset of the attributes used in registration.
	Attrs []CaEnrollAttribute `json:"attr_reqs,omitempty"`
}

CaEnrollmentRequest holds data needed for getting ECert (enrollment) from CA server

type CaIdentityResponse

type CaIdentityResponse struct {
	ID             string                `json:"id"`
	Type           string                `json:"type"`
	Affiliation    string                `json:"affiliation"`
	Attributes     []CaRegisterAttribute `json:"attrs" mapstructure:"attrs"`
	MaxEnrollments int                   `json:"max_enrollments" mapstructure:"max_enrollments"`
}

CaIdentityResponse represent identity

type CaReEnrollmentRequest

type CaReEnrollmentRequest struct {
	Identity *Identity
	// Profile define which CA profile to be used for signing. When this profile is empty default profile is used.
	// This is the common situation when issuing and ECert.
	// If request is fo generating TLS certificates then profile must be `tls`
	// If operation is related to parent CA server then profile must be `ca`
	// In FabricCA custom profiles can be created. In this situation use custom profile name.
	Profile string `json:"profile,omitempty"`
	// Label is used for hardware secure modules.
	Label string `json:"label,omitempty"`
	// CAName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and
	// this names are used to distinguish between them. If empty default CA instance will be used.
	CAName string `json:"caname,omitempty"`
	// Host is the list of valid host names for this certificate. If empty default hosts will be used
	Hosts []string `json:"hosts"`
	// Attrs are the attributes that must be included in ECert. This is subset of the attributes used in registration.
	Attrs []CaEnrollAttribute `json:"attr_reqs,omitempty"`
}

CaReEnrollmentRequest holds data needed for getting new ECert from CA server

type CaRegisterAttribute

type CaRegisterAttribute struct {
	// Name is the name of the attribute.
	Name string `json:"name"`
	// Value is the value of the attribute. Can be empty string
	Value string `json:"value"`
	// ECert define how this attribute will be included in ECert. If this value is true this attribute will be
	// added to ECert automatically on Enrollment if no attributes are requested on Enrollment request.
	ECert bool `json:"ecert,omitempty"`
}

CaRegisterAttribute holds user attribute used for registration for example user may have attr `accountType` with value `premium` this attributes can be accessed in chainCode and build business logic on top of them

type CaRevokeResult

type CaRevokeResult struct {
	// RevokedCertificates is list of revoked certificates
	RevokedCertificates []CaRevokeResultCertificate `json:"RevokedCerts"`
	// CRL is the certificate revocation list from the operation.
	CRL string `json:"CRL"`
}

CaRevokeResult is holding result from FabricCA revoke

type CaRevokeResultCertificate

type CaRevokeResultCertificate struct {
	// Serial is revoked certificate serial number
	Serial string `json:"Serial"`
	// AKI is revoked certificate AKI
	AKI string `json:"AKI"`
}

CaRevokeResultCertificate identify revoked certificate

type ChainCode

type ChainCode struct {
	ChannelId    string
	Name         string
	Version      string
	Type         ChainCodeType
	Args         []string
	ArgBytes     []byte
	TransientMap map[string][]byte
	// contains filtered or unexported fields
}

ChainCode the fields necessary to execute operation over chaincode.

type ChainCodeType

type ChainCodeType int32
const (
	ChaincodeSpec_UNDEFINED ChainCodeType = 0
	ChaincodeSpec_GOLANG    ChainCodeType = 1
	ChaincodeSpec_NODE      ChainCodeType = 2
	ChaincodeSpec_CAR       ChainCodeType = 3
	ChaincodeSpec_JAVA      ChainCodeType = 4
)

type ChainCodesResponse

type ChainCodesResponse struct {
	PeerName   string
	Error      error
	ChainCodes []*peer.ChaincodeInfo
}

ChainCodesResponse is the result of queering installed and instantiated chaincodes

type ChaincodeLibrary

type ChaincodeLibrary struct {
	Namespace string
	SrcPath   string
}

type ClientConfig

type ClientConfig struct {
	CryptoConfig `yaml:"crypto"`
	Orderers     map[string]OrdererConfig `yaml:"orderers"`
	Peers        map[string]PeerConfig    `yaml:"peers"`
	EventPeers   map[string]PeerConfig    `yaml:"eventPeers"`
}

ClientConfig holds config data for crypto, peers and orderers

func NewClientConfig

func NewClientConfig(path string) (*ClientConfig, error)

NewFabricClientConfig create config from provided yaml file in path

type CollectionConfig

type CollectionConfig struct {
	Name               string
	RequiredPeersCount int32
	MaximumPeersCount  int32
	Organizations      []string
}

type CryptoConfig

type CryptoConfig struct {
	Family    string `yaml:"family"`
	Algorithm string `yaml:"algorithm"`
	Hash      string `yaml:"hash"`
}

Config holds config values for fabric and fabric-ca cryptography

type CryptoSuite

type CryptoSuite interface {
	// GenerateKey returns PrivateKey.
	GenerateKey() (interface{}, error)
	// CreateCertificateRequest will create CSR request. It takes enrolmentId and Private key
	CreateCertificateRequest(enrollmentId string, key interface{}, hosts []string) ([]byte, error)
	// Sign signs message. It takes message to sign and Private key
	Sign(msg []byte, key interface{}) ([]byte, error)
	// Hash computes Hash value of provided data. Hash function will be different in different crypto implementations.
	Hash(data []byte) []byte
}

CryptSuite defines common interface for different crypto implementations. Currently Hyperledger Fabric supports only Elliptic curves.

func NewECCryptSuiteFromConfig

func NewECCryptSuiteFromConfig(config CryptoConfig) (CryptoSuite, error)

NewECCryptSuite creates new Elliptic curve crypto suite from config

type ECCryptSuite

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

ECCryptSuite implements Ecliptic curve crypto suite

func (*ECCryptSuite) CreateCertificateRequest

func (c *ECCryptSuite) CreateCertificateRequest(enrollmentId string, key interface{}, hosts []string) ([]byte, error)

func (*ECCryptSuite) GenerateKey

func (c *ECCryptSuite) GenerateKey() (interface{}, error)

func (*ECCryptSuite) Hash

func (c *ECCryptSuite) Hash(data []byte) []byte

func (*ECCryptSuite) Sign

func (c *ECCryptSuite) Sign(msg []byte, k interface{}) ([]byte, error)

type EventBlockResponse

type EventBlockResponse struct {
	Error        error
	ChannelId    string
	BlockHeight  uint64
	Transactions []EventBlockResponseTransaction
	RawBlock     []byte
}

type EventBlockResponseTransaction

type EventBlockResponseTransaction struct {
	Id          string
	Type        string
	Status      string
	ChainCodeId string
	Events      []EventBlockResponseTransactionEvent
}

type EventBlockResponseTransactionEvent

type EventBlockResponseTransactionEvent struct {
	Name  string
	Value []byte
}

type EventListener

type EventListener struct {
	Peer         Peer
	Context      context.Context
	Identity     Identity
	Crypto       CryptoSuite
	ChannelId    string
	ListenerType int
	FullBlock    bool
	// contains filtered or unexported fields
}

func NewEventListener

func NewEventListener(ctx context.Context, crypto CryptoSuite, identity Identity, p Peer, channelId string, listenerType int) (*EventListener, error)

func (*EventListener) Listen

func (e *EventListener) Listen(response chan<- EventBlockResponse)

func (*EventListener) SeekNewest

func (e *EventListener) SeekNewest() error

func (*EventListener) SeekOldest

func (e *EventListener) SeekOldest() error

func (*EventListener) SeekRange

func (e *EventListener) SeekRange(start, end uint64) error

func (*EventListener) SeekSingle

func (e *EventListener) SeekSingle(num uint64) error

type FabricCAClient

type FabricCAClient struct {
	// Uri is access point for fabric-ca server. Port number and scheme must be provided.
	// for example http://127.0.0.1:7054
	Url string
	// SkipTLSVerification define how connection must handle invalid TLC certificates.
	// if true, all verifications are skipped. This value is overwritten by Transport property, if provided
	SkipTLSVerification bool
	// Crypto is CryptSuite implementation used to sign request for fabric-ca server
	Crypto CryptoSuite
	// Transport define transport rules for communication with fabric-ca server. If nil, default Go setting will be used
	// It is responsibility of the user to provide proper TLS/certificate setting in TLS communication.
	Transport *http.Transport
	// MspId value will be added to Identity in Enrollment and ReEnrollment invocations.
	// This value is not used anywhere in CA implementation, but is need in every call to Fabric and is added here
	// for convenience, because (in general case) FabricCA is serving one MSP
	// User can overwrite this value at any time.
	MspId string
}

FabricCAClient is client implementation for fabric-ca server

func NewCAClient

func NewCAClient(path string, transport *http.Transport) (*FabricCAClient, error)

NewFabricCAClient creates new FabricCAClient from configuration file path is the file path for configuration file transport is the transport that will be used in all requests. If transport is nil default transport will be used. It is responsibility of the SDK user to provide correct settings and TLS certificates if custom transport is provided.

func NewCaClientFromConfig

func NewCaClientFromConfig(config CAConfig, transport *http.Transport) (*FabricCAClient, error)

NewCaClientFromConfig creates new FabricCAClient from CAConfig

func (*FabricCAClient) AddAffiliation

func (f *FabricCAClient) AddAffiliation(identity *Identity, req CAAddAffiliationRequest) (*CAAffiliationResponse, error)

AddAffiliation add new affiliation to FabricCa

func (*FabricCAClient) Enroll

func (f *FabricCAClient) Enroll(request CaEnrollmentRequest) (*Identity, []byte, error)

Enroll execute enrollment request for registered user in FabricCA server. On success new Identity with ECert and generated csr are returned.

func (*FabricCAClient) GetCaCertificateChain

func (f *FabricCAClient) GetCaCertificateChain(caName string) (*CAGetCertsResponse, error)

GetCaCertificateChain gets root and intermediate certificates used by FabricCA server. This certificates must be presented to Fabric entities (peers, orderers) as MSP so they can verify that request are from valid entities. caName is the name of the CA that should be used. FabricCa support more than one CA server on same endpoint and this names are used to distinguish between them. If empty default CA instance will be used.

func (*FabricCAClient) GetIdentity

func (f *FabricCAClient) GetIdentity(identity *Identity, id string, caName string) (*CAGetIdentityResponse, error)

GetIdentity get single identity defined by `id` from FabricCa server

func (*FabricCAClient) ListAffiliations

func (f *FabricCAClient) ListAffiliations(identity *Identity, path string, caName string) (*CAAffiliationResponse, error)

ListAffiliations get list of all affiliations registered in FabricCa. If `path` is specified result will contains only affiliations "bellow" path, else full tree will be returned.

func (*FabricCAClient) ListAllIdentities

func (f *FabricCAClient) ListAllIdentities(identity *Identity, caName string) (*CAListAllIdentitiesResponse, error)

ListAllIdentities get list of all identities from FabricCa server

func (*FabricCAClient) ModifyAffiliation

func (f *FabricCAClient) ModifyAffiliation(identity *Identity, req CAModifyAffiliationRequest) (*CAAffiliationResponse, error)

ModifyAffiliation will modify existing affiliation

func (*FabricCAClient) ModifyIdentity

func (f *FabricCAClient) ModifyIdentity(identity *Identity, req CAModifyIdentityRequest) (*CAGetIdentityResponse, error)

ModifyIdentity will update existing identity

func (*FabricCAClient) ReEnroll

func (f *FabricCAClient) ReEnroll(request CaReEnrollmentRequest) (*Identity, []byte, error)

ReEnroll create new certificate from old one. Useful when certificate is about to expire. Difference with `Enroll` is that `Enroll` require identity with `Registar` role. In re-enrolment the old certificate is used to identify the identity.

func (*FabricCAClient) Register

func (f *FabricCAClient) Register(identity *Identity, req *CARegistrationRequest) (string, error)

Register registers new user in fabric-ca server. In registration request attributes, affiliation and max enrolments must be set. It is responsibility of the SDK user to ensure passwords are with big entropy. Identity parameter is certificate for user that makes registration and this user MUST have the role for registering new users.

func (*FabricCAClient) RemoveAffiliation

func (f *FabricCAClient) RemoveAffiliation(identity *Identity, req CARemoveAffiliationRequest) (*CAAffiliationResponse, error)

RemoveAffiliation remove affiliation from FabricCa server. FabricCa server must be configured to allows removal of affiliations.

func (*FabricCAClient) RemoveIdentity

func (f *FabricCAClient) RemoveIdentity(identity *Identity, req CARemoveIdentityRequest) (*CAGetIdentityResponse, error)

RemoveIdentity remove identity fromFabricCA. FabricCA must be configured to allow this operation

func (*FabricCAClient) Revoke

func (f *FabricCAClient) Revoke(identity *Identity, request *CARevocationRequest) (*CaRevokeResult, error)

Revoke revokes ECert in fabric-ca server. Note that this request will revoke certificate ONLY in FabricCa server. Peers (for now) do not know about this certificate revocation. It is responsibility of the SDK user to update peers and set this certificate in every peer revocation list.

type FabricClient

type FabricClient struct {
	Crypto     CryptoSuite
	Peers      map[string]*Peer
	Orderers   map[string]*Orderer
	EventPeers map[string]*Peer
}

FabricClient expose API's to work with Hyperledger Fabric

func NewFabricClient

func NewFabricClient(path string) (*FabricClient, error)

NewFabricClient creates new client from provided config file.

func NewFabricClientFromConfig

func NewFabricClientFromConfig(config ClientConfig) (*FabricClient, error)

NewFabricClientFromConfig create a new FabricClient from ClientConfig

func (*FabricClient) CreateUpdateChannel

func (c *FabricClient) CreateUpdateChannel(identity Identity, path string, channelId string, orderer string) error

CreateUpdateChannel read channel config generated (usually) from configtxgen and send it to orderer This step is needed before any peer is able to join the channel and before any future updates of the channel.

func (*FabricClient) InstallChainCode

func (c *FabricClient) InstallChainCode(identity Identity, req *InstallRequest, peers []string) ([]*PeerResponse, error)

InstallChainCode install chainCode to one or many peers. Peer must be in the channel where chaincode will be installed.

func (*FabricClient) InstantiateChainCode

func (c *FabricClient) InstantiateChainCode(identity Identity, req *ChainCode, peers []string, orderer string,
	operation string, collectionsConfig []CollectionConfig) (*orderer.BroadcastResponse, error)

InstantiateChainCode run installed chainCode to particular peer in particular channel. Chaincode must be installed using InstallChainCode or CLI interface before this operation. If this is first time running the chaincode operation must be `deploy` If this operation update existing chaincode operation must be `upgrade` collectionsConfig is configuration for private collections in versions >= 1.1. If not provided no private collections will be created. collectionsConfig can be specified when chaincode is upgraded.

func (*FabricClient) Invoke

func (c *FabricClient) Invoke(identity Identity, chainCode ChainCode, peers []string, orderer string) (*InvokeResponse, error)

Invoke execute chainCode for ledger update. Peers that simulate the chainCode must be enough to satisfy the policy. When Invoke returns with success this is not granite that ledger was update. Invoke will return `transactionId`. This ID will be transactionId in events. It is responsibility of SDK user to build logic that handle successful and failed commits. If chaincode call `shim.Error` or simulation fails for other reasons this is considered as simulation failure. In such case Invoke will return the error and transaction will NOT be send to orderer. This transaction will NOT be committed to blockchain.

func (*FabricClient) JoinChannel

func (c *FabricClient) JoinChannel(identity Identity, channelId string, peers []string, orderer string) ([]*PeerResponse, error)

JoinChannel send transaction to one or many Peers to join particular channel. Channel must be created before this operation using `CreateUpdateChannel` or manually using CLI interface. Orderers must be aware of this channel, otherwise operation will fail.

func (*FabricClient) ListenForFilteredBlock

func (c *FabricClient) ListenForFilteredBlock(ctx context.Context, identity Identity, eventPeer, channelId string, response chan<- EventBlockResponse) error

ListenForFilteredBlock listen for events in blockchain. Difference with `ListenForFullBlock` is that event names will be returned but NOT events data. Also full block data will not be available. Other options are same as `ListenForFullBlock`.

func (*FabricClient) ListenForFullBlock

func (c *FabricClient) ListenForFullBlock(ctx context.Context, identity Identity, eventPeer, channelId string, response chan<- EventBlockResponse) error

ListenForFullBlock will listen for events when new block is committed to blockchain and will return block height, list of all transactions in this block, there statuses and events associated with them. Listener is per channel, so user must create a new listener for every channel of interest. This event listener will start listen from newest block, and actual (raw) block data will NOT be returned. If user wants fo start listening from different blocks or want to receive full block bytes he/she must construct the listener manually and provide proper seek and block options. User must provide channel where events will be send and is responsibility for the user to read this channel. To cancel listening provide context with cancellation option and call cancel. User can listen for same events in same channel in multiple peers for redundancy using same `chan<- EventBlockResponse` In this case every peer will send its events, so identical events may appear more than once in channel.

func (*FabricClient) Query

func (c *FabricClient) Query(identity Identity, chainCode ChainCode, peers []string) ([]*QueryResponse, error)

Query execute chainCode to one or many peers and return there responses without sending them to orderer for transaction - ReadOnly operation. Because is expected all peers to be in same state this function allows very easy horizontal scaling by distributing query operations between peers.

func (*FabricClient) QueryChannelInfo

func (c *FabricClient) QueryChannelInfo(identity Identity, channelId string, peers []string) ([]*QueryChannelInfoResponse, error)

QueryChannelInfo get current block height, current hash and prev hash about particular channel in peer/s

func (*FabricClient) QueryChannels

func (c *FabricClient) QueryChannels(identity Identity, peers []string) ([]*QueryChannelsResponse, error)

QueryChannels returns a list of channels that peer/s has joined

func (*FabricClient) QueryInstalledChainCodes

func (c *FabricClient) QueryInstalledChainCodes(identity Identity, peers []string) ([]*ChainCodesResponse, error)

QueryInstalledChainCodes get all chainCodes that are installed but not instantiated in one or many peers

func (*FabricClient) QueryInstantiatedChainCodes

func (c *FabricClient) QueryInstantiatedChainCodes(identity Identity, channelId string, peers []string) ([]*ChainCodesResponse, error)

QueryInstantiatedChainCodes get all chainCodes that are running (instantiated) "inside" particular channel in peer

func (*FabricClient) QueryTransaction

func (c *FabricClient) QueryTransaction(identity Identity, channelId string, txId string, peers []string) ([]*QueryTransactionResponse, error)

QueryTransaction get data for particular transaction. TODO for now it only returns status of the transaction, and not the whole data (payload, endorsement etc)

type Identity

type Identity struct {
	Certificate *x509.Certificate
	PrivateKey  interface{}
	MspId       string
}

Identity is participant public and private key

func LoadCertFromFile

func LoadCertFromFile(pk, sk string) (*Identity, error)

LoadCertFromFile read public key (pk) and private/secret kye (sk) from file system and return new Identity

func UnmarshalIdentity

func UnmarshalIdentity(data string) (*Identity, error)

UnmarshalIdentity unmarshal identity from string

func (*Identity) EnrollmentId

func (i *Identity) EnrollmentId() string

EnrollmentId get enrollment id from certificate

func (*Identity) ToPem

func (i *Identity) ToPem() ([]byte, []byte, error)

EnrollmentId get enrollment id from certificate

type InstallRequest

type InstallRequest struct {
	ChannelId        string
	ChainCodeName    string
	ChainCodeVersion string
	ChainCodeType    ChainCodeType
	Namespace        string
	SrcPath          string
	Libraries        []ChaincodeLibrary
}

InstallRequest holds fields needed to install chaincode

type InvokeResponse

type InvokeResponse struct {
	Status common.Status
	// TxID is transaction id. This id can be used to track transactions and their status
	TxID string
}

InvokeResponse represent result from invoke operation. Please note that this is the result of simulation, not the result of actual block commit.

type Orderer

type Orderer struct {
	Name string
	Uri  string
	Opts []grpc.DialOption
	// contains filtered or unexported fields
}

Orderer expose API's to communicate with orderers.

func NewOrdererFromConfig

func NewOrdererFromConfig(conf OrdererConfig) (*Orderer, error)

NewOrdererFromConfig create new Orderer from config

func (*Orderer) Broadcast

func (o *Orderer) Broadcast(envelope *common.Envelope) (*orderer.BroadcastResponse, error)

Broadcast Broadcast envelope to orderer for execution.

func (*Orderer) Deliver

func (o *Orderer) Deliver(envelope *common.Envelope) (*common.Block, error)

Deliver delivers envelope to orderer. Please note that new connection will be created on every call of Deliver.

type OrdererConfig

type OrdererConfig struct {
	Host    string `yaml:"host"`
	UseTLS  bool   `yaml:"useTLS"`
	TlsPath string `yaml:"tlsPath"`
}

OrdererConfig hold config values for Orderer. ULR is in address:port notation

type Peer

type Peer struct {
	Name  string
	Uri   string
	MspId string
	Opts  []grpc.DialOption
	// contains filtered or unexported fields
}

Peer expose API's to communicate with peer

func NewPeerFromConfig

func NewPeerFromConfig(conf PeerConfig) (*Peer, error)

NewPeerFromConfig creates new peer from provided config

func (*Peer) Endorse

func (p *Peer) Endorse(resp chan *PeerResponse, prop *peer.SignedProposal)

Endorse sends single transaction to single peer.

type PeerConfig

type PeerConfig struct {
	Host    string `yaml:"host"`
	UseTLS  bool   `yaml:"useTLS"`
	TlsPath string `yaml:"tlsPath"`
}

PeerConfig hold config values for Peer. ULR is in address:port notation

type PeerResponse

type PeerResponse struct {
	Response *peer.ProposalResponse
	Err      error
	Name     string
}

PeerResponse is response from peer transaction request

type QueryChannelInfoResponse

type QueryChannelInfoResponse struct {
	PeerName string
	Error    error
	Info     *common.BlockchainInfo
}

QueryChannelInfoResponse hold the response for querying channel info from particular peer

type QueryChannelsResponse

type QueryChannelsResponse struct {
	PeerName string
	Error    error
	Channels []string
}

QueryChannelsResponse holds the result from querying which channels peer is currently joined

type QueryResponse

type QueryResponse struct {
	PeerName string
	Error    error
	Response *peer.ProposalResponse
}

QueryResponse represent result from query operation

type QueryTransactionResponse

type QueryTransactionResponse struct {
	PeerName   string
	Error      error
	StatusCode int32
}

QueryTransactionResponse holds data from `client.QueryTransaction` TODO it is not fully implemented!

type TransactionId

type TransactionId struct {
	Nonce         []byte
	TransactionId string
	Creator       []byte
}

TransactionId represents transaction identifier. TransactionId is the unique transaction number.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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