diff --git a/api/apifabca/mocks/mockfabriccaclient.gen.go b/api/apifabca/mocks/mockfabriccaclient.gen.go index 3d461a08b0..aefdd66411 100644 --- a/api/apifabca/mocks/mockfabriccaclient.gen.go +++ b/api/apifabca/mocks/mockfabriccaclient.gen.go @@ -32,6 +32,18 @@ func (_m *MockFabricCAClient) EXPECT() *MockFabricCAClientMockRecorder { return _m.recorder } +// CAName mocks base method +func (_m *MockFabricCAClient) CAName() string { + ret := _m.ctrl.Call(_m, "CAName") + ret0, _ := ret[0].(string) + return ret0 +} + +// CAName indicates an expected call of CAName +func (_mr *MockFabricCAClientMockRecorder) CAName() *gomock.Call { + return _mr.mock.ctrl.RecordCall(_mr.mock, "CAName") +} + // Enroll mocks base method func (_m *MockFabricCAClient) Enroll(_param0 string, _param1 string) (bccsp.Key, []byte, error) { ret := _m.ctrl.Call(_m, "Enroll", _param0, _param1) @@ -46,18 +58,6 @@ func (_mr *MockFabricCAClientMockRecorder) Enroll(arg0, arg1 interface{}) *gomoc return _mr.mock.ctrl.RecordCall(_mr.mock, "Enroll", arg0, arg1) } -// GetCAName mocks base method -func (_m *MockFabricCAClient) GetCAName() string { - ret := _m.ctrl.Call(_m, "GetCAName") - ret0, _ := ret[0].(string) - return ret0 -} - -// GetCAName indicates an expected call of GetCAName -func (_mr *MockFabricCAClientMockRecorder) GetCAName() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "GetCAName") -} - // Reenroll mocks base method func (_m *MockFabricCAClient) Reenroll(_param0 apifabca.User) (bccsp.Key, []byte, error) { ret := _m.ctrl.Call(_m, "Reenroll", _param0) diff --git a/api/apifabclient/peer.go b/api/apifabclient/peer.go index 41521a164f..82bd361cc8 100644 --- a/api/apifabclient/peer.go +++ b/api/apifabclient/peer.go @@ -45,13 +45,3 @@ type Peer interface { SetRoles(roles []string) URL() string } - -// PeersToTxnProcessors converts a slice of Peers to a slice of TxnProposalProcessors -func PeersToTxnProcessors(peers []Peer) []txn.ProposalProcessor { - tpp := make([]txn.ProposalProcessor, len(peers)) - - for i := range peers { - tpp[i] = peers[i] - } - return tpp -} diff --git a/pkg/config/config.go b/pkg/config/config.go index 7d2336e80a..f609a3c46c 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -32,7 +32,8 @@ var format = logging.MustStringFormatter( const cmdRoot = "fabric_sdk" -type config struct { +// Config represents the configuration for the client +type Config struct { networkConfig *apiconfig.NetworkConfig networkConfigCached bool } @@ -45,7 +46,7 @@ func InitConfig(configFile string) (apiconfig.Config, error) { // InitConfigWithCmdRoot reads in a config file and allows the // environment variable prefixed to be specified -func InitConfigWithCmdRoot(configFile string, cmdRootPrefix string) (apiconfig.Config, error) { +func InitConfigWithCmdRoot(configFile string, cmdRootPrefix string) (*Config, error) { myViper.SetEnvPrefix(cmdRootPrefix) myViper.AutomaticEnv() replacer := strings.NewReplacer(".", "_") @@ -79,11 +80,11 @@ func InitConfigWithCmdRoot(configFile string, cmdRootPrefix string) (apiconfig.C } logging.SetBackend(backendFormatter).SetLevel(logging.Level(logLevel), "fabric_sdk_go") - return &config{}, nil - + return &Config{}, nil } -func (c *config) CAConfig(org string) (*apiconfig.CAConfig, error) { +// CAConfig returns the CA configuration. +func (c *Config) CAConfig(org string) (*apiconfig.CAConfig, error) { config, err := c.NetworkConfig() if err != nil { return nil, err @@ -93,8 +94,8 @@ func (c *config) CAConfig(org string) (*apiconfig.CAConfig, error) { return &caConfig, nil } -//GetCAServerCertFiles Read configuration option for the server certificate files -func (c *config) CAServerCertFiles(org string) ([]string, error) { +// CAServerCertFiles Read configuration option for the server certificate files +func (c *Config) CAServerCertFiles(org string) ([]string, error) { config, err := c.NetworkConfig() if err != nil { return nil, err @@ -109,8 +110,8 @@ func (c *config) CAServerCertFiles(org string) ([]string, error) { return certFileModPath, nil } -//GetCAClientKeyFile Read configuration option for the fabric CA client key file -func (c *config) CAClientKeyFile(org string) (string, error) { +// CAClientKeyFile Read configuration option for the fabric CA client key file +func (c *Config) CAClientKeyFile(org string) (string, error) { config, err := c.NetworkConfig() if err != nil { return "", err @@ -120,8 +121,8 @@ func (c *config) CAClientKeyFile(org string) (string, error) { "$GOPATH", os.Getenv("GOPATH"), -1), nil } -//GetCAClientCertFile Read configuration option for the fabric CA client cert file -func (c *config) CAClientCertFile(org string) (string, error) { +// CAClientCertFile Read configuration option for the fabric CA client cert file +func (c *Config) CAClientCertFile(org string) (string, error) { config, err := c.NetworkConfig() if err != nil { return "", err @@ -132,7 +133,7 @@ func (c *config) CAClientCertFile(org string) (string, error) { } // MspID returns the MSP ID for the requested organization -func (c *config) MspID(org string) (string, error) { +func (c *Config) MspID(org string) (string, error) { config, err := c.NetworkConfig() if err != nil { return "", err @@ -147,11 +148,11 @@ func (c *config) MspID(org string) (string, error) { // FabricClientViper returns the internal viper instance used by the // SDK to read configuration options -func (c *config) FabricClientViper() *viper.Viper { +func (c *Config) FabricClientViper() *viper.Viper { return myViper } -func (c *config) cacheNetworkConfiguration() error { +func (c *Config) cacheNetworkConfiguration() error { err := myViper.UnmarshalKey("client.network", &c.networkConfig) if err == nil { c.networkConfigCached = true @@ -161,8 +162,8 @@ func (c *config) cacheNetworkConfiguration() error { return err } -// GetOrderersConfig returns a list of defined orderers -func (c *config) OrderersConfig() ([]apiconfig.OrdererConfig, error) { +// OrderersConfig returns a list of defined orderers +func (c *Config) OrderersConfig() ([]apiconfig.OrdererConfig, error) { orderers := []apiconfig.OrdererConfig{} config, err := c.NetworkConfig() if err != nil { @@ -179,7 +180,7 @@ func (c *config) OrderersConfig() ([]apiconfig.OrdererConfig, error) { } // RandomOrdererConfig returns a pseudo-random orderer from the network config -func (c *config) RandomOrdererConfig() (*apiconfig.OrdererConfig, error) { +func (c *Config) RandomOrdererConfig() (*apiconfig.OrdererConfig, error) { config, err := c.NetworkConfig() if err != nil { return nil, err @@ -203,7 +204,7 @@ func (c *config) RandomOrdererConfig() (*apiconfig.OrdererConfig, error) { } // OrdererConfig returns the requested orderer -func (c *config) OrdererConfig(name string) (*apiconfig.OrdererConfig, error) { +func (c *Config) OrdererConfig(name string) (*apiconfig.OrdererConfig, error) { config, err := c.NetworkConfig() if err != nil { return nil, err @@ -218,7 +219,7 @@ func (c *config) OrdererConfig(name string) (*apiconfig.OrdererConfig, error) { // PeersConfig Retrieves the fabric peers for the specified org from the // config file provided -func (c *config) PeersConfig(org string) ([]apiconfig.PeerConfig, error) { +func (c *Config) PeersConfig(org string) ([]apiconfig.PeerConfig, error) { config, err := c.NetworkConfig() if err != nil { return nil, err @@ -245,7 +246,7 @@ func (c *config) PeersConfig(org string) ([]apiconfig.PeerConfig, error) { } // NetworkConfig returns the network configuration defined in the config file -func (c *config) NetworkConfig() (*apiconfig.NetworkConfig, error) { +func (c *Config) NetworkConfig() (*apiconfig.NetworkConfig, error) { if c.networkConfigCached { return c.networkConfig, nil } @@ -257,13 +258,13 @@ func (c *config) NetworkConfig() (*apiconfig.NetworkConfig, error) { } // IsTLSEnabled is TLS enabled? -func (c *config) IsTLSEnabled() bool { +func (c *Config) IsTLSEnabled() bool { return myViper.GetBool("client.tls.enabled") } // TLSCACertPool ... // TODO: Should be related to configuration. -func (c *config) TLSCACertPool(tlsCertificate string) (*x509.CertPool, error) { +func (c *Config) TLSCACertPool(tlsCertificate string) (*x509.CertPool, error) { certPool := x509.NewCertPool() if tlsCertificate != "" { rawData, err := ioutil.ReadFile(tlsCertificate) @@ -283,7 +284,7 @@ func (c *config) TLSCACertPool(tlsCertificate string) (*x509.CertPool, error) { } // TLSCACertPoolFromRoots ... -func (c *config) TLSCACertPoolFromRoots(ordererRootCAs [][]byte) (*x509.CertPool, error) { +func (c *Config) TLSCACertPoolFromRoots(ordererRootCAs [][]byte) (*x509.CertPool, error) { certPool := x509.NewCertPool() for _, root := range ordererRootCAs { @@ -299,43 +300,43 @@ func (c *config) TLSCACertPoolFromRoots(ordererRootCAs [][]byte) (*x509.CertPool } // IsSecurityEnabled ... -func (c *config) IsSecurityEnabled() bool { +func (c *Config) IsSecurityEnabled() bool { return myViper.GetBool("client.security.enabled") } // TcertBatchSize ... -func (c *config) TcertBatchSize() int { +func (c *Config) TcertBatchSize() int { return myViper.GetInt("client.tcert.batch.size") } // SecurityAlgorithm ... -func (c *config) SecurityAlgorithm() string { +func (c *Config) SecurityAlgorithm() string { return myViper.GetString("client.security.hashAlgorithm") } // SecurityLevel ... -func (c *config) SecurityLevel() int { +func (c *Config) SecurityLevel() int { return myViper.GetInt("client.security.level") } // KeyStorePath returns the keystore path used by BCCSP -func (c *config) KeyStorePath() string { +func (c *Config) KeyStorePath() string { keystorePath := strings.Replace(myViper.GetString("client.keystore.path"), "$GOPATH", os.Getenv("GOPATH"), -1) return path.Join(keystorePath, "keystore") } -// CAKeystorePath returns the same path as KeyStorePath() without the +// CAKeyStorePath returns the same path as KeyStorePath() without the // 'keystore' directory added. This is done because the fabric-ca-client // adds this to the path -func (c *config) CAKeyStorePath() string { +func (c *Config) CAKeyStorePath() string { return strings.Replace(myViper.GetString("client.keystore.path"), "$GOPATH", os.Getenv("GOPATH"), -1) } // CryptoConfigPath ... -func (c *config) CryptoConfigPath() string { +func (c *Config) CryptoConfigPath() string { return strings.Replace(myViper.GetString("client.cryptoconfig.path"), "$GOPATH", os.Getenv("GOPATH"), -1) } @@ -356,7 +357,7 @@ func loadCAKey(rawData []byte) (*x509.Certificate, error) { } // CSPConfig ... -func (c *config) CSPConfig() *bccspFactory.FactoryOpts { +func (c *Config) CSPConfig() *bccspFactory.FactoryOpts { return &bccspFactory.FactoryOpts{ ProviderName: "SW", SwOpts: &bccspFactory.SwOpts{ diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index b4f226c9ca..1dbe8e905c 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -445,3 +445,13 @@ func crossCheckWithViperConfig(expected string, actual string, message string, t t.Fatalf(message) } } + +func TestInterfaces(t *testing.T) { + var apiConfig api.Config + var config Config + + apiConfig = &config + if apiConfig == nil { + t.Fatalf("this shouldn't happen.") + } +} diff --git a/pkg/fabric-ca-client/fabricca.go b/pkg/fabric-ca-client/fabricca.go index 12f6234922..d5c92d2869 100644 --- a/pkg/fabric-ca-client/fabricca.go +++ b/pkg/fabric-ca-client/fabricca.go @@ -20,7 +20,8 @@ import ( var logger = logging.MustGetLogger("fabric_sdk_go") -type fabricCA struct { +// FabricCA represents a client to Fabric CA. +type FabricCA struct { fabricCAClient *fabric_ca.Client } @@ -29,8 +30,7 @@ type fabricCA struct { // @param {string} organization for this CA // @returns {api.FabricCAClient} FabricCAClient implementation // @returns {error} error, if any -func NewFabricCAClient(config config.Config, org string) (sdkApi.FabricCAClient, - error) { +func NewFabricCAClient(config config.Config, org string) (*FabricCA, error) { if org == "" || config == nil { return nil, fmt.Errorf("Organization and config are required to load CA config") } @@ -71,7 +71,7 @@ func NewFabricCAClient(config config.Config, org string) (sdkApi.FabricCAClient, c.Config.MSPDir = config.CAKeyStorePath() c.Config.CSP = config.CSPConfig() - fabricCAClient := &fabricCA{fabricCAClient: c} + fabricCAClient := FabricCA{fabricCAClient: c} logger.Infof("Constructed fabricCAClient instance: %v", fabricCAClient) err = c.Init() @@ -79,22 +79,19 @@ func NewFabricCAClient(config config.Config, org string) (sdkApi.FabricCAClient, return nil, fmt.Errorf("New fabricCAClient failed: %s", err) } - return fabricCAClient, nil + return &fabricCAClient, nil } -func (fabricCAServices *fabricCA) CAName() string { +// CAName returns the CA name. +func (fabricCAServices *FabricCA) CAName() string { return fabricCAServices.fabricCAClient.Config.CAName } -// Enroll ... -/** - * Enroll a registered user in order to receive a signed X509 certificate - * @param {string} enrollmentID The registered ID to use for enrollment - * @param {string} enrollmentSecret The secret associated with the enrollment ID - * @returns {[]byte} X509 certificate - * @returns {[]byte} private key - */ -func (fabricCAServices *fabricCA) Enroll(enrollmentID string, enrollmentSecret string) (bccsp.Key, []byte, error) { +// Enroll a registered user in order to receive a signed X509 certificate. +// enrollmentID The registered ID to use for enrollment +// enrollmentSecret The secret associated with the enrollment ID +// Returns X509 certificate +func (fabricCAServices *FabricCA) Enroll(enrollmentID string, enrollmentSecret string) (bccsp.Key, []byte, error) { if enrollmentID == "" { return nil, nil, fmt.Errorf("enrollmentID is empty") } @@ -113,13 +110,9 @@ func (fabricCAServices *fabricCA) Enroll(enrollmentID string, enrollmentSecret s return enrollmentResponse.Identity.GetECert().Key(), enrollmentResponse.Identity.GetECert().Cert(), nil } -/** - * ReEnroll an enrolled user in order to receive a signed X509 certificate - * @param {user} User to be reenrolled - * @returns {[]byte} X509 certificate - * @returns {[]byte} private key - */ -func (fabricCAServices *fabricCA) Reenroll(user sdkApi.User) (bccsp.Key, []byte, error) { +// Reenroll an enrolled user in order to receive a signed X509 certificate +// Returns X509 certificate +func (fabricCAServices *FabricCA) Reenroll(user sdkApi.User) (bccsp.Key, []byte, error) { if user == nil { return nil, nil, fmt.Errorf("User does not exist") } @@ -145,11 +138,10 @@ func (fabricCAServices *fabricCA) Reenroll(user sdkApi.User) (bccsp.Key, []byte, } // Register a User with the Fabric CA -// @param {User} registrar The User that is initiating the registration -// @param {RegistrationRequest} request Registration Request -// @returns {string} Enrolment Secret -// @returns {error} Error -func (fabricCAServices *fabricCA) Register(registrar sdkApi.User, +// registrar: The User that is initiating the registration +// request: Registration Request +// Returns Enrolment Secret +func (fabricCAServices *FabricCA) Register(registrar sdkApi.User, request *sdkApi.RegistrationRequest) (string, error) { // Validate registration request if request == nil { @@ -184,10 +176,9 @@ func (fabricCAServices *fabricCA) Register(registrar sdkApi.User, } // Revoke a User with the Fabric CA -// @param {User} registrar The User that is initiating the revocation -// @param {RevocationRequest} request Revocation Request -// @returns {error} Error -func (fabricCAServices *fabricCA) Revoke(registrar sdkApi.User, +// registrar: The User that is initiating the revocation +// request: Revocation Request +func (fabricCAServices *FabricCA) Revoke(registrar sdkApi.User, request *sdkApi.RevocationRequest) error { // Validate revocation request if request == nil { @@ -209,7 +200,7 @@ func (fabricCAServices *fabricCA) Revoke(registrar sdkApi.User, } // createSigningIdentity creates an identity to sign Fabric CA requests with -func (fabricCAServices *fabricCA) createSigningIdentity(user sdkApi. +func (fabricCAServices *FabricCA) createSigningIdentity(user sdkApi. User) (*fabric_ca.Identity, error) { // Validate user if user == nil { diff --git a/pkg/fabric-ca-client/fabricca_test.go b/pkg/fabric-ca-client/fabricca_test.go index e8c21e200b..21b465dedf 100644 --- a/pkg/fabric-ca-client/fabricca_test.go +++ b/pkg/fabric-ca-client/fabricca_test.go @@ -311,3 +311,13 @@ func readCert(t *testing.T) []byte { } return cert } + +func TestInterfaces(t *testing.T) { + var apiCA ca.FabricCAClient + var ca FabricCA + + apiCA = &ca + if apiCA == nil { + t.Fatalf("this shouldn't happen.") + } +} diff --git a/pkg/fabric-ca-client/mocks/mockconfig.go b/pkg/fabric-ca-client/mocks/mockconfig.go index 4cb9c57b2b..04cc43f57e 100644 --- a/pkg/fabric-ca-client/mocks/mockconfig.go +++ b/pkg/fabric-ca-client/mocks/mockconfig.go @@ -114,12 +114,12 @@ func (c *MockConfig) MspID(org string) (string, error) { // KeyStorePath ... func (c *MockConfig) KeyStorePath() string { - return "" + return "/tmp/msp" } -// CAKeyStorePath not implemented +// CAKeyStorePath ... func (c *MockConfig) CAKeyStorePath() string { - return "" + return "/tmp/msp" } // CryptoConfigPath ... diff --git a/pkg/fabric-client/client.go b/pkg/fabric-client/client.go index 662e0a8ee6..2d261e1646 100644 --- a/pkg/fabric-client/client.go +++ b/pkg/fabric-client/client.go @@ -20,6 +20,7 @@ import ( fc "github.com/hyperledger/fabric-sdk-go/pkg/fabric-client/internal" "github.com/hyperledger/fabric-sdk-go/pkg/fabric-client/msp" packager "github.com/hyperledger/fabric-sdk-go/pkg/fabric-client/packager" + peer "github.com/hyperledger/fabric-sdk-go/pkg/fabric-client/peer" "github.com/op/go-logging" @@ -33,7 +34,8 @@ import ( var logger = logging.MustGetLogger("fabric_sdk_go") -type client struct { +// Client enables access to a Fabric network. +type Client struct { channels map[string]fab.Channel cryptoSuite bccsp.BCCSP stateStore fab.KeyValueStore @@ -41,26 +43,15 @@ type client struct { config config.Config } -// NewClient ... -/* - * Returns a Client instance - */ -func NewClient(config config.Config) fab.FabricClient { +// NewClient returns a Client instance. +func NewClient(config config.Config) *Client { channels := make(map[string]fab.Channel) - c := &client{channels: channels, cryptoSuite: nil, stateStore: nil, userContext: nil, config: config} - return c + c := Client{channels: channels, cryptoSuite: nil, stateStore: nil, userContext: nil, config: config} + return &c } -// NewChannel ... -/* - * Returns a channel instance with the given name. This represents a channel and its associated ledger - * (as explained above), and this call returns an empty object. To initialize the channel in the blockchain network, - * a list of participating endorsers and orderer peers must be configured first on the returned object. - * @param {string} name The name of the channel. Recommend using namespaces to avoid collision. - * @returns {Channel} The uninitialized channel instance. - * @returns {Error} if the channel by that name already exists in the application's state store - */ -func (c *client) NewChannel(name string) (fab.Channel, error) { +// NewChannel returns a channel instance with the given name. +func (c *Client) NewChannel(name string) (fab.Channel, error) { if _, ok := c.channels[name]; ok { return nil, fmt.Errorf("Channel %s already exists", name) } @@ -73,7 +64,7 @@ func (c *client) NewChannel(name string) (fab.Channel, error) { } // GetConfig ... -func (c *client) GetConfig() config.Config { +func (c *Client) GetConfig() config.Config { return c.config } @@ -87,7 +78,7 @@ func (c *client) GetConfig() config.Config { * @param {string} name The name of the channel. * @returns {Channel} The channel instance */ -func (c *client) GetChannel(name string) fab.Channel { +func (c *Client) GetChannel(name string) fab.Channel { return c.channels[name] } @@ -100,7 +91,7 @@ func (c *client) GetChannel(name string) fab.Channel { * @returns {Channel} The channel instance for the name or error if the target Peer(s) does not know * anything about the channel. */ -func (c *client) QueryChannelInfo(name string, peers []fab.Peer) (fab.Channel, error) { +func (c *Client) QueryChannelInfo(name string, peers []fab.Peer) (fab.Channel, error) { return nil, fmt.Errorf("Not implemented yet") } @@ -111,7 +102,7 @@ func (c *client) QueryChannelInfo(name string, peers []fab.Peer) (fab.Channel, e * so that multiple app instances can share app state via the database (note that this doesn’t necessarily make the app stateful). * This API makes this pluggable so that different store implementations can be selected by the application. */ -func (c *client) SetStateStore(stateStore fab.KeyValueStore) { +func (c *Client) SetStateStore(stateStore fab.KeyValueStore) { c.stateStore = stateStore } @@ -119,7 +110,7 @@ func (c *client) SetStateStore(stateStore fab.KeyValueStore) { /* * A convenience method for obtaining the state store object in use for this client. */ -func (c *client) GetStateStore() fab.KeyValueStore { +func (c *Client) GetStateStore() fab.KeyValueStore { return c.stateStore } @@ -127,7 +118,7 @@ func (c *client) GetStateStore() fab.KeyValueStore { /* * A convenience method for obtaining the state store object in use for this client. */ -func (c *client) SetCryptoSuite(cryptoSuite bccsp.BCCSP) { +func (c *Client) SetCryptoSuite(cryptoSuite bccsp.BCCSP) { c.cryptoSuite = cryptoSuite } @@ -135,7 +126,7 @@ func (c *client) SetCryptoSuite(cryptoSuite bccsp.BCCSP) { /* * A convenience method for obtaining the CryptoSuite object in use for this client. */ -func (c *client) GetCryptoSuite() bccsp.BCCSP { +func (c *Client) GetCryptoSuite() bccsp.BCCSP { return c.cryptoSuite } @@ -147,7 +138,7 @@ func (c *client) GetCryptoSuite() bccsp.BCCSP { * this cache will not be established and the application is responsible for setting the user context again when the application * crashed and is recovered. */ -func (c *client) SaveUserToStateStore(user fab.User, skipPersistence bool) error { +func (c *Client) SaveUserToStateStore(user fab.User, skipPersistence bool) error { if user == nil { return fmt.Errorf("user is nil") } @@ -185,7 +176,7 @@ func (c *client) SaveUserToStateStore(user fab.User, skipPersistence bool) error * @returns {Promise} A Promise for a {User} object upon successful restore, or if the user by the name * does not exist in the state store, returns null without rejecting the promise */ -func (c *client) LoadUserFromStateStore(name string) (fab.User, error) { +func (c *Client) LoadUserFromStateStore(name string) (fab.User, error) { if c.userContext != nil { return c.userContext, nil } @@ -229,7 +220,7 @@ func (c *client) LoadUserFromStateStore(name string) (fab.User, error) { * @param {byte[]} The bytes of the ConfigEnvelope protopuf * @returns {byte[]} The bytes of the ConfigUpdate protobuf */ -func (c *client) ExtractChannelConfig(configEnvelope []byte) ([]byte, error) { +func (c *Client) ExtractChannelConfig(configEnvelope []byte) ([]byte, error) { logger.Debug("extractConfigUpdate - start") envelope := &common.Envelope{} @@ -259,7 +250,7 @@ func (c *client) ExtractChannelConfig(configEnvelope []byte) ([]byte, error) { * @param {byte[]} config - The Configuration Update in byte form * @return {ConfigSignature} - The signature of the current user on the config bytes */ -func (c *client) SignChannelConfig(config []byte) (*common.ConfigSignature, error) { +func (c *Client) SignChannelConfig(config []byte) (*common.ConfigSignature, error) { logger.Debug("SignChannelConfig - start") if config == nil { @@ -326,7 +317,7 @@ func (c *client) SignChannelConfig(config []byte) (*common.ConfigSignature, erro * required by the channel create policy when using the `config` parameter. * @returns {Result} Result Object with status on the create process. */ -func (c *client) CreateChannel(request *fab.CreateChannelRequest) error { +func (c *Client) CreateChannel(request *fab.CreateChannelRequest) error { haveEnvelope := false if request != nil && request.Envelope != nil { logger.Debug("createChannel - have envelope") @@ -335,7 +326,8 @@ func (c *client) CreateChannel(request *fab.CreateChannelRequest) error { return c.CreateOrUpdateChannel(request, haveEnvelope) } -func (c *client) CreateOrUpdateChannel(request *fab.CreateChannelRequest, haveEnvelope bool) error { +// CreateOrUpdateChannel creates a new channel or updates an existing channel. +func (c *Client) CreateOrUpdateChannel(request *fab.CreateChannelRequest, haveEnvelope bool) error { // Validate request if request == nil { return fmt.Errorf("Missing all required input request parameters for initialize channel") @@ -429,14 +421,8 @@ func (c *client) CreateOrUpdateChannel(request *fab.CreateChannelRequest, haveEn return nil } -//QueryChannels -/** - * Queries the names of all the channels that a - * peer has joined. - * @param {Peer} peer - * @returns {object} ChannelQueryResponse proto - */ -func (c *client) QueryChannels(peer fab.Peer) (*pb.ChannelQueryResponse, error) { +// QueryChannels queries the names of all the channels that a peer has joined. +func (c *Client) QueryChannels(peer fab.Peer) (*pb.ChannelQueryResponse, error) { if peer == nil { return nil, fmt.Errorf("QueryChannels requires peer") @@ -455,14 +441,9 @@ func (c *client) QueryChannels(peer fab.Peer) (*pb.ChannelQueryResponse, error) return response, nil } -//QueryInstalledChaincodes -/** - * Queries the installed chaincodes on a peer - * Returning the details of all chaincodes installed on a peer. - * @param {Peer} peer - * @returns {object} ChaincodeQueryResponse proto - */ -func (c *client) QueryInstalledChaincodes(peer fab.Peer) (*pb.ChaincodeQueryResponse, error) { +// QueryInstalledChaincodes queries the installed chaincodes on a peer. +// Returns the details of all chaincodes installed on a peer. +func (c *Client) QueryInstalledChaincodes(peer fab.Peer) (*pb.ChaincodeQueryResponse, error) { if peer == nil { return nil, fmt.Errorf("To query installed chaincdes you need to pass peer") @@ -480,15 +461,8 @@ func (c *client) QueryInstalledChaincodes(peer fab.Peer) (*pb.ChaincodeQueryResp return response, nil } -// InstallChaincode -/** -* Sends an install proposal to one or more endorsing peers. -* @param {string} chaincodeName: required - The name of the chaincode. -* @param {[]string} chaincodePath: required - string of the path to the location of the source code of the chaincode -* @param {[]string} chaincodeVersion: required - string of the version of the chaincode -* @param {[]string} chaincodeVersion: optional - Array of byte the chaincodePackage - */ -func (c *client) InstallChaincode(chaincodeName string, chaincodePath string, chaincodeVersion string, +// InstallChaincode sends an install proposal to one or more endorsing peers. +func (c *Client) InstallChaincode(chaincodeName string, chaincodePath string, chaincodeVersion string, chaincodePackage []byte, targets []fab.Peer) ([]*apitxn.TransactionProposalResponse, string, error) { if chaincodeName == "" { @@ -543,13 +517,13 @@ func (c *client) InstallChaincode(chaincodeName string, chaincodePath string, ch SignedProposal: signedProposal, Proposal: proposal, TransactionID: txID, - }, 0, fab.PeersToTxnProcessors(targets)) + }, 0, peer.PeersToTxnProcessors(targets)) return transactionProposalResponse, txID, err } // GetIdentity returns client's serialized identity -func (c *client) GetIdentity() ([]byte, error) { +func (c *Client) GetIdentity() ([]byte, error) { if c.userContext == nil { return nil, fmt.Errorf("User is nil") @@ -564,11 +538,11 @@ func (c *client) GetIdentity() ([]byte, error) { } // GetUserContext ... -func (c *client) GetUserContext() fab.User { +func (c *Client) GetUserContext() fab.User { return c.userContext } // SetUserContext ... -func (c *client) SetUserContext(user fab.User) { +func (c *Client) SetUserContext(user fab.User) { c.userContext = user } diff --git a/pkg/fabric-client/client_test.go b/pkg/fabric-client/client_test.go index afe55e6dde..3eb81292ee 100644 --- a/pkg/fabric-client/client_test.go +++ b/pkg/fabric-client/client_test.go @@ -195,3 +195,13 @@ func TestQueryMethodsOnClient(t *testing.T) { } } + +func TestInterfaces(t *testing.T) { + var apiClient fab.FabricClient + var client Client + + apiClient = &client + if apiClient == nil { + t.Fatalf("this shouldn't happen.") + } +} diff --git a/pkg/fabric-client/events/eventhub.go b/pkg/fabric-client/events/eventhub.go index 9c638ed26e..d45af8f986 100644 --- a/pkg/fabric-client/events/eventhub.go +++ b/pkg/fabric-client/events/eventhub.go @@ -29,7 +29,8 @@ import ( var logger = logging.MustGetLogger("fabric_sdk_go") -type eventHub struct { +// EventHub allows a client to listen to event at a peer. +type EventHub struct { // Protects chaincodeRegistrants, blockRegistrants and txRegistrants mtx sync.RWMutex // Map of clients registered for chaincode events @@ -69,7 +70,7 @@ func (ccf *consumerClientFactory) newEventsClient(client fab.FabricClient, peerA } // NewEventHub ... -func NewEventHub(client fab.FabricClient) (fab.EventHub, error) { +func NewEventHub(client fab.FabricClient) (*EventHub, error) { if client == nil { return nil, fmt.Errorf("Client is nil") @@ -77,7 +78,7 @@ func NewEventHub(client fab.FabricClient) (fab.EventHub, error) { chaincodeRegistrants := make(map[string][]*fab.ChainCodeCBE) txRegistrants := make(map[string]func(string, pb.TxValidationCode, error)) - eventHub := &eventHub{ + eventHub := EventHub{ chaincodeRegistrants: chaincodeRegistrants, blockRegistrants: nil, txRegistrants: txRegistrants, @@ -89,11 +90,11 @@ func NewEventHub(client fab.FabricClient) (fab.EventHub, error) { // register default transaction callback eventHub.RegisterBlockEvent(eventHub.txCallback) - return eventHub, nil + return &eventHub, nil } // SetInterests clears all interests and sets the interests for BLOCK type of events. -func (eventHub *eventHub) SetInterests(block bool) { +func (eventHub *EventHub) SetInterests(block bool) { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -107,7 +108,7 @@ func (eventHub *eventHub) SetInterests(block bool) { } // Disconnect disconnects from peer event source -func (eventHub *eventHub) Disconnect() { +func (eventHub *EventHub) Disconnect() { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -123,7 +124,7 @@ func (eventHub *eventHub) Disconnect() { } // RegisterBlockEvent - register callback function for block events -func (eventHub *eventHub) RegisterBlockEvent(callback func(*common.Block)) { +func (eventHub *EventHub) RegisterBlockEvent(callback func(*common.Block)) { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -136,7 +137,7 @@ func (eventHub *eventHub) RegisterBlockEvent(callback func(*common.Block)) { } // UnregisterBlockEvent unregister callback for block event -func (eventHub *eventHub) UnregisterBlockEvent(callback func(*common.Block)) { +func (eventHub *EventHub) UnregisterBlockEvent(callback func(*common.Block)) { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -163,7 +164,7 @@ func (eventHub *eventHub) UnregisterBlockEvent(callback func(*common.Block)) { } // addChaincodeInterest adds interest for specific CHAINCODE events. -func (eventHub *eventHub) addChaincodeInterest(ChaincodeID string, EventName string) { +func (eventHub *EventHub) addChaincodeInterest(ChaincodeID string, EventName string) { ccInterest := &pb.Interest{ EventType: pb.EventType_CHAINCODE, RegInfo: &pb.Interest_ChaincodeRegInfo{ @@ -183,7 +184,7 @@ func (eventHub *eventHub) addChaincodeInterest(ChaincodeID string, EventName str } // removeChaincodeInterest remove interest for specific CHAINCODE event -func (eventHub *eventHub) removeChaincodeInterest(ChaincodeID string, EventName string) { +func (eventHub *EventHub) removeChaincodeInterest(ChaincodeID string, EventName string) { ccInterest := &pb.Interest{ EventType: pb.EventType_CHAINCODE, RegInfo: &pb.Interest_ChaincodeRegInfo{ @@ -206,37 +207,25 @@ func (eventHub *eventHub) removeChaincodeInterest(ChaincodeID string, EventName } -// SetPeerAddr ... -/** - * Set peer url for event source

- * Note: Only use this if creating your own EventHub. The chain - * creates a default eventHub that most Node clients can - * use (see eventHubConnect, eventHubDisconnect and getEventHub). - * @param {string} peeraddr peer url - * @param {string} peerTLSCertificate peer tls certificate - * @param {string} peerTLSServerHostOverride tls serverhostoverride - */ -func (eventHub *eventHub) SetPeerAddr(peerURL string, peerTLSCertificate string, peerTLSServerHostOverride string) { +// SetPeerAddr set peer url for event source +// peeraddr peer url +// peerTLSCertificate peer tls certificate +// peerTLSServerHostOverride tls serverhostoverride +func (eventHub *EventHub) SetPeerAddr(peerURL string, peerTLSCertificate string, peerTLSServerHostOverride string) { eventHub.peerAddr = peerURL eventHub.peerTLSCertificate = peerTLSCertificate eventHub.peerTLSServerHostOverride = peerTLSServerHostOverride } -// Isconnected ... -/** - * Get connected state of eventhub - * @returns true if connected to event source, false otherwise - */ -func (eventHub *eventHub) IsConnected() bool { +// IsConnected gets connected state of eventhub +// Returns true if connected to event source, false otherwise +func (eventHub *EventHub) IsConnected() bool { return eventHub.connected } -// Connect ... -/** - * Establishes connection with peer event source

- */ -func (eventHub *eventHub) Connect() error { +// Connect establishes connection with peer event source +func (eventHub *EventHub) Connect() error { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -270,12 +259,12 @@ func (eventHub *eventHub) Connect() error { } //GetInterestedEvents implements consumer.EventAdapter interface for registering interested events -func (eventHub *eventHub) GetInterestedEvents() ([]*pb.Interest, error) { +func (eventHub *EventHub) GetInterestedEvents() ([]*pb.Interest, error) { return eventHub.interestedEvents, nil } //Recv implements consumer.EventAdapter interface for receiving events -func (eventHub *eventHub) Recv(msg *pb.Event) (bool, error) { +func (eventHub *EventHub) Recv(msg *pb.Event) (bool, error) { switch msg.Event.(type) { case *pb.Event_Block: blockEvent := msg.Event.(*pb.Event_Block) @@ -306,7 +295,7 @@ func (eventHub *eventHub) Recv(msg *pb.Event) (bool, error) { } // Disconnected implements consumer.EventAdapter interface for receiving events -func (eventHub *eventHub) Disconnected(err error) { +func (eventHub *EventHub) Disconnected(err error) { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -318,18 +307,14 @@ func (eventHub *eventHub) Disconnected(err error) { eventHub.connected = false } -// RegisterChaincodeEvent ... -/** - * Register a callback function to receive chaincode events. - * @param {string} ccid string chaincode id - * @param {string} eventname string The regex string used to filter events - * @param {function} callback Function Callback function for filter matches - * that takes a single parameter which is a json object representation - * of type "message ChaincodeEvent" - * @returns {object} ChainCodeCBE object that should be treated as an opaque - * handle used to unregister (see unregisterChaincodeEvent) - */ -func (eventHub *eventHub) RegisterChaincodeEvent(ccid string, eventname string, callback func(*fab.ChaincodeEvent)) *fab.ChainCodeCBE { +// RegisterChaincodeEvent registers a callback function to receive chaincode events. +// ccid: chaincode id +// eventname: The regex string used to filter events +// callback: Callback function for filter matches that takes a single parameter which is a json object representation +// of type "message ChaincodeEvent" +// Returns ChainCodeCBE object that should be treated as an opaque +// handle used to unregister (see unregisterChaincodeEvent) +func (eventHub *EventHub) RegisterChaincodeEvent(ccid string, eventname string, callback func(*fab.ChaincodeEvent)) *fab.ChainCodeCBE { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -348,13 +333,9 @@ func (eventHub *eventHub) RegisterChaincodeEvent(ccid string, eventname string, return &cbe } -// UnregisterChaincodeEvent ... -/** - * Unregister chaincode event registration - * @param {object} ChainCodeCBE handle returned from call to - * registerChaincodeEvent. - */ -func (eventHub *eventHub) UnregisterChaincodeEvent(cbe *fab.ChainCodeCBE) { +// UnregisterChaincodeEvent unregisters chaincode event registration +// ChainCodeCBE: handle returned from call to registerChaincodeEvent. +func (eventHub *EventHub) UnregisterChaincodeEvent(cbe *fab.ChainCodeCBE) { eventHub.mtx.Lock() defer eventHub.mtx.Unlock() @@ -379,17 +360,11 @@ func (eventHub *eventHub) UnregisterChaincodeEvent(cbe *fab.ChainCodeCBE) { } } -// RegisterTxEvent ... -/** - * Register a callback function to receive transactional events.

- * Note: transactional event registration is primarily used by - * the sdk to track deploy and invoke completion events. Nodejs - * clients generally should not need to call directly. - * @param {string} txid string transaction id - * @param {function} callback Function that takes a single parameter which - * is a json object representation of type "message Transaction" - */ -func (eventHub *eventHub) RegisterTxEvent(txID string, callback func(string, pb.TxValidationCode, error)) { +// RegisterTxEvent registers a callback function to receive transactional events. +// txid: transaction id +// callback: Function that takes a single parameter which +// is a json object representation of type "message Transaction" +func (eventHub *EventHub) RegisterTxEvent(txID string, callback func(string, pb.TxValidationCode, error)) { logger.Debugf("reg txid %s\n", txID) eventHub.mtx.Lock() @@ -397,12 +372,9 @@ func (eventHub *eventHub) RegisterTxEvent(txID string, callback func(string, pb. eventHub.mtx.Unlock() } -// UnregisterTxEvent ... -/** - * Unregister transactional event registration. - * @param txid string transaction id - */ -func (eventHub *eventHub) UnregisterTxEvent(txID string) { +// UnregisterTxEvent unregister transactional event registration. +// txid: transaction id +func (eventHub *EventHub) UnregisterTxEvent(txID string) { eventHub.mtx.Lock() delete(eventHub.txRegistrants, txID) eventHub.mtx.Unlock() @@ -413,7 +385,7 @@ func (eventHub *eventHub) UnregisterTxEvent(txID string) { * @param {object} block json object representing block of tx * from the fabric */ -func (eventHub *eventHub) txCallback(block *common.Block) { +func (eventHub *EventHub) txCallback(block *common.Block) { logger.Debugf("txCallback block=%v\n", block) txFilter := util.TxValidationFlags(block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER]) @@ -452,7 +424,7 @@ func (eventHub *eventHub) txCallback(block *common.Block) { } } -func (eventHub *eventHub) getBlockRegistrants() []func(*common.Block) { +func (eventHub *EventHub) getBlockRegistrants() []func(*common.Block) { eventHub.mtx.RLock() defer eventHub.mtx.RUnlock() @@ -464,7 +436,7 @@ func (eventHub *eventHub) getBlockRegistrants() []func(*common.Block) { return clone } -func (eventHub *eventHub) getChaincodeRegistrants(chaincodeID string) []*fab.ChainCodeCBE { +func (eventHub *EventHub) getChaincodeRegistrants(chaincodeID string) []*fab.ChainCodeCBE { eventHub.mtx.RLock() defer eventHub.mtx.RUnlock() @@ -481,7 +453,7 @@ func (eventHub *eventHub) getChaincodeRegistrants(chaincodeID string) []*fab.Cha return clone } -func (eventHub *eventHub) getTXRegistrant(txID string) func(string, pb.TxValidationCode, error) { +func (eventHub *EventHub) getTXRegistrant(txID string) func(string, pb.TxValidationCode, error) { eventHub.mtx.RLock() defer eventHub.mtx.RUnlock() return eventHub.txRegistrants[txID] @@ -541,7 +513,7 @@ func getChainCodeEvent(tdata []byte) (event *pb.ChaincodeEvent, channelID string } // Utility function to fire callbacks for chaincode registrants -func (eventHub *eventHub) notifyChaincodeRegistrants(channelID string, ccEvent *pb.ChaincodeEvent, patternMatch bool) { +func (eventHub *EventHub) notifyChaincodeRegistrants(channelID string, ccEvent *pb.ChaincodeEvent, patternMatch bool) { cbeArray := eventHub.getChaincodeRegistrants(ccEvent.ChaincodeId) if len(cbeArray) <= 0 { diff --git a/pkg/fabric-client/events/eventhub_test.go b/pkg/fabric-client/events/eventhub_test.go index 10c0ccc54f..5f5f586726 100644 --- a/pkg/fabric-client/events/eventhub_test.go +++ b/pkg/fabric-client/events/eventhub_test.go @@ -423,7 +423,7 @@ func TestDiconnectedWhenDisconnected(t *testing.T) { } -func verifyDisconnectedEventHub(eventHub *eventHub, t *testing.T) { +func verifyDisconnectedEventHub(eventHub *EventHub, t *testing.T) { if eventHub.connected == true { t.Fatalf("EventHub is not disconnected after Disconnect call") } @@ -498,3 +498,13 @@ func TestConnectWithInterestsFalseAndGetInterests(t *testing.T) { } } + +func TestInterfaces(t *testing.T) { + var apiEventHub fab.EventHub + var eventHub EventHub + + apiEventHub = &eventHub + if apiEventHub == nil { + t.Fatalf("this shouldn't happen.") + } +} diff --git a/pkg/fabric-client/events/eventmocks.go b/pkg/fabric-client/events/eventmocks.go index fb0a04fd9a..918bdee66f 100644 --- a/pkg/fabric-client/events/eventmocks.go +++ b/pkg/fabric-client/events/eventmocks.go @@ -110,21 +110,16 @@ func (mec *mockEventClient) Stop() error { return nil } -func createMockedEventHub(t *testing.T) (*eventHub, *mockEventClientFactory) { +func createMockedEventHub(t *testing.T) (*EventHub, *mockEventClientFactory) { // Initialize bccsp factories before calling get client err := bccspFactory.InitFactories(mocks.NewMockConfig().CSPConfig()) if err != nil { t.Fatalf("Failed getting ephemeral software-based BCCSP [%s]", err) } - eh, err := NewEventHub(client.NewClient(mocks.NewMockConfig())) + eventHub, err := NewEventHub(client.NewClient(mocks.NewMockConfig())) if err != nil { t.Fatalf("Error creating event hub: %v", err) } - eventHub, ok := eh.(*eventHub) - if !ok { - t.Fatalf("Could not create eventHub") - return nil, nil - } var clientFactory mockEventClientFactory eventHub.eventsClientFactory = &clientFactory diff --git a/pkg/fabric-client/orderer/orderer.go b/pkg/fabric-client/orderer/orderer.go index 6ce24d13cc..a89c6fcbb2 100644 --- a/pkg/fabric-client/orderer/orderer.go +++ b/pkg/fabric-client/orderer/orderer.go @@ -24,13 +24,14 @@ import ( var logger = logging.MustGetLogger("fabric_sdk_go") -type orderer struct { +// Orderer allows a client to broadcast a transaction. +type Orderer struct { url string grpcDialOption []grpc.DialOption } // CreateNewOrdererWithRootCAs Returns a new Orderer instance using the passed in orderer root CAs -func CreateNewOrdererWithRootCAs(url string, ordererRootCAs [][]byte, serverHostOverride string, config config.Config) (fab.Orderer, error) { +func CreateNewOrdererWithRootCAs(url string, ordererRootCAs [][]byte, serverHostOverride string, config config.Config) (*Orderer, error) { if config.IsTLSEnabled() { tlsCaCertPool, err := config.TLSCACertPoolFromRoots(ordererRootCAs) if err != nil { @@ -41,29 +42,29 @@ func CreateNewOrdererWithRootCAs(url string, ordererRootCAs [][]byte, serverHost return createNewOrdererWithoutTLS(url), nil } -func createNewOrdererWithoutTLS(url string) fab.Orderer { +func createNewOrdererWithoutTLS(url string) *Orderer { var opts []grpc.DialOption opts = append(opts, grpc.WithTimeout(time.Second*3)) opts = append(opts, grpc.WithInsecure()) - return &orderer{url: url, grpcDialOption: opts} + return &Orderer{url: url, grpcDialOption: opts} } -func createNewOrdererWithCertPool(url string, tlsCaCertPool *x509.CertPool, serverHostOverride string) fab.Orderer { +func createNewOrdererWithCertPool(url string, tlsCaCertPool *x509.CertPool, serverHostOverride string) *Orderer { var opts []grpc.DialOption opts = append(opts, grpc.WithTimeout(time.Second*3)) creds := credentials.NewClientTLSFromCert(tlsCaCertPool, serverHostOverride) opts = append(opts, grpc.WithTransportCredentials(creds)) - return &orderer{url: url, grpcDialOption: opts} + return &Orderer{url: url, grpcDialOption: opts} } // URL Get the Orderer url. Required property for the instance objects. -// @returns {string} The address of the Orderer -func (o *orderer) URL() string { +// Returns the address of the Orderer. +func (o *Orderer) URL() string { return o.url } // SendBroadcast Send the created transaction to Orderer. -func (o *orderer) SendBroadcast(envelope *fab.SignedEnvelope) (*common.Status, error) { +func (o *Orderer) SendBroadcast(envelope *fab.SignedEnvelope) (*common.Status, error) { conn, err := grpc.Dial(o.url, o.grpcDialOption...) if err != nil { return nil, err @@ -112,10 +113,8 @@ func (o *orderer) SendBroadcast(envelope *fab.SignedEnvelope) (*common.Status, e // SendDeliver sends a deliver request to the ordering service and returns the // blocks requested -// @param {*SignedEnvelope} envelope that contains the seek request for blocks -// @return {chan *common.Block} channel with the requested blocks -// @return {chan error} a buffered channel that can contain a single error -func (o *orderer) SendDeliver(envelope *fab.SignedEnvelope) (chan *common.Block, +// envelope: contains the seek request for blocks +func (o *Orderer) SendDeliver(envelope *fab.SignedEnvelope) (chan *common.Block, chan error) { responses := make(chan *common.Block) errors := make(chan error, 1) @@ -185,7 +184,7 @@ func (o *orderer) SendDeliver(envelope *fab.SignedEnvelope) (chan *common.Block, } // NewOrderer Returns a Orderer instance -func NewOrderer(url string, certificate string, serverHostOverride string, config config.Config) (fab.Orderer, error) { +func NewOrderer(url string, certificate string, serverHostOverride string, config config.Config) (*Orderer, error) { var opts []grpc.DialOption opts = append(opts, grpc.WithTimeout(time.Second*3)) if config.IsTLSEnabled() { @@ -198,5 +197,5 @@ func NewOrderer(url string, certificate string, serverHostOverride string, confi } else { opts = append(opts, grpc.WithInsecure()) } - return &orderer{url: url, grpcDialOption: opts}, nil + return &Orderer{url: url, grpcDialOption: opts}, nil } diff --git a/pkg/fabric-client/orderer/orderer_test.go b/pkg/fabric-client/orderer/orderer_test.go index 013728f342..7ecb228e4e 100644 --- a/pkg/fabric-client/orderer/orderer_test.go +++ b/pkg/fabric-client/orderer/orderer_test.go @@ -412,3 +412,13 @@ func TestSendBroadcastError(t *testing.T) { } } + +func TestInterfaces(t *testing.T) { + var apiOrderer fab.Orderer + var orderer Orderer + + apiOrderer = &orderer + if apiOrderer == nil { + t.Fatalf("this shouldn't happen.") + } +} diff --git a/pkg/fabric-client/peer/peer.go b/pkg/fabric-client/peer/peer.go index 6b6fb0c6c9..1b64f9bac9 100644 --- a/pkg/fabric-client/peer/peer.go +++ b/pkg/fabric-client/peer/peer.go @@ -174,3 +174,13 @@ func (p *Peer) RemoveListener(eventListenerRef string) (bool, error) { return false, nil //to do } + +// PeersToTxnProcessors converts a slice of Peers to a slice of TxnProposalProcessors +func PeersToTxnProcessors(peers []fab.Peer) []apitxn.ProposalProcessor { + tpp := make([]apitxn.ProposalProcessor, len(peers)) + + for i := range peers { + tpp[i] = peers[i] + } + return tpp +} diff --git a/pkg/fabric-client/peer/peer_test.go b/pkg/fabric-client/peer/peer_test.go index 0659683f62..a9178e36fb 100644 --- a/pkg/fabric-client/peer/peer_test.go +++ b/pkg/fabric-client/peer/peer_test.go @@ -214,6 +214,33 @@ func TestPlaceholders(t *testing.T) { } } +func TestPeersToTxnProcessors(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + config := mock_apiconfig.NewMockConfig(mockCtrl) + config.EXPECT().IsTLSEnabled().Return(false) + + peer1, err := NewPeer(peer1URL, config) + if err != nil { + t.Fatalf("Failed to create NewPeer error(%v)", err) + } + + config.EXPECT().IsTLSEnabled().Return(false) + peer2, err := NewPeer(peer2URL, config) + if err != nil { + t.Fatalf("Failed to create NewPeer error(%v)", err) + } + + peers := []fab.Peer{peer1, peer2} + processors := PeersToTxnProcessors(peers) + + for i := range peers { + if !reflect.DeepEqual(peers[i], processors[i]) { + t.Fatalf("Peer to Processors mismatch") + } + } +} + func TestInterfaces(t *testing.T) { var apiPeer fab.Peer var peer Peer diff --git a/test/integration/channel_queries_test.go b/test/integration/channel_queries_test.go index b22464be67..1fef078b95 100644 --- a/test/integration/channel_queries_test.go +++ b/test/integration/channel_queries_test.go @@ -227,7 +227,7 @@ func testInstantiatedChaincodes(t *testing.T, channel fab.Channel) { func testQueryByChaincode(t *testing.T, channel fab.Channel, config config.Config, testSetup *BaseSetupImpl) { // Test valid targets - targets := fab.PeersToTxnProcessors(channel.Peers()) + targets := peer.PeersToTxnProcessors(channel.Peers()) // set Client User Context to Admin before calling QueryByChaincode testSetup.Client.SetUserContext(testSetup.AdminUser) diff --git a/test/scripts/unit.sh b/test/scripts/unit.sh index 188dde642e..6cb32dd6ec 100755 --- a/test/scripts/unit.sh +++ b/test/scripts/unit.sh @@ -10,9 +10,12 @@ set -e +REPO="github.com/hyperledger/fabric-sdk-go" + # Packages to exclude -PKGS=`go list github.com/hyperledger/fabric-sdk-go/... 2> /dev/null | \ - grep -v /vendor/ | \ - grep -v /test/` +PKGS=`go list $REPO... 2> /dev/null | \ + grep -v ^$REPO/api/ | \ + grep -v ^$REPO/pkg/fabric-ca-client/mocks | grep -v ^$REPO/pkg/fabric-client/mocks | \ + grep -v ^$REPO/vendor/ | grep -v ^$REPO/test/` echo "Running tests..." gocov test $GOTESTFLAGS $LDFLAGS $PKGS -p 1 -timeout=5m | gocov-xml > report.xml