From f3528ca32c7e462654464934b3100527dae0f6a6 Mon Sep 17 00:00:00 2001 From: Sudesh Shetty Date: Mon, 28 May 2018 10:45:55 -0400 Subject: [PATCH] [FAB-10279] refactoring endpointconfig In EndpointConfig implementation, - network config should be loaded once at the beginning when endpoint config is created from config backend. - All entity search functions should return (entity, bool) instead of (entity, error) Change-Id: Ia93a7ac53da28fcd8d38aa97e36a0f9a436f87b0 Signed-off-by: Sudesh Shetty --- .../discovery/dynamicdiscovery/chservice.go | 6 +- .../dynamicdiscovery/localservice.go | 6 +- .../dynamicdiscovery/provider_test.go | 7 +- .../discovery/dynamicdiscovery/service.go | 6 +- .../discovery/staticdiscovery/provider.go | 12 +- pkg/client/common/filter/endpoint.go | 4 +- pkg/client/msp/client.go | 8 +- pkg/client/resmgmt/opts.go | 6 +- pkg/client/resmgmt/resmgmt.go | 6 +- pkg/client/resmgmt/resmgmt_test.go | 5 +- pkg/common/errors/status/codes.go | 16 +- pkg/common/providers/fab/provider.go | 22 +- .../providers/test/mockfab/mockfab.gen.go | 44 +-- pkg/fab/channel/transactor.go | 29 +- pkg/fab/chconfig/chconfig.go | 84 +++--- pkg/fab/chconfig/chconfig_test.go | 4 +- pkg/fab/comm/network.go | 29 +- pkg/fab/comm/network_test.go | 4 +- pkg/fab/endpointconfig.go | 264 +++++++++--------- pkg/fab/endpointconfig_test.go | 166 +++++------ pkg/fab/events/endpoint/endpoint_test.go | 4 +- pkg/fab/events/endpoint/endpointdiscovery.go | 19 +- pkg/fab/mocks/mockconfig.go | 63 ++--- pkg/fab/opts.go | 22 +- pkg/fab/opts_test.go | 68 ++--- pkg/fab/orderer/orderer.go | 6 +- pkg/fabsdk/fabsdk_test.go | 32 +-- pkg/fabsdk/provider/msppvdr/msppvdr.go | 6 +- pkg/msp/caclient.go | 7 +- pkg/msp/enrollment_test.go | 6 +- pkg/msp/getsigid.go | 6 +- pkg/msp/getsigid_test.go | 6 +- pkg/msp/identityconfig.go | 13 +- pkg/msp/identityconfig_test.go | 52 ++-- pkg/msp/identitymgr.go | 7 +- pkg/msp/main_test.go | 14 +- pkg/msp/test/mockmspapi/mockmspapi.gen.go | 65 +++++ test/integration/base_test_setup.go | 6 +- .../endpointconfig_override_test.go | 94 +++---- test/integration/msp/user_data_mgmt_test.go | 6 +- test/integration/orgs/multiple_orgs_test.go | 13 +- test/integration/revoked/revoked_peer_test.go | 13 +- test/integration/sdk/channel_config_test.go | 4 +- test/integration/sdk/ledger_queries_test.go | 4 +- 44 files changed, 631 insertions(+), 633 deletions(-) diff --git a/pkg/client/common/discovery/dynamicdiscovery/chservice.go b/pkg/client/common/discovery/dynamicdiscovery/chservice.go index efe436fb6d..542fe1b122 100644 --- a/pkg/client/common/discovery/dynamicdiscovery/chservice.go +++ b/pkg/client/common/discovery/dynamicdiscovery/chservice.go @@ -73,9 +73,9 @@ func (s *channelService) queryPeers() ([]fab.Peer, error) { func (s *channelService) getTargets(ctx contextAPI.Channel) ([]fab.PeerConfig, error) { // TODO: The number of peers to query should be retrieved from the channel policy. // This will done in a future patch. - chpeers, err := ctx.EndpointConfig().ChannelPeers(ctx.ChannelID()) - if err != nil { - return nil, errors.Wrapf(err, "failed to get peer configs for channel [%s]", ctx.ChannelID()) + chpeers, ok := ctx.EndpointConfig().ChannelPeers(ctx.ChannelID()) + if !ok { + return nil, errors.Errorf("failed to get peer configs for channel [%s]", ctx.ChannelID()) } targets := make([]fab.PeerConfig, len(chpeers)) for i := 0; i < len(targets); i++ { diff --git a/pkg/client/common/discovery/dynamicdiscovery/localservice.go b/pkg/client/common/discovery/dynamicdiscovery/localservice.go index ca7dceb8f5..0a6335fda0 100644 --- a/pkg/client/common/discovery/dynamicdiscovery/localservice.go +++ b/pkg/client/common/discovery/dynamicdiscovery/localservice.go @@ -77,9 +77,9 @@ func (s *LocalService) queryPeers() ([]fab.Peer, error) { } func (s *LocalService) getTarget(ctx contextAPI.Client) (*fab.PeerConfig, error) { - peers, err := ctx.EndpointConfig().NetworkPeers() - if err != nil { - return nil, errors.Wrapf(err, "failed to get peer configs") + peers, ok := ctx.EndpointConfig().NetworkPeers() + if !ok { + return nil, errors.New("failed to get network peers") } mspID := ctx.Identifier().MSPID for _, p := range peers { diff --git a/pkg/client/common/discovery/dynamicdiscovery/provider_test.go b/pkg/client/common/discovery/dynamicdiscovery/provider_test.go index 4107a1aab7..cb930df56c 100644 --- a/pkg/client/common/discovery/dynamicdiscovery/provider_test.go +++ b/pkg/client/common/discovery/dynamicdiscovery/provider_test.go @@ -82,6 +82,9 @@ type config struct { peers []pfab.ChannelPeer } -func (c *config) ChannelPeers(name string) ([]pfab.ChannelPeer, error) { - return c.peers, nil +func (c *config) ChannelPeers(name string) ([]pfab.ChannelPeer, bool) { + if len(c.peers) == 0 { + return nil, false + } + return c.peers, true } diff --git a/pkg/client/common/discovery/dynamicdiscovery/service.go b/pkg/client/common/discovery/dynamicdiscovery/service.go index cfd552251c..468d55903e 100644 --- a/pkg/client/common/discovery/dynamicdiscovery/service.go +++ b/pkg/client/common/discovery/dynamicdiscovery/service.go @@ -114,9 +114,9 @@ func asPeers(ctx contextAPI.Client, endpoints []*discclient.Peer) []fab.Peer { logger.Debugf("Adding endpoint [%s]", url) - peerConfig, err := ctx.EndpointConfig().PeerConfig(url) - if err != nil { - logger.Warnf("Error getting peer config for url [%s]: %s", url, err) + peerConfig, found := ctx.EndpointConfig().PeerConfig(url) + if !found { + logger.Warnf("Peer config not found for url [%s]", url) continue } diff --git a/pkg/client/common/discovery/staticdiscovery/provider.go b/pkg/client/common/discovery/staticdiscovery/provider.go index 8c42d9f41e..c311b5aad8 100644 --- a/pkg/client/common/discovery/staticdiscovery/provider.go +++ b/pkg/client/common/discovery/staticdiscovery/provider.go @@ -45,9 +45,9 @@ func (dp *DiscoveryProvider) CreateDiscoveryService(channelID string) (fab.Disco } // Use configured channel peers - chPeers, err := dp.config.ChannelPeers(channelID) - if err != nil { - return nil, errors.WithMessage(err, "unable to read configuration for channel peers") + chPeers, ok := dp.config.ChannelPeers(channelID) + if !ok { + return nil, errors.New("unable to read configuration for channel peers") } peers := []fab.Peer{} @@ -67,9 +67,9 @@ func (dp *DiscoveryProvider) CreateDiscoveryService(channelID string) (fab.Disco func (dp *DiscoveryProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) { peers := []fab.Peer{} - netPeers, err := dp.config.NetworkPeers() - if err != nil { - return nil, errors.WithMessage(err, "unable to read configuration for network peers") + netPeers, ok := dp.config.NetworkPeers() + if !ok { + return nil, errors.New("unable to read configuration for network peers") } for _, p := range netPeers { diff --git a/pkg/client/common/filter/endpoint.go b/pkg/client/common/filter/endpoint.go index bf84a2c1a2..0d102da96a 100644 --- a/pkg/client/common/filter/endpoint.go +++ b/pkg/client/common/filter/endpoint.go @@ -29,8 +29,8 @@ const ( func NewEndpointFilter(ctx context.Channel, et EndpointType) *EndpointFilter { // Retrieve channel peers - chPeers, err := ctx.EndpointConfig().ChannelPeers(ctx.ChannelID()) - if err != nil { + chPeers, ok := ctx.EndpointConfig().ChannelPeers(ctx.ChannelID()) + if !ok { // Setting channel peers to empty due to config error, should not happen chPeers = []fab.ChannelPeer{} } diff --git a/pkg/client/msp/client.go b/pkg/client/msp/client.go index a4cd17e915..093484579e 100644 --- a/pkg/client/msp/client.go +++ b/pkg/client/msp/client.go @@ -89,11 +89,11 @@ func New(clientProvider context.ClientProvider, opts ...ClientOption) (*Client, if msp.orgName == "" { return nil, errors.New("organization is not provided") } - networkConfig, err := ctx.EndpointConfig().NetworkConfig() - if err != nil { - return nil, errors.WithMessage(err, "failed to get NetworkConfig") + networkConfig, ok := ctx.EndpointConfig().NetworkConfig() + if !ok { + return nil, errors.New("failed to get NetworkConfig") } - _, ok := networkConfig.Organizations[strings.ToLower(msp.orgName)] + _, ok = networkConfig.Organizations[strings.ToLower(msp.orgName)] if !ok { return nil, fmt.Errorf("non-existent organization: '%s'", msp.orgName) } diff --git a/pkg/client/resmgmt/opts.go b/pkg/client/resmgmt/opts.go index 0ca088526f..62ef7e5ac7 100644 --- a/pkg/client/resmgmt/opts.go +++ b/pkg/client/resmgmt/opts.go @@ -87,9 +87,9 @@ func WithOrdererEndpoint(key string) RequestOption { return func(ctx context.Client, opts *requestOptions) error { - ordererCfg, err := ctx.EndpointConfig().OrdererConfig(key) - if err != nil { - return errors.Wrapf(err, "orderer not found for url : %s", key) + ordererCfg, found := ctx.EndpointConfig().OrdererConfig(key) + if !found { + return errors.Errorf("orderer not found for url : %s", key) } orderer, err := ctx.InfraProvider().CreateOrdererFromConfig(ordererCfg) diff --git a/pkg/client/resmgmt/resmgmt.go b/pkg/client/resmgmt/resmgmt.go index d9c9be6ea7..27bc0e5790 100644 --- a/pkg/client/resmgmt/resmgmt.go +++ b/pkg/client/resmgmt/resmgmt.go @@ -992,7 +992,7 @@ func (rc *Client) requestOrderer(opts *requestOptions, channelID string) (fab.Or } func (rc *Client) ordererConfig(channelID string) (*fab.OrdererConfig, error) { - orderers, err := rc.ctx.EndpointConfig().ChannelOrderers(channelID) + orderers, ok := rc.ctx.EndpointConfig().ChannelOrderers(channelID) // TODO: Not sure that we should fallback to global orderers section. // For now - not doing so. @@ -1000,8 +1000,8 @@ func (rc *Client) ordererConfig(channelID string) (*fab.OrdererConfig, error) { // orderers, err = rc.ctx.Config().OrderersConfig() //} - if err != nil { - return nil, errors.WithMessage(err, "orderers lookup failed") + if !ok { + return nil, errors.New("orderers lookup failed") } if len(orderers) == 0 { return nil, errors.New("no orderers found") diff --git a/pkg/client/resmgmt/resmgmt_test.go b/pkg/client/resmgmt/resmgmt_test.go index 4798f420aa..17663b2a6e 100644 --- a/pkg/client/resmgmt/resmgmt_test.go +++ b/pkg/client/resmgmt/resmgmt_test.go @@ -340,7 +340,7 @@ func TestJoinChannelNoOrdererConfig(t *testing.T) { err = rc.JoinChannel("mychannel", WithTargets(peer1)) assert.NotNil(t, err, "Should have failed to join channel since no orderer has been configured") - assert.Contains(t, err.Error(), "no matching channel config found") + assert.Contains(t, err.Error(), "orderer not found: orderers lookup failed") // Misconfigured channel orderer configBackend = getInvalidChannelOrdererBackend(backend...) @@ -354,7 +354,8 @@ func TestJoinChannelNoOrdererConfig(t *testing.T) { rc = setupResMgmtClient(t, ctx) err = rc.JoinChannel("mychannel", WithTargets(peer1)) - if err == nil || !strings.Contains(err.Error(), "no matching orderer config found") { + + if err == nil || !strings.Contains(err.Error(), "failed to find orderer for request: orderer not found: orderers lookup failed") { t.Fatalf("Should have failed to join channel since channel orderer has been misconfigured") } diff --git a/pkg/common/errors/status/codes.go b/pkg/common/errors/status/codes.go index d47dd9fd6e..54a11e8f8c 100644 --- a/pkg/common/errors/status/codes.go +++ b/pkg/common/errors/status/codes.go @@ -48,24 +48,12 @@ const ( // MissingEndorsement is if an endoresement is missing MissingEndorsement Code = 9 - // NoMatchingCertificateAuthorityEntity is if entityMatchers are unable to find any matchingCertificateAuthority - NoMatchingCertificateAuthorityEntity Code = 21 - - // NoMatchingPeerEntity is if entityMatchers are unable to find any matchingPeer - NoMatchingPeerEntity Code = 22 - - // NoMatchingOrdererEntity is if entityMatchers are unable to find any matchingOrderer - NoMatchingOrdererEntity Code = 23 - // PrematureChaincodeExecution indicates that an attempt was made to invoke a chaincode that's // in the process of being launched. - PrematureChaincodeExecution Code = 24 - - // NoMatchingChannelEntity is if entityMatchers are unable to find any matchingChannel - NoMatchingChannelEntity Code = 25 + PrematureChaincodeExecution Code = 21 // ChaincodeAlreadyLaunching indicates that an attempt for multiple simultaneous invokes was made to launch chaincode - ChaincodeAlreadyLaunching Code = 26 + ChaincodeAlreadyLaunching Code = 22 ) // CodeName maps the codes in this packages to human-readable strings diff --git a/pkg/common/providers/fab/provider.go b/pkg/common/providers/fab/provider.go index c63eb4acbe..3ceffee061 100644 --- a/pkg/common/providers/fab/provider.go +++ b/pkg/common/providers/fab/provider.go @@ -85,17 +85,17 @@ type CommManager interface { //EndpointConfig contains endpoint network configurations type EndpointConfig interface { Timeout(TimeoutType) time.Duration - MSPID(org string) (string, error) - PeerMSPID(name string) (string, error) - OrderersConfig() ([]OrdererConfig, error) - OrdererConfig(nameOrURL string) (*OrdererConfig, error) - PeersConfig(org string) ([]PeerConfig, error) - PeerConfig(nameOrURL string) (*PeerConfig, error) - NetworkConfig() (*NetworkConfig, error) - NetworkPeers() ([]NetworkPeer, error) - ChannelConfig(name string) (*ChannelNetworkConfig, error) - ChannelPeers(name string) ([]ChannelPeer, error) - ChannelOrderers(name string) ([]OrdererConfig, error) + MSPID(org string) (string, bool) + PeerMSPID(name string) (string, bool) + OrderersConfig() ([]OrdererConfig, bool) + OrdererConfig(nameOrURL string) (*OrdererConfig, bool) + PeersConfig(org string) ([]PeerConfig, bool) + PeerConfig(nameOrURL string) (*PeerConfig, bool) + NetworkConfig() (*NetworkConfig, bool) + NetworkPeers() ([]NetworkPeer, bool) + ChannelConfig(name string) (*ChannelNetworkConfig, bool) + ChannelPeers(name string) ([]ChannelPeer, bool) + ChannelOrderers(name string) ([]OrdererConfig, bool) TLSCACertPool(certConfig ...*x509.Certificate) (*x509.CertPool, error) EventServiceType() EventServiceType TLSClientCerts() ([]tls.Certificate, error) diff --git a/pkg/common/providers/test/mockfab/mockfab.gen.go b/pkg/common/providers/test/mockfab/mockfab.gen.go index f29018c0de..a7ae351cd8 100644 --- a/pkg/common/providers/test/mockfab/mockfab.gen.go +++ b/pkg/common/providers/test/mockfab/mockfab.gen.go @@ -39,10 +39,10 @@ func (m *MockEndpointConfig) EXPECT() *MockEndpointConfigMockRecorder { } // ChannelConfig mocks base method -func (m *MockEndpointConfig) ChannelConfig(arg0 string) (*fab.ChannelNetworkConfig, error) { +func (m *MockEndpointConfig) ChannelConfig(arg0 string) (*fab.ChannelNetworkConfig, bool) { ret := m.ctrl.Call(m, "ChannelConfig", arg0) ret0, _ := ret[0].(*fab.ChannelNetworkConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -52,10 +52,10 @@ func (mr *MockEndpointConfigMockRecorder) ChannelConfig(arg0 interface{}) *gomoc } // ChannelOrderers mocks base method -func (m *MockEndpointConfig) ChannelOrderers(arg0 string) ([]fab.OrdererConfig, error) { +func (m *MockEndpointConfig) ChannelOrderers(arg0 string) ([]fab.OrdererConfig, bool) { ret := m.ctrl.Call(m, "ChannelOrderers", arg0) ret0, _ := ret[0].([]fab.OrdererConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -65,10 +65,10 @@ func (mr *MockEndpointConfigMockRecorder) ChannelOrderers(arg0 interface{}) *gom } // ChannelPeers mocks base method -func (m *MockEndpointConfig) ChannelPeers(arg0 string) ([]fab.ChannelPeer, error) { +func (m *MockEndpointConfig) ChannelPeers(arg0 string) ([]fab.ChannelPeer, bool) { ret := m.ctrl.Call(m, "ChannelPeers", arg0) ret0, _ := ret[0].([]fab.ChannelPeer) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -102,10 +102,10 @@ func (mr *MockEndpointConfigMockRecorder) EventServiceType() *gomock.Call { } // MSPID mocks base method -func (m *MockEndpointConfig) MSPID(arg0 string) (string, error) { +func (m *MockEndpointConfig) MSPID(arg0 string) (string, bool) { ret := m.ctrl.Call(m, "MSPID", arg0) ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -115,10 +115,10 @@ func (mr *MockEndpointConfigMockRecorder) MSPID(arg0 interface{}) *gomock.Call { } // NetworkConfig mocks base method -func (m *MockEndpointConfig) NetworkConfig() (*fab.NetworkConfig, error) { +func (m *MockEndpointConfig) NetworkConfig() (*fab.NetworkConfig, bool) { ret := m.ctrl.Call(m, "NetworkConfig") ret0, _ := ret[0].(*fab.NetworkConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -128,10 +128,10 @@ func (mr *MockEndpointConfigMockRecorder) NetworkConfig() *gomock.Call { } // NetworkPeers mocks base method -func (m *MockEndpointConfig) NetworkPeers() ([]fab.NetworkPeer, error) { +func (m *MockEndpointConfig) NetworkPeers() ([]fab.NetworkPeer, bool) { ret := m.ctrl.Call(m, "NetworkPeers") ret0, _ := ret[0].([]fab.NetworkPeer) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -141,10 +141,10 @@ func (mr *MockEndpointConfigMockRecorder) NetworkPeers() *gomock.Call { } // OrdererConfig mocks base method -func (m *MockEndpointConfig) OrdererConfig(arg0 string) (*fab.OrdererConfig, error) { +func (m *MockEndpointConfig) OrdererConfig(arg0 string) (*fab.OrdererConfig, bool) { ret := m.ctrl.Call(m, "OrdererConfig", arg0) ret0, _ := ret[0].(*fab.OrdererConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -154,10 +154,10 @@ func (mr *MockEndpointConfigMockRecorder) OrdererConfig(arg0 interface{}) *gomoc } // OrderersConfig mocks base method -func (m *MockEndpointConfig) OrderersConfig() ([]fab.OrdererConfig, error) { +func (m *MockEndpointConfig) OrderersConfig() ([]fab.OrdererConfig, bool) { ret := m.ctrl.Call(m, "OrderersConfig") ret0, _ := ret[0].([]fab.OrdererConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -167,10 +167,10 @@ func (mr *MockEndpointConfigMockRecorder) OrderersConfig() *gomock.Call { } // PeerConfig mocks base method -func (m *MockEndpointConfig) PeerConfig(arg0 string) (*fab.PeerConfig, error) { +func (m *MockEndpointConfig) PeerConfig(arg0 string) (*fab.PeerConfig, bool) { ret := m.ctrl.Call(m, "PeerConfig", arg0) ret0, _ := ret[0].(*fab.PeerConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -180,10 +180,10 @@ func (mr *MockEndpointConfigMockRecorder) PeerConfig(arg0 interface{}) *gomock.C } // PeerMSPID mocks base method -func (m *MockEndpointConfig) PeerMSPID(arg0 string) (string, error) { +func (m *MockEndpointConfig) PeerMSPID(arg0 string) (string, bool) { ret := m.ctrl.Call(m, "PeerMSPID", arg0) ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } @@ -193,10 +193,10 @@ func (mr *MockEndpointConfigMockRecorder) PeerMSPID(arg0 interface{}) *gomock.Ca } // PeersConfig mocks base method -func (m *MockEndpointConfig) PeersConfig(arg0 string) ([]fab.PeerConfig, error) { +func (m *MockEndpointConfig) PeersConfig(arg0 string) ([]fab.PeerConfig, bool) { ret := m.ctrl.Call(m, "PeersConfig", arg0) ret0, _ := ret[0].([]fab.PeerConfig) - ret1, _ := ret[1].(error) + ret1, _ := ret[1].(bool) return ret0, ret1 } diff --git a/pkg/fab/channel/transactor.go b/pkg/fab/channel/transactor.go index 63bd7605b3..0a086074d2 100644 --- a/pkg/fab/channel/transactor.go +++ b/pkg/fab/channel/transactor.go @@ -16,7 +16,6 @@ import ( reqContext "context" - "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/status" contextImpl "github.com/hyperledger/fabric-sdk-go/pkg/context" "github.com/hyperledger/fabric-sdk-go/pkg/core/config/endpoint" "github.com/hyperledger/fabric-sdk-go/pkg/fab/txn" @@ -82,8 +81,8 @@ func orderersFromChannelCfg(ctx context.Client, cfg fab.ChannelCfg) ([]fab.Order if !ok { logger.Debugf("Failed to get channel Cfg orderer [%s] from ordererDict, now trying orderer Matchers in Entity Matchers", target) // Try to find a match from entityMatchers config - matchingOrdererConfig, matchErr := ctx.EndpointConfig().OrdererConfig(strings.ToLower(target)) - if matchErr == nil { + matchingOrdererConfig, found := ctx.EndpointConfig().OrdererConfig(strings.ToLower(target)) + if found { logger.Debugf("Found matching ordererConfig from entity Matchers for channel Cfg Orderer [%s]", target) oCfg = *matchingOrdererConfig ok = true @@ -114,24 +113,16 @@ func orderersFromChannelCfg(ctx context.Client, cfg fab.ChannelCfg) ([]fab.Order //will return empty list when orderers are not found in endpoint config func orderersFromChannel(ctx context.Client, channelID string) ([]fab.Orderer, error) { - chNetworkConfig, err := ctx.EndpointConfig().ChannelConfig(channelID) - if err != nil { - s, ok := status.FromError(err) - if ok && s.Code == status.NoMatchingChannelEntity.ToInt32() { - return []fab.Orderer{}, nil - } - return nil, errors.WithMessage(err, "failed to get channel network config") + chNetworkConfig, ok := ctx.EndpointConfig().ChannelConfig(channelID) + if !ok { + return []fab.Orderer{}, nil } orderers := []fab.Orderer{} for _, chOrderer := range chNetworkConfig.Orderers { - ordererConfig, err := ctx.EndpointConfig().OrdererConfig(chOrderer) - if err != nil { - s, ok := status.FromError(err) - if !ok || s.Code != status.NoMatchingOrdererEntity.ToInt32() { - return nil, errors.Wrapf(err, "unable to get orderer config from [%s]", chOrderer) - } + ordererConfig, found := ctx.EndpointConfig().OrdererConfig(chOrderer) + if !found { //continue if given channel orderer not found in endpoint config continue } @@ -148,9 +139,9 @@ func orderersFromChannel(ctx context.Client, channelID string) ([]fab.Orderer, e func orderersByTarget(ctx context.Client) (map[string]fab.OrdererConfig, error) { ordererDict := map[string]fab.OrdererConfig{} - orderersConfig, err := ctx.EndpointConfig().OrderersConfig() - if err != nil { - return nil, errors.WithMessage(err, "loading orderers config failed") + orderersConfig, ok := ctx.EndpointConfig().OrderersConfig() + if !ok { + return nil, errors.New("loading orderers config failed") } for _, oc := range orderersConfig { diff --git a/pkg/fab/chconfig/chconfig.go b/pkg/fab/chconfig/chconfig.go index 1a1d98529b..12ec38b04d 100644 --- a/pkg/fab/chconfig/chconfig.go +++ b/pkg/fab/chconfig/chconfig.go @@ -15,7 +15,6 @@ import ( channelConfig "github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/common/channelconfig" imsp "github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/msp" "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry" - "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/status" "github.com/hyperledger/fabric-sdk-go/pkg/common/logging" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" @@ -194,9 +193,9 @@ func (c *ChannelConfig) queryPeers(reqCtx reqContext.Context) (*ChannelCfg, erro func (c *ChannelConfig) calculateTargetsFromConfig(ctx context.Client) ([]fab.ProposalProcessor, error) { targets := []fab.ProposalProcessor{} - chPeers, err := ctx.EndpointConfig().ChannelPeers(c.channelID) - if err != nil { - return nil, errors.WithMessage(err, "read configuration for channel peers failed") + chPeers, ok := ctx.EndpointConfig().ChannelPeers(c.channelID) + if !ok { + return nil, errors.New("read configuration for channel peers failed") } for _, p := range chPeers { @@ -231,70 +230,67 @@ func (c *ChannelConfig) resolveOptsFromConfig(ctx context.Client) error { } //If missing from opts, check config and update opts from config - chSdkCfg, err := ctx.EndpointConfig().ChannelConfig(c.channelID) - if err != nil { - s, ok := status.FromError(err) - if !ok || s.Code != status.NoMatchingChannelEntity.ToInt32() { - return err - } + chSdkCfg, ok := ctx.EndpointConfig().ChannelConfig(c.channelID) + if ok { + //resolve opts + c.resolveMaxResponsesOptsFromConfig(chSdkCfg) + c.resolveMinResponsesOptsFromConfig(chSdkCfg) + c.resolveRetryOptsFromConfig(chSdkCfg) } - //resolve opts - c.resolveMaxResponsesOptsFromConfig(chSdkCfg) - c.resolveMinResponsesOptsFromConfig(chSdkCfg) - c.resolveRetryOptsFromConfig(chSdkCfg) + //apply default to missing opts + c.applyDefaultOpts() return nil } func (c *ChannelConfig) resolveMaxResponsesOptsFromConfig(chSdkCfg *fab.ChannelNetworkConfig) { - if c.opts.MaxTargets == 0 { - if chSdkCfg != nil && &chSdkCfg.Policies != nil && &chSdkCfg.Policies.QueryChannelConfig != nil { - c.opts.MaxTargets = chSdkCfg.Policies.QueryChannelConfig.MaxTargets - } - if c.opts.MaxTargets == 0 { - c.opts.MaxTargets = defaultMaxTargets - } + if c.opts.MaxTargets == 0 && &chSdkCfg.Policies != nil && &chSdkCfg.Policies.QueryChannelConfig != nil { + c.opts.MaxTargets = chSdkCfg.Policies.QueryChannelConfig.MaxTargets } } func (c *ChannelConfig) resolveMinResponsesOptsFromConfig(chSdkCfg *fab.ChannelNetworkConfig) { - if c.opts.MinResponses == 0 { - if chSdkCfg != nil && &chSdkCfg.Policies != nil && &chSdkCfg.Policies.QueryChannelConfig != nil { - c.opts.MinResponses = chSdkCfg.Policies.QueryChannelConfig.MinResponses - } - if c.opts.MinResponses == 0 { - c.opts.MinResponses = defaultMinResponses - } + if c.opts.MinResponses == 0 && &chSdkCfg.Policies != nil && &chSdkCfg.Policies.QueryChannelConfig != nil { + c.opts.MinResponses = chSdkCfg.Policies.QueryChannelConfig.MinResponses } - } func (c *ChannelConfig) resolveRetryOptsFromConfig(chSdkCfg *fab.ChannelNetworkConfig) { - if c.opts.RetryOpts.RetryableCodes == nil { - if chSdkCfg != nil && &chSdkCfg.Policies != nil && &chSdkCfg.Policies.QueryChannelConfig != nil { + if c.opts.RetryOpts.RetryableCodes == nil && &chSdkCfg.Policies != nil && &chSdkCfg.Policies.QueryChannelConfig != nil { c.opts.RetryOpts = chSdkCfg.Policies.QueryChannelConfig.RetryOpts } - if c.opts.RetryOpts.Attempts == 0 { - c.opts.RetryOpts.Attempts = retry.DefaultAttempts - } + c.opts.RetryOpts.RetryableCodes = retry.ChannelConfigRetryableCodes + } +} - if c.opts.RetryOpts.InitialBackoff == 0 { - c.opts.RetryOpts.InitialBackoff = retry.DefaultInitialBackoff - } +func (c *ChannelConfig) applyDefaultOpts() { + if c.opts.MaxTargets == 0 { + c.opts.MaxTargets = defaultMaxTargets + } + if c.opts.MinResponses == 0 { + c.opts.MinResponses = defaultMinResponses + } + if c.opts.RetryOpts.Attempts == 0 { + c.opts.RetryOpts.Attempts = retry.DefaultAttempts + } - if c.opts.RetryOpts.BackoffFactor == 0 { - c.opts.RetryOpts.BackoffFactor = retry.DefaultBackoffFactor - } + if c.opts.RetryOpts.InitialBackoff == 0 { + c.opts.RetryOpts.InitialBackoff = retry.DefaultInitialBackoff + } - if c.opts.RetryOpts.MaxBackoff == 0 { - c.opts.RetryOpts.MaxBackoff = retry.DefaultMaxBackoff - } + if c.opts.RetryOpts.BackoffFactor == 0 { + c.opts.RetryOpts.BackoffFactor = retry.DefaultBackoffFactor + } - c.opts.RetryOpts.RetryableCodes = retry.ChannelConfigRetryableCodes + if c.opts.RetryOpts.MaxBackoff == 0 { + c.opts.RetryOpts.MaxBackoff = retry.DefaultMaxBackoff } + if c.opts.RetryOpts.RetryableCodes == nil { + c.opts.RetryOpts.RetryableCodes = retry.ChannelConfigRetryableCodes + } } // WithPeers encapsulates peers to Option diff --git a/pkg/fab/chconfig/chconfig_test.go b/pkg/fab/chconfig/chconfig_test.go index b45832e59b..5a1d71c148 100644 --- a/pkg/fab/chconfig/chconfig_test.go +++ b/pkg/fab/chconfig/chconfig_test.go @@ -344,9 +344,9 @@ type customMockConfig struct { called bool } -func (c *customMockConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, error) { +func (c *customMockConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, bool) { c.called = true - return c.chConfig, nil + return c.chConfig, true } //customRetryHandler is wrapper around retry handler which keeps count of attempts for unit-testing diff --git a/pkg/fab/comm/network.go b/pkg/fab/comm/network.go index 3f61d0174b..0be95a2f53 100644 --- a/pkg/fab/comm/network.go +++ b/pkg/fab/comm/network.go @@ -7,22 +7,21 @@ SPDX-License-Identifier: Apache-2.0 package comm import ( - "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/status" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/pkg/errors" ) // NetworkPeerConfig fetches the peer configuration based on a key (name or URL). func NetworkPeerConfig(cfg fab.EndpointConfig, key string) (*fab.NetworkPeer, error) { - peerCfg, err := cfg.PeerConfig(key) - if err != nil { - return nil, errors.WithMessage(err, "peer not found") + peerCfg, ok := cfg.PeerConfig(key) + if !ok { + return nil, errors.Errorf("peer not found") } // find MSP ID - networkPeers, err := cfg.NetworkPeers() - if err != nil { - return nil, errors.WithMessage(err, "unable to load network peer config") + networkPeers, ok := cfg.NetworkPeers() + if !ok { + return nil, errors.New("unable to load network peer config") } var mspID string @@ -43,23 +42,17 @@ func NetworkPeerConfig(cfg fab.EndpointConfig, key string) (*fab.NetworkPeer, er // SearchPeerConfigFromURL searches for the peer configuration based on a URL. func SearchPeerConfigFromURL(cfg fab.EndpointConfig, url string) (*fab.PeerConfig, error) { - peerCfg, err := cfg.PeerConfig(url) + peerCfg, ok := cfg.PeerConfig(url) - if peerCfg != nil { + if ok { return peerCfg, nil } - if err != nil { - s, ok := status.FromError(err) - if !ok || s.Code != status.NoMatchingPeerEntity.ToInt32() { - return nil, errors.Wrapf(err, "unable to get peer config from [%s]", url) - } - } //If the given url is already parsed URL through entity matcher, then 'cfg.PeerConfig()' //may return NoMatchingPeerEntity error. So retry with network peer URLs - networkPeers, err := cfg.NetworkPeers() - if err != nil { - return nil, errors.WithMessage(err, "unable to load network peer config") + networkPeers, ok := cfg.NetworkPeers() + if !ok { + return nil, errors.New("unable to load network peer config") } for _, peer := range networkPeers { diff --git a/pkg/fab/comm/network_test.go b/pkg/fab/comm/network_test.go index 438e84a7e6..e5952221cc 100644 --- a/pkg/fab/comm/network_test.go +++ b/pkg/fab/comm/network_test.go @@ -64,8 +64,8 @@ func TestSearchPeerConfigFromURL(t *testing.T) { t.Fatalf("Unexpected error reading config: %v", err) } - peer0Org1, err := sampleConfig.PeerConfig("peer0.org1.example.com") - assert.Nil(t, err, "supposed to get no error") + peer0Org1, ok := sampleConfig.PeerConfig("peer0.org1.example.com") + assert.True(t, ok, "peerconfig search was expected to be successful") //Positive scenario, // peerconfig should be found using matched URL diff --git a/pkg/fab/endpointconfig.go b/pkg/fab/endpointconfig.go index 9e77550c00..d462fdf92f 100644 --- a/pkg/fab/endpointconfig.go +++ b/pkg/fab/endpointconfig.go @@ -18,7 +18,6 @@ import ( "time" "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/multi" - "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/status" "github.com/hyperledger/fabric-sdk-go/pkg/common/logging" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" @@ -67,7 +66,7 @@ func ConfigFromBackend(coreBackend ...core.ConfigBackend) (fab.EndpointConfig, e channelMatchers: make(map[int]*regexp.Regexp), } - if err := config.cacheNetworkConfiguration(); err != nil { + if err := config.loadNetworkConfiguration(); err != nil { return nil, errors.WithMessage(err, "network configuration load failed") } @@ -97,13 +96,12 @@ func ConfigFromBackend(coreBackend ...core.ConfigBackend) (fab.EndpointConfig, e // EndpointConfig represents the endpoint configuration for the client type EndpointConfig struct { - backend *lookup.ConfigLookup - networkConfig *fab.NetworkConfig - tlsCertPool commtls.CertPool - networkConfigCached bool - peerMatchers map[int]*regexp.Regexp - ordererMatchers map[int]*regexp.Regexp - channelMatchers map[int]*regexp.Regexp + backend *lookup.ConfigLookup + networkConfig *fab.NetworkConfig + tlsCertPool commtls.CertPool + peerMatchers map[int]*regexp.Regexp + ordererMatchers map[int]*regexp.Regexp + channelMatchers map[int]*regexp.Regexp } // Timeout reads timeouts for the given timeout type, if type is not found in the config @@ -113,61 +111,58 @@ func (c *EndpointConfig) Timeout(tType fab.TimeoutType) time.Duration { } // MSPID returns the MSP ID for the requested organization -func (c *EndpointConfig) MSPID(org string) (string, error) { - config, err := c.NetworkConfig() - if err != nil { - return "", err +func (c *EndpointConfig) MSPID(org string) (string, bool) { + config, ok := c.NetworkConfig() + if !ok { + return "", false } // viper lowercases all key maps, org is lower case mspID := config.Organizations[strings.ToLower(org)].MSPID if mspID == "" { - return "", errors.Errorf("MSP ID is empty for org: %s", org) + return "", false } - return mspID, nil + return mspID, true } // PeerMSPID returns msp that peer belongs to -func (c *EndpointConfig) PeerMSPID(name string) (string, error) { - netConfig, err := c.NetworkConfig() - if err != nil { - return "", err +func (c *EndpointConfig) PeerMSPID(name string) (string, bool) { + netConfig, ok := c.NetworkConfig() + if !ok { + return "", false } - var mspID string - // Find organisation/msp that peer belongs to for _, org := range netConfig.Organizations { for i := 0; i < len(org.Peers); i++ { if strings.EqualFold(org.Peers[i], name) { // peer belongs to this org add org msp - mspID = org.MSPID - break - } else { - peer, err := c.findMatchingPeer(org.Peers[i]) - if err == nil && strings.EqualFold(peer, name) { - mspID = org.MSPID - break - } + return org.MSPID, true + } + + peer, ok := c.findMatchingPeer(org.Peers[i]) + if ok && strings.EqualFold(peer, name) { + return org.MSPID, true } } } - return mspID, nil + return "", false } // OrderersConfig returns a list of defined orderers -func (c *EndpointConfig) OrderersConfig() ([]fab.OrdererConfig, error) { - orderers := []fab.OrdererConfig{} - config, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) OrderersConfig() ([]fab.OrdererConfig, bool) { + + networkConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } - for name, orderer := range config.Orderers { + orderers := []fab.OrdererConfig{} + for name, orderer := range networkConfig.Orderers { - matchedOrderer := c.tryMatchingOrdererConfig(config, name) + matchedOrderer := c.tryMatchingOrdererConfig(networkConfig, name) if matchedOrderer != nil { //if found in entity matcher then use the matched one orderer = *matchedOrderer @@ -176,27 +171,27 @@ func (c *EndpointConfig) OrderersConfig() ([]fab.OrdererConfig, error) { if orderer.TLSCACerts.Path != "" { orderer.TLSCACerts.Path = pathvar.Subst(orderer.TLSCACerts.Path) } else if len(orderer.TLSCACerts.Pem) == 0 && !c.backend.GetBool("client.tlsCerts.systemCertPool") { - return nil, errors.Errorf("Orderer has no certs configured. Make sure TLSCACerts.Pem or TLSCACerts.Path is set for %s", orderer.URL) + logger.Debugf("Orderer has no certs configured. Make sure TLSCACerts.Pem or TLSCACerts.Path is set for %s", orderer.URL) + return nil, false } - orderers = append(orderers, orderer) } - return orderers, nil + return orderers, true } // OrdererConfig returns the requested orderer -func (c *EndpointConfig) OrdererConfig(nameOrURL string) (*fab.OrdererConfig, error) { - networkConfig, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) OrdererConfig(nameOrURL string) (*fab.OrdererConfig, bool) { + networkConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } - orderer, ok := networkConfig.Orderers[strings.ToLower(nameOrURL)] + orderer, ok := networkConfig.Orderers[strings.ToLower(nameOrURL)] if !ok { - ordererCfgs, err := c.OrderersConfig() - if err != nil { - return nil, err + ordererCfgs, found := c.OrderersConfig() + if !found { + return nil, false } for _, ordererCfg := range ordererCfgs { if strings.EqualFold(ordererCfg.URL, nameOrURL) { @@ -211,7 +206,7 @@ func (c *EndpointConfig) OrdererConfig(nameOrURL string) (*fab.OrdererConfig, er logger.Debugf("Could not find Orderer for [%s], trying with Entity Matchers", nameOrURL) matchingOrdererConfig := c.tryMatchingOrdererConfig(networkConfig, strings.ToLower(nameOrURL)) if matchingOrdererConfig == nil { - return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingOrdererEntity.ToInt32(), "no matching orderer config found", nil)) + return nil, false } logger.Debugf("Found matching Orderer Config for [%s]", nameOrURL) orderer = *matchingOrdererConfig @@ -221,20 +216,21 @@ func (c *EndpointConfig) OrdererConfig(nameOrURL string) (*fab.OrdererConfig, er orderer.TLSCACerts.Path = pathvar.Subst(orderer.TLSCACerts.Path) } - return &orderer, nil + return &orderer, true } // PeersConfig Retrieves the fabric peers for the specified org from the // config file provided -func (c *EndpointConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { - networkConfig, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) PeersConfig(org string) ([]fab.PeerConfig, bool) { + networkConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } peersConfig := networkConfig.Organizations[strings.ToLower(org)].Peers peers := []fab.PeerConfig{} + var err error for _, peerName := range peersConfig { p := networkConfig.Peers[strings.ToLower(peerName)] if err = c.verifyPeerConfig(p, peerName, endpoint.IsTLSEnabled(p.URL)); err != nil { @@ -252,14 +248,20 @@ func (c *EndpointConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { peers = append(peers, p) } - return peers, nil + + if len(peers) > 0 { + return peers, true + } + + return nil, false } // PeerConfig Retrieves a specific peer from the configuration by name or url -func (c *EndpointConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error) { - networkConfig, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, bool) { + + networkConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } //lookup by name in config @@ -288,7 +290,7 @@ func (c *EndpointConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error) { } if matchPeerConfig == nil { - return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingPeerEntity.ToInt32(), "no matching peer config found", nil)) + return nil, false } logger.Debugf("Found MatchingPeerConfig for name/url [%s]", nameOrURL) @@ -297,33 +299,26 @@ func (c *EndpointConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error) { matchPeerConfig.TLSCACerts.Path = pathvar.Subst(peerConfig.TLSCACerts.Path) } - return matchPeerConfig, nil + return matchPeerConfig, true } // NetworkConfig returns the network configuration defined in the config file -func (c *EndpointConfig) NetworkConfig() (*fab.NetworkConfig, error) { - if c.networkConfigCached { - return c.networkConfig, nil - } - - if err := c.cacheNetworkConfiguration(); err != nil { - return nil, errors.WithMessage(err, "network configuration load failed") - } - return c.networkConfig, nil +func (c *EndpointConfig) NetworkConfig() (*fab.NetworkConfig, bool) { + return c.networkConfig, c.networkConfig != nil } // NetworkPeers returns the network peers configuration, all the peers from all the orgs in config. -func (c *EndpointConfig) NetworkPeers() ([]fab.NetworkPeer, error) { - netConfig, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) NetworkPeers() ([]fab.NetworkPeer, bool) { + netConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } var netPeers []fab.NetworkPeer for org, orgConfig := range netConfig.Organizations { - orgPeers, err := c.PeersConfig(org) - if err != nil { - return nil, err + orgPeers, found := c.PeersConfig(org) + if !found { + continue } for _, orgPeer := range orgPeers { @@ -331,7 +326,11 @@ func (c *EndpointConfig) NetworkPeers() ([]fab.NetworkPeer, error) { } } - return netPeers, nil + if len(netPeers) > 0 { + return netPeers, true + } + + return nil, false } // MappedChannelName will return channelName if it is an original channel name in the config @@ -375,10 +374,10 @@ func (c *EndpointConfig) mappedChannelName(networkConfig *fab.NetworkConfig, cha } // ChannelConfig returns the channel configuration -func (c *EndpointConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, error) { - networkConfig, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, bool) { + networkConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } // viper lowercases all key maps @@ -386,31 +385,29 @@ func (c *EndpointConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, if !ok { matchingChannel := c.tryMatchingChannelConfig(networkConfig, name) if matchingChannel == nil { - return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingChannelEntity.ToInt32(), "no matching channel config found", nil)) + return nil, false } - return matchingChannel, nil + return matchingChannel, true } - return &ch, nil + return &ch, true } // ChannelPeers returns the channel peers configuration -func (c *EndpointConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { - netConfig, err := c.NetworkConfig() - if err != nil { - return nil, err +func (c *EndpointConfig) ChannelPeers(name string) ([]fab.ChannelPeer, bool) { + netConfig, ok := c.NetworkConfig() + if !ok { + return nil, false } peers := []fab.ChannelPeer{} - // viper lowercases all key maps chConfig, ok := netConfig.Channels[strings.ToLower(name)] if !ok { matchingChannel := c.tryMatchingChannelConfig(netConfig, name) if matchingChannel == nil { - return peers, nil + return nil, false } - // reset 'name' with the mappedChannel as it's referenced further below chConfig = *matchingChannel } @@ -429,17 +426,18 @@ func (c *EndpointConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { p = *matchingPeerConfig } - if err = c.verifyPeerConfig(p, peerName, endpoint.IsTLSEnabled(p.URL)); err != nil { - return nil, err + if err := c.verifyPeerConfig(p, peerName, endpoint.IsTLSEnabled(p.URL)); err != nil { + logger.Debugf("Verify PeerConfig failed for peer [%s], cause : [%v]", peerName, err) + return nil, false } if p.TLSCACerts.Path != "" { p.TLSCACerts.Path = pathvar.Subst(p.TLSCACerts.Path) } - mspID, err := c.PeerMSPID(peerName) - if err != nil { - return nil, errors.Errorf("failed to retrieve msp id for peer %s", peerName) + mspID, ok := c.PeerMSPID(peerName) + if !ok { + return nil, false } networkPeer := fab.NetworkPeer{PeerConfig: p, MSPID: mspID} @@ -449,28 +447,30 @@ func (c *EndpointConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { peers = append(peers, peer) } - return peers, nil + return peers, true } // ChannelOrderers returns a list of channel orderers -func (c *EndpointConfig) ChannelOrderers(name string) ([]fab.OrdererConfig, error) { +func (c *EndpointConfig) ChannelOrderers(name string) ([]fab.OrdererConfig, bool) { orderers := []fab.OrdererConfig{} - channel, err := c.ChannelConfig(name) - if err != nil || channel == nil { - return nil, errors.Errorf("Unable to retrieve channel config: %s", err) + channel, ok := c.ChannelConfig(name) + if !ok { + return nil, false } for _, chOrderer := range channel.Orderers { - orderer, err := c.OrdererConfig(chOrderer) - if err != nil || orderer == nil { - return nil, errors.Errorf("unable to retrieve orderer config: %s", err) + orderer, ok := c.OrdererConfig(chOrderer) + if !ok { + return nil, false } - orderers = append(orderers, *orderer) } - return orderers, nil + if len(orderers) == 0 { + return nil, false + } + return orderers, true } // TLSCACertPool returns the configured cert pool. If a certConfig @@ -657,7 +657,7 @@ func (c *EndpointConfig) getTimeout(tType fab.TimeoutType) time.Duration { //nol return timeout } -func (c *EndpointConfig) cacheNetworkConfiguration() error { +func (c *EndpointConfig) loadNetworkConfiguration() error { networkConfig := fab.NetworkConfig{} networkConfig.Name = c.backend.GetString("name") networkConfig.Description = c.backend.GetString("description") @@ -706,7 +706,6 @@ func (c *EndpointConfig) cacheNetworkConfiguration() error { } c.networkConfig = &networkConfig - c.networkConfigCached = true return nil } @@ -932,14 +931,15 @@ func copyPropertiesMap(origMap map[string]interface{}) map[string]interface{} { return newMap } -func (c *EndpointConfig) findMatchingPeer(peerName string) (string, error) { - networkConfig, err := c.NetworkConfig() - if err != nil { - return "", err +func (c *EndpointConfig) findMatchingPeer(peerName string) (string, bool) { + networkConfig, ok := c.NetworkConfig() + if !ok { + return "", false } + //Return if no peerMatchers are configured if len(c.peerMatchers) == 0 { - return "", errors.New("no Peer entityMatchers are found") + return "", false } //sort the keys @@ -955,24 +955,25 @@ func (c *EndpointConfig) findMatchingPeer(peerName string) (string, error) { if v.MatchString(peerName) { // get the matching matchConfig from the index number peerMatchConfig := networkConfig.EntityMatchers["peer"][k] - return peerMatchConfig.MappedHost, nil + return peerMatchConfig.MappedHost, true } } - return "", errors.WithStack(status.New(status.ClientStatus, status.NoMatchingPeerEntity.ToInt32(), "no matching peer config found", nil)) + return "", false } func (c *EndpointConfig) compileMatchers() error { - networkConfig, err := c.NetworkConfig() - if err != nil { - return err + networkConfig, ok := c.NetworkConfig() + if !ok { + return errors.New("failed to get network config") } + //return no error if entityMatchers is not configured if networkConfig.EntityMatchers == nil { return nil } - err = c.compilePeerMatcher(networkConfig) + err := c.compilePeerMatcher(networkConfig) if err != nil { return err } @@ -1047,13 +1048,13 @@ func (c *EndpointConfig) loadTLSCerts() ([]*x509.Certificate, error) { var certs []*x509.Certificate errs := multi.Errors{} - orderers, err := c.OrderersConfig() - if err != nil { - errs = append(errs, err) + orderers, ok := c.OrderersConfig() + if !ok { + errs = append(errs, errors.New("OrderersConfig not found")) } - peers, err := c.NetworkPeers() - if err != nil { - errs = append(errs, err) + peers, ok := c.NetworkPeers() + if !ok { + errs = append(errs, errors.New("failed to get network peers")) } for _, peer := range peers { cert, err := peer.TLSCACerts.TLSCert() @@ -1076,10 +1077,11 @@ func (c *EndpointConfig) loadTLSCerts() ([]*x509.Certificate, error) { // Client returns the Client config func (c *EndpointConfig) client() (*msp.ClientConfig, error) { - config, err := c.NetworkConfig() - if err != nil { - return nil, err + config, ok := c.NetworkConfig() + if !ok { + return nil, errors.New("failed to get network config") } + client := config.Client client.Organization = strings.ToLower(client.Organization) @@ -1091,9 +1093,9 @@ func (c *EndpointConfig) client() (*msp.ClientConfig, error) { } //ResetNetworkConfig clears network config cache -func (c *EndpointConfig) ResetNetworkConfig() { +func (c *EndpointConfig) ResetNetworkConfig() error { c.networkConfig = nil - c.networkConfigCached = false + return c.loadNetworkConfiguration() } func loadByteKeyOrCertFromFile(c *msp.ClientConfig, isKey bool) ([]byte, error) { diff --git a/pkg/fab/endpointconfig_test.go b/pkg/fab/endpointconfig_test.go index 19392e1972..9b2a0f7be1 100644 --- a/pkg/fab/endpointconfig_test.go +++ b/pkg/fab/endpointconfig_test.go @@ -32,7 +32,7 @@ import ( ) const ( - org0 = "org0" + org2 = "org2" org1 = "org1" configTestFilePath = "../core/config/testdata/config_test.yaml" certPath = "${GOPATH}/src/github.com/hyperledger/fabric-sdk-go/test/fixtures/fabricca/tls/certs/client/client_fabric_client.pem" @@ -88,29 +88,30 @@ func TestCAConfigFailsByNetworkConfig(t *testing.T) { } sampleEndpointConfig := endpointCfg.(*EndpointConfig) - sampleEndpointConfig.networkConfigCached = false - customBackend.KeyValueMap["channels"] = "INVALID" - _, err = sampleEndpointConfig.NetworkConfig() - if err == nil { + err = sampleEndpointConfig.ResetNetworkConfig() + assert.NotNil(t, err) + + _, ok := sampleEndpointConfig.NetworkConfig() + if ok { t.Fatal("Network config load supposed to fail") } //Testing MSPID failure scenario - mspID, err := sampleEndpointConfig.MSPID("peerorg1") - if mspID != "" || err == nil { + mspID, ok := sampleEndpointConfig.MSPID("peerorg1") + if mspID != "" || ok { t.Fatal("Get MSP ID supposed to fail") } //Testing OrdererConfig failure scenario - oConfig, err := sampleEndpointConfig.OrdererConfig("peerorg1") - if oConfig != nil || err == nil { + oConfig, ok := sampleEndpointConfig.OrdererConfig("peerorg1") + if oConfig != nil || ok { t.Fatal("Testing get OrdererConfig supposed to fail") } //Testing PeersConfig failure scenario - pConfigs, err := sampleEndpointConfig.PeersConfig("peerorg1") - if pConfigs != nil || err == nil { + pConfigs, ok := sampleEndpointConfig.PeersConfig("peerorg1") + if pConfigs != nil || ok { t.Fatal("Testing PeersConfig supposed to fail") } @@ -119,18 +120,18 @@ func TestCAConfigFailsByNetworkConfig(t *testing.T) { func checkCAConfigFailsByNetworkConfig(sampleEndpointConfig *EndpointConfig, t *testing.T) { //Testing ChannelConfig failure scenario - chConfig, err := sampleEndpointConfig.ChannelConfig("invalid") - if chConfig != nil || err == nil { + chConfig, ok := sampleEndpointConfig.ChannelConfig("invalid") + if chConfig != nil || ok { t.Fatal("Testing ChannelConfig supposed to fail") } //Testing ChannelPeers failure scenario - cpConfigs, err := sampleEndpointConfig.ChannelPeers("invalid") - if cpConfigs != nil || err == nil { + cpConfigs, ok := sampleEndpointConfig.ChannelPeers("invalid") + if cpConfigs != nil || ok { t.Fatal("Testing ChannelPeeers supposed to fail") } //Testing ChannelOrderers failure scenario - coConfigs, err := sampleEndpointConfig.ChannelOrderers("invalid") - if coConfigs != nil || err == nil { + coConfigs, ok := sampleEndpointConfig.ChannelOrderers("invalid") + if coConfigs != nil || ok { t.Fatal("Testing ChannelOrderers supposed to fail") } } @@ -309,9 +310,9 @@ func TestOrdererConfig(t *testing.T) { t.Fatal("Testing non-existing OrdererConfig failed") } - orderers, err := endpointConfig.OrderersConfig() - if err != nil { - t.Fatal(err) + orderers, ok := endpointConfig.OrderersConfig() + if !ok { + t.Fatal("Failed to get orderer config") } if orderers[0].TLSCACerts.Path != "" { @@ -329,8 +330,8 @@ func TestChannelOrderers(t *testing.T) { t.Fatal("Failed to get endpoint config from backend") } - orderers, err := endpointConfig.ChannelOrderers("mychannel") - if orderers == nil || err != nil { + orderers, ok := endpointConfig.ChannelOrderers("mychannel") + if orderers == nil || !ok { t.Fatal("Testing ChannelOrderers failed") } @@ -363,15 +364,11 @@ func testCommonConfigPeerByURL(t *testing.T, expectedConfigURL string, fetchedCo endpointConfig := config1.(*EndpointConfig) - expectedConfig, err := endpointConfig.PeerConfig(expectedConfigURL) - if err != nil { - t.Fatalf(err.Error()) - } + expectedConfig, ok := endpointConfig.PeerConfig(expectedConfigURL) + assert.True(t, ok, "getting peerconfig supposed to be successful") - fetchedConfig, err := endpointConfig.PeerConfig(fetchedConfigURL) - if err != nil { - t.Fatalf(err.Error()) - } + fetchedConfig, ok := endpointConfig.PeerConfig(fetchedConfigURL) + assert.True(t, ok, "getting peerconfig supposed to be successful") if fetchedConfig.URL == "" { t.Fatalf("Url value for the host is empty") @@ -393,15 +390,11 @@ func testCommonConfigOrderer(t *testing.T, expectedConfigHost string, fetchedCon t.Fatal("Failed to get endpoint config from backend") } - expectedConfig, err = endpointConfig.OrdererConfig(expectedConfigHost) - if err != nil { - t.Fatalf(err.Error()) - } + expectedConfig, ok := endpointConfig.OrdererConfig(expectedConfigHost) + assert.True(t, ok) - fetchedConfig, err = endpointConfig.OrdererConfig(fetchedConfigHost) - if err != nil { - t.Fatalf(err.Error()) - } + fetchedConfig, ok = endpointConfig.OrdererConfig(fetchedConfigHost) + assert.True(t, ok) if expectedConfig.URL == "" { t.Fatalf("Url value for the host is empty") @@ -487,15 +480,11 @@ func testCommonConfigChannel(t *testing.T, expectedConfigName string, fetchedCon t.Fatal("Failed to get endpoint config from backend") } - expectedConfig, err = endpointConfig.ChannelConfig(expectedConfigName) - if err != nil { - t.Fatalf(err.Error()) - } + expectedConfig, ok := endpointConfig.ChannelConfig(expectedConfigName) + assert.True(t, ok) - fetchedConfig, err = endpointConfig.ChannelConfig(fetchedConfigName) - if err != nil { - t.Fatalf(err.Error()) - } + fetchedConfig, ok = endpointConfig.ChannelConfig(fetchedConfigName) + assert.True(t, ok) return expectedConfig, fetchedConfig } @@ -511,10 +500,9 @@ func TestPeersConfig(t *testing.T) { t.Fatal("Failed to get endpoint config from backend") } - pc, err := endpointConfig.PeersConfig(org0) - if err != nil { - t.Fatalf(err.Error()) - } + pc, ok := endpointConfig.PeersConfig(org2) + fmt.Println(ok, pc) + assert.True(t, ok) for _, value := range pc { if value.URL == "" { @@ -525,10 +513,8 @@ func TestPeersConfig(t *testing.T) { } } - pc, err = endpointConfig.PeersConfig(org1) - if err != nil { - t.Fatalf(err.Error()) - } + pc, ok = endpointConfig.PeersConfig(org1) + assert.True(t, ok) for _, value := range pc { if value.URL == "" { @@ -549,15 +535,11 @@ func testCommonConfigPeer(t *testing.T, expectedConfigHost string, fetchedConfig endpointConfig := config1.(*EndpointConfig) - expectedConfig, err = endpointConfig.PeerConfig(expectedConfigHost) - if err != nil { - t.Fatalf(err.Error()) - } + expectedConfig, ok := endpointConfig.PeerConfig(expectedConfigHost) + assert.True(t, ok, "getting peerconfig supposed to be successful") - fetchedConfig, err = endpointConfig.PeerConfig(fetchedConfigHost) - if err != nil { - t.Fatalf(err.Error()) - } + fetchedConfig, ok = endpointConfig.PeerConfig(fetchedConfigHost) + assert.True(t, ok, "getting peerconfig supposed to be successful") if expectedConfig.URL == "" { t.Fatalf("Url value for the host is empty") @@ -644,10 +626,9 @@ func TestNetworkConfig(t *testing.T) { t.Fatal("Failed to get endpoint config from backend") } - conf, err := endpointConfig.NetworkConfig() - if err != nil { - t.Fatal(err) - } + conf, ok := endpointConfig.NetworkConfig() + assert.True(t, ok) + if len(conf.Orderers) == 0 { t.Fatal("Expected orderers to be set") } @@ -697,9 +678,9 @@ func TestInitConfigFromRawWithPem(t *testing.T) { endpointConfig := config1.(*EndpointConfig) - o, err := endpointConfig.OrderersConfig() - if err != nil { - t.Fatalf("Failed to load orderers from config. Error: %s", err) + o, ok := endpointConfig.OrderersConfig() + if !ok { + t.Fatalf("Failed to load orderers from config.") } if len(o) == 0 { @@ -725,9 +706,9 @@ SQtE5YgdxkUCIHReNWh/pluHTxeGu2jNCH1eh6o2ajSGeeizoapvdJbN t.Fatalf("Orderer Pem doesn't match. Expected \n'%s'\n, but got \n'%s'\n", oPem, loadedOPem) } - pc, err := endpointConfig.PeersConfig(org1) - if err != nil { - t.Fatalf(err.Error()) + pc, ok := endpointConfig.PeersConfig(org1) + if !ok { + t.Fatalf("unexpected error while getting peerConfig") } if len(pc) == 0 { t.Fatalf("peers list of %s cannot be nil or empty", org1) @@ -738,9 +719,9 @@ SQtE5YgdxkUCIHReNWh/pluHTxeGu2jNCH1eh6o2ajSGeeizoapvdJbN func checkPem(endpointConfig *EndpointConfig, t *testing.T) { peer0 := "peer0.org1.example.com" - p0, err := endpointConfig.PeerConfig(peer0) - if err != nil { - t.Fatalf("Failed to load %s of %s from the config. Error: %s", peer0, org1, err) + p0, ok := endpointConfig.PeerConfig(peer0) + if !ok { + t.Fatalf("Failed to load %s of %s from the config.", peer0, org1) } if p0 == nil { t.Fatalf("%s of %s cannot be nil", peer0, org1) @@ -802,11 +783,8 @@ func TestLoadConfigWithEmbeddedUsersWithPems(t *testing.T) { t.Fatal(err) } - conf, err := endpointConfig.NetworkConfig() - - if err != nil { - t.Fatal(err) - } + conf, ok := endpointConfig.NetworkConfig() + assert.True(t, ok) if conf.Organizations[strings.ToLower(org1)].Users[strings.ToLower("EmbeddedUser")].Cert.Pem == "" { t.Fatal("Failed to parse the embedded cert for user EmbeddedUser") @@ -837,11 +815,9 @@ func TestLoadConfigWithEmbeddedUsersWithPaths(t *testing.T) { t.Fatal(err) } - conf, err := endpointConfig.NetworkConfig() + conf, ok := endpointConfig.NetworkConfig() - if err != nil { - t.Fatal(err) - } + assert.True(t, ok) if conf.Organizations[strings.ToLower(org1)].Users[strings.ToLower("EmbeddedUserWithPaths")].Cert.Path == "" { t.Fatal("Failed to parse the embedded cert for user EmbeddedUserWithPaths") @@ -1159,10 +1135,8 @@ func TestPeerChannelConfig(t *testing.T) { } //get network config - networkConfig, err := config.NetworkConfig() - if err != nil { - t.Fatal(err) - } + networkConfig, ok := config.NetworkConfig() + assert.True(t, ok) //Test if channels config are working as expected, with time values parsed properly assert.True(t, len(networkConfig.Channels) == 3) @@ -1231,8 +1205,8 @@ func TestEndpointConfigWithMultipleBackends(t *testing.T) { assert.NotNil(t, endpointConfig, "Invalid endpoint config from multiple backends") //Get network Config - networkConfig, err := endpointConfig.NetworkConfig() - assert.Nil(t, err, "failed to get network config") + networkConfig, ok := endpointConfig.NetworkConfig() + assert.True(t, ok, "failed to get network config") assert.NotNil(t, networkConfig, "Invalid networkConfig") //Client @@ -1299,9 +1273,9 @@ func TestNetworkPeersWithEntityMatchers(t *testing.T) { } func testNetworkPeers(t *testing.T, endpointConfig fab.EndpointConfig) { - networkPeers, err := endpointConfig.NetworkPeers() + networkPeers, ok := endpointConfig.NetworkPeers() - assert.Nil(t, err, "not suppopsed to get error") + assert.True(t, ok, "supposed to be successful") assert.NotNil(t, networkPeers, "supposed to get valid network peers") assert.Equal(t, 2, len(networkPeers), "supposed to get 2 network peers") assert.NotEmpty(t, networkPeers[0].MSPID) @@ -1310,12 +1284,12 @@ func testNetworkPeers(t *testing.T, endpointConfig fab.EndpointConfig) { assert.NotEmpty(t, networkPeers[1].PeerConfig) //cross check with peer config for org1 - peerConfigOrg1, err := endpointConfig.PeersConfig("org1") - assert.Nil(t, err, "not suppopsed to get error") + peerConfigOrg1, ok := endpointConfig.PeersConfig("org1") + assert.True(t, ok, "not suppopsed to get false") //cross check with peer config for org2 - peerConfigOrg2, err := endpointConfig.PeersConfig("org2") - assert.Nil(t, err, "not suppopsed to get error") + peerConfigOrg2, ok := endpointConfig.PeersConfig("org2") + assert.True(t, ok, "not suppopsed to get false") if networkPeers[0].MSPID == "Org1MSP" { assert.Equal(t, peerConfigOrg1[0], networkPeers[0].PeerConfig) diff --git a/pkg/fab/events/endpoint/endpoint_test.go b/pkg/fab/events/endpoint/endpoint_test.go index c7641957a1..103089b8ef 100644 --- a/pkg/fab/events/endpoint/endpoint_test.go +++ b/pkg/fab/events/endpoint/endpoint_test.go @@ -141,9 +141,9 @@ func newMockConfig(channelPeers ...fab.ChannelPeer) *mockConfig { } } -func (c *mockConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { +func (c *mockConfig) ChannelPeers(name string) ([]fab.ChannelPeer, bool) { fmt.Printf("mockConfig.ChannelPeers - returning %#v", c.channelPeers) - return c.channelPeers, nil + return c.channelPeers, true } func newMockContext() *fabmocks.MockContext { diff --git a/pkg/fab/events/endpoint/endpointdiscovery.go b/pkg/fab/events/endpoint/endpointdiscovery.go index c6346ebca4..389a4baf43 100644 --- a/pkg/fab/events/endpoint/endpointdiscovery.go +++ b/pkg/fab/events/endpoint/endpointdiscovery.go @@ -8,7 +8,6 @@ package endpoint import ( "github.com/hyperledger/fabric-sdk-go/pkg/client/common/discovery" - "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/status" "github.com/hyperledger/fabric-sdk-go/pkg/common/logging" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" @@ -61,9 +60,9 @@ func (p *DiscoveryProvider) CreateDiscoveryService(channelID string) (fab.Discov target = discovery.NewDiscoveryFilterService(target, p.filter) } - chpeers, err := p.ctx.EndpointConfig().ChannelPeers(channelID) - if err != nil { - return nil, errors.Wrapf(err, "unable to get channel peers for channel [%s]", channelID) + chpeers, ok := p.ctx.EndpointConfig().ChannelPeers(channelID) + if !ok { + return nil, errors.Errorf("unable to get channel peers for channel [%s]", channelID) } return &discoveryService{ @@ -93,19 +92,15 @@ func (s *discoveryService) GetPeers() ([]fab.Peer, error) { var peerConfig *fab.PeerConfig var err error + var found bool chPeer := s.getChannelPeer(peer.URL()) if chPeer != nil { peerConfig = &chPeer.PeerConfig } else { - peerConfig, err = s.ctx.EndpointConfig().PeerConfig(peer.URL()) - if err != nil { - errStatus, ok := status.FromError(err) - if ok && errStatus.Code == status.NoMatchingPeerEntity.ToInt32() { - logger.Debugf("no peer found for URL :%s", peer.URL()) - continue - } - return nil, errors.Wrapf(err, "unable to get peer config from [%s]", peer.URL()) + peerConfig, found = s.ctx.EndpointConfig().PeerConfig(peer.URL()) + if !found { + continue } chPeer = s.getChannelPeer(peerConfig.URL) } diff --git a/pkg/fab/mocks/mockconfig.go b/pkg/fab/mocks/mockconfig.go index 2ed5c29582..783554bbcd 100644 --- a/pkg/fab/mocks/mockconfig.go +++ b/pkg/fab/mocks/mockconfig.go @@ -119,23 +119,23 @@ func (c *MockConfig) Timeout(arg fab.TimeoutType) time.Duration { } // PeersConfig Retrieves the fabric peers from the config file provided -func (c *MockConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { - return nil, nil +func (c *MockConfig) PeersConfig(org string) ([]fab.PeerConfig, bool) { + return nil, false } // PeerConfig Retrieves a specific peer from the configuration by org and name -func (c *MockConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error) { +func (c *MockConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, bool) { if nameOrURL == "invalid" { - return nil, errors.New("no peer") + return nil, false } if c.customPeerCfg != nil { - return c.customPeerCfg, nil + return c.customPeerCfg, true } cfg := fab.PeerConfig{ URL: "example.com", } - return &cfg, nil + return &cfg, true } // TLSCACertPool ... @@ -168,10 +168,9 @@ func (c *MockConfig) SecurityProviderLibPath() string { } // OrderersConfig returns a list of defined orderers -func (c *MockConfig) OrderersConfig() ([]fab.OrdererConfig, error) { - oConfig, err := c.OrdererConfig("") - - return []fab.OrdererConfig{*oConfig}, err +func (c *MockConfig) OrderersConfig() ([]fab.OrdererConfig, bool) { + oConfig, _ := c.OrdererConfig("") + return []fab.OrdererConfig{*oConfig}, true } //SetCustomNetworkPeerCfg sets custom orderer config for unit-tests @@ -195,28 +194,28 @@ func (c *MockConfig) SetCustomRandomOrdererCfg(customRandomOrdererCfg *fab.Order } // OrdererConfig not implemented -func (c *MockConfig) OrdererConfig(name string) (*fab.OrdererConfig, error) { +func (c *MockConfig) OrdererConfig(name string) (*fab.OrdererConfig, bool) { if name == "Invalid" { - return nil, errors.New("no orderer") + return nil, false } if c.customOrdererCfg != nil { - return c.customOrdererCfg, nil + return c.customOrdererCfg, true } oConfig := fab.OrdererConfig{ URL: "example.com", } - return &oConfig, nil + return &oConfig, true } // MSPID not implemented -func (c *MockConfig) MSPID(org string) (string, error) { - return "", nil +func (c *MockConfig) MSPID(org string) (string, bool) { + return "", false } // PeerMSPID not implemented -func (c *MockConfig) PeerMSPID(name string) (string, error) { - return "", nil +func (c *MockConfig) PeerMSPID(name string) (string, bool) { + return "", false } // KeyStorePath ... @@ -240,20 +239,20 @@ func (c *MockConfig) CryptoConfigPath() string { } // NetworkConfig not implemented -func (c *MockConfig) NetworkConfig() (*fab.NetworkConfig, error) { - return nil, nil +func (c *MockConfig) NetworkConfig() (*fab.NetworkConfig, bool) { + return nil, false } // ChannelConfig returns the channel configuration -func (c *MockConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, error) { - return &fab.ChannelNetworkConfig{Policies: fab.ChannelPolicies{}}, nil +func (c *MockConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, bool) { + return &fab.ChannelNetworkConfig{Policies: fab.ChannelPolicies{}}, true } // ChannelPeers returns the channel peers configuration -func (c *MockConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { +func (c *MockConfig) ChannelPeers(name string) ([]fab.ChannelPeer, bool) { if name == "noChannelPeers" { - return nil, nil + return nil, false } peerChCfg := fab.PeerChannelConfig{EndorsingPeer: true, ChaincodeQuery: true, LedgerQuery: true, EventSource: true} @@ -262,26 +261,26 @@ func (c *MockConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { } mockPeer := fab.ChannelPeer{PeerChannelConfig: peerChCfg, NetworkPeer: fab.NetworkPeer{PeerConfig: fab.PeerConfig{URL: "example.com"}}} - return []fab.ChannelPeer{mockPeer}, nil + return []fab.ChannelPeer{mockPeer}, true } // ChannelOrderers returns a list of channel orderers -func (c *MockConfig) ChannelOrderers(name string) ([]fab.OrdererConfig, error) { +func (c *MockConfig) ChannelOrderers(name string) ([]fab.OrdererConfig, bool) { if name == "Invalid" { - return nil, errors.New("no orderer") + return nil, false } - oConfig, err := c.OrdererConfig("") + oConfig, _ := c.OrdererConfig("") - return []fab.OrdererConfig{*oConfig}, err + return []fab.OrdererConfig{*oConfig}, true } // NetworkPeers returns the mock network peers configuration -func (c *MockConfig) NetworkPeers() ([]fab.NetworkPeer, error) { +func (c *MockConfig) NetworkPeers() ([]fab.NetworkPeer, bool) { if c.customNetworkPeerCfg != nil { - return c.customNetworkPeerCfg, nil + return c.customNetworkPeerCfg, true } - return nil, errors.New("no config") + return nil, false } // SecurityProvider ... diff --git a/pkg/fab/opts.go b/pkg/fab/opts.go index 64ba4c0db3..c2e1173186 100644 --- a/pkg/fab/opts.go +++ b/pkg/fab/opts.go @@ -47,57 +47,57 @@ type timeout interface { // mspID interface allows to uniquely override EndpointConfig interface's MSPID() function type mspID interface { - MSPID(org string) (string, error) + MSPID(org string) (string, bool) } // peerMSPID interface allows to uniquely override EndpointConfig interface's PeerMSPID() function type peerMSPID interface { - PeerMSPID(name string) (string, error) + PeerMSPID(name string) (string, bool) } // orderersConfig interface allows to uniquely override EndpointConfig interface's OrderersConfig() function type orderersConfig interface { - OrderersConfig() ([]fab.OrdererConfig, error) + OrderersConfig() ([]fab.OrdererConfig, bool) } // ordererConfig interface allows to uniquely override EndpointConfig interface's OrdererConfig() function type ordererConfig interface { - OrdererConfig(name string) (*fab.OrdererConfig, error) + OrdererConfig(name string) (*fab.OrdererConfig, bool) } // peersConfig interface allows to uniquely override EndpointConfig interface's PeersConfig() function type peersConfig interface { - PeersConfig(org string) ([]fab.PeerConfig, error) + PeersConfig(org string) ([]fab.PeerConfig, bool) } // peerConfig interface allows to uniquely override EndpointConfig interface's PeerConfig() function type peerConfig interface { - PeerConfig(nameOrURL string) (*fab.PeerConfig, error) + PeerConfig(nameOrURL string) (*fab.PeerConfig, bool) } // networkConfig interface allows to uniquely override EndpointConfig interface's NetworkConfig() function type networkConfig interface { - NetworkConfig() (*fab.NetworkConfig, error) + NetworkConfig() (*fab.NetworkConfig, bool) } // networkPeers interface allows to uniquely override EndpointConfig interface's NetworkPeers() function type networkPeers interface { - NetworkPeers() ([]fab.NetworkPeer, error) + NetworkPeers() ([]fab.NetworkPeer, bool) } // channelConfig interface allows to uniquely override EndpointConfig interface's ChannelConfig() function type channelConfig interface { - ChannelConfig(name string) (*fab.ChannelNetworkConfig, error) + ChannelConfig(name string) (*fab.ChannelNetworkConfig, bool) } // channelPeers interface allows to uniquely override EndpointConfig interface's ChannelPeers() function type channelPeers interface { - ChannelPeers(name string) ([]fab.ChannelPeer, error) + ChannelPeers(name string) ([]fab.ChannelPeer, bool) } // channelOrderers interface allows to uniquely override EndpointConfig interface's ChannelOrderers() function type channelOrderers interface { - ChannelOrderers(name string) ([]fab.OrdererConfig, error) + ChannelOrderers(name string) ([]fab.OrdererConfig, bool) } // tlsCACertPool interface allows to uniquely override EndpointConfig interface's TLSCACertPool() function diff --git a/pkg/fab/opts_test.go b/pkg/fab/opts_test.go index b968ef96e9..23d5ecb25a 100644 --- a/pkg/fab/opts_test.go +++ b/pkg/fab/opts_test.go @@ -67,16 +67,16 @@ func TestCreateCustomEndpointConfig(t *testing.T) { if tmout < 0 { t.Fatalf("EndpointConfig was supposed to have Timeout function overridden from Options but was not %+v. Timeout: %s", eco, tmout) } - m, err := eco.MSPID("") - if err != nil { - t.Fatalf("MSPID returned unexpected error %s", err) + m, ok := eco.MSPID("") + if !ok { + t.Fatalf("Failed to get MSP ID") } if m != "testMSP" { t.Fatalf("MSPID did not return expected interface value. Expected: %s, Received: %s", "testMSP", m) } - m, err = eco.PeerMSPID("") - if err != nil { - t.Fatalf("PeerMSPID returned unexpected error %s", err) + m, ok = eco.PeerMSPID("") + if !ok { + t.Fatalf("PeerMSPID supposed to pass") } if m != "testPeerMSP" { t.Fatalf("MSPID did not return expected interface value. Expected: %s, Received: %s", "testPeerMSP", m) @@ -103,9 +103,9 @@ func TestCreateCustomEndpointConfigRemainingFunctions(t *testing.T) { t.Fatalf("build ConfigEndpointOption returned is nil") } // verify that their functions are available - p, err := eco.ChannelPeers("") - if err != nil { - t.Fatalf("ChannelPeers returned unexpected error %s", err) + p, ok := eco.ChannelPeers("") + if !ok { + t.Fatalf("ChannelPeers expected to succeed") } if len(p) != 1 { t.Fatalf("ChannelPeers did not return expected interface value. Expected: 1 ChannelPeer, Received: %d", len(p)) @@ -157,9 +157,9 @@ func TestCreateCustomEndpointConfigWithSomeDefaultFunctions(t *testing.T) { if tmout != expectedTimeout { t.Fatalf("EndpointConfig was supposed to have Timeout function overridden from Options but was not %+v. Timeout: [expected: %s, received: %s]", eco, expectedTimeout, tmout) } - m, err := endpointConfigOptionWithSomeDefaults.MSPID("") - if err != nil { - t.Fatalf("MSPID returned unexpected error %s", err) + m, ok := endpointConfigOptionWithSomeDefaults.MSPID("") + if !ok { + t.Fatalf("Failed to get MSPID") } if m != "testMSP" { t.Fatalf("MSPID did not return expected interface value. Expected: %s, Received: %s", "testMSP", m) @@ -268,68 +268,68 @@ func (m *mockTimeoutConfig) Timeout(timeoutType fab.TimeoutType) time.Duration { type mockMspID struct{} -func (m *mockMspID) MSPID(org string) (string, error) { - return "testMSP", nil +func (m *mockMspID) MSPID(org string) (string, bool) { + return "testMSP", true } type mockPeerMSPID struct{} -func (m *mockPeerMSPID) PeerMSPID(name string) (string, error) { - return "testPeerMSP", nil +func (m *mockPeerMSPID) PeerMSPID(name string) (string, bool) { + return "testPeerMSP", true } type mockrderersConfig struct{} -func (m *mockrderersConfig) OrderersConfig() ([]fab.OrdererConfig, error) { - return []fab.OrdererConfig{{URL: "orderer1.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}}, nil +func (m *mockrderersConfig) OrderersConfig() ([]fab.OrdererConfig, bool) { + return []fab.OrdererConfig{{URL: "orderer1.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}}, true } type mockOrdererConfig struct{} -func (m *mockOrdererConfig) OrdererConfig(name string) (*fab.OrdererConfig, error) { - return &fab.OrdererConfig{URL: "o.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, nil +func (m *mockOrdererConfig) OrdererConfig(name string) (*fab.OrdererConfig, bool) { + return &fab.OrdererConfig{URL: "o.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, true } type mockPeersConfig struct{} -func (m *mockPeersConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { - return []fab.PeerConfig{{URL: "peer.com", EventURL: "event.peer.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}}, nil +func (m *mockPeersConfig) PeersConfig(org string) ([]fab.PeerConfig, bool) { + return []fab.PeerConfig{{URL: "peer.com", EventURL: "event.peer.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}}, true } type mockPeerConfig struct{} -func (m *mockPeerConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error) { - return &fab.PeerConfig{URL: "p.com", EventURL: "event.p.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, nil +func (m *mockPeerConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, bool) { + return &fab.PeerConfig{URL: "p.com", EventURL: "event.p.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, true } type mockNetworkConfig struct{} -func (m *mockNetworkConfig) NetworkConfig() (*fab.NetworkConfig, error) { - return &fab.NetworkConfig{}, nil +func (m *mockNetworkConfig) NetworkConfig() (*fab.NetworkConfig, bool) { + return &fab.NetworkConfig{}, true } type mockNetworkPeers struct{} -func (m *mockNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, error) { - return []fab.NetworkPeer{{PeerConfig: fab.PeerConfig{URL: "p.com", EventURL: "event.p.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, MSPID: ""}}, nil +func (m *mockNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, bool) { + return []fab.NetworkPeer{{PeerConfig: fab.PeerConfig{URL: "p.com", EventURL: "event.p.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, MSPID: ""}}, true } type mockChannelConfig struct{} -func (m *mockChannelConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, error) { - return &fab.ChannelNetworkConfig{}, nil +func (m *mockChannelConfig) ChannelConfig(name string) (*fab.ChannelNetworkConfig, bool) { + return &fab.ChannelNetworkConfig{}, true } type mockChannelPeers struct{} -func (m *mockChannelPeers) ChannelPeers(name string) ([]fab.ChannelPeer, error) { - return []fab.ChannelPeer{{}}, nil +func (m *mockChannelPeers) ChannelPeers(name string) ([]fab.ChannelPeer, bool) { + return []fab.ChannelPeer{{}}, true } type mockChannelOrderers struct{} -func (m *mockChannelOrderers) ChannelOrderers(name string) ([]fab.OrdererConfig, error) { - return []fab.OrdererConfig{}, nil +func (m *mockChannelOrderers) ChannelOrderers(name string) ([]fab.OrdererConfig, bool) { + return []fab.OrdererConfig{}, true } type mockTLSCACertPool struct{} diff --git a/pkg/fab/orderer/orderer.go b/pkg/fab/orderer/orderer.go index 67efc96467..74e532e670 100644 --- a/pkg/fab/orderer/orderer.go +++ b/pkg/fab/orderer/orderer.go @@ -174,9 +174,9 @@ func FromOrdererConfig(ordererCfg *fab.OrdererConfig) Option { // by name from the apiconfig.Config supplied to the constructor, and then constructs a new orderer from it func FromOrdererName(name string) Option { return func(o *Orderer) error { - ordererCfg, err := o.config.OrdererConfig(name) - if err != nil { - return errors.Wrapf(err, "orderer config not found for orderer : %s", name) + ordererCfg, found := o.config.OrdererConfig(name) + if !found { + return errors.Errorf("orderer config not found for orderer : %s", name) } return FromOrdererConfig(ordererCfg)(o) diff --git a/pkg/fabsdk/fabsdk_test.go b/pkg/fabsdk/fabsdk_test.go index c14720fd2a..4a79cc1018 100644 --- a/pkg/fabsdk/fabsdk_test.go +++ b/pkg/fabsdk/fabsdk_test.go @@ -311,25 +311,25 @@ func TestWithConfigEndpoint(t *testing.T) { // some functions by calling WithEndpointConfig(np, mo) above endpointConfig := sdk.opts.endpointConfig - network, err := endpointConfig.NetworkPeers() - if err != nil { - t.Fatalf("Error getting NetworkPeer from config: %s", err) + network, ok := endpointConfig.NetworkPeers() + if !ok { + t.Fatal("Error getting NetworkPeer from config") } - expectedNetwork, err := np.NetworkPeers() - if err != nil { - t.Fatalf("Error getting extecd NetworkPeer from direct config: %s", err) + expectedNetwork, ok := np.NetworkPeers() + if !ok { + t.Fatal("Error getting extecd NetworkPeer from direct config") } if !reflect.DeepEqual(network, expectedNetwork) { t.Fatalf("Expected NetworkPeer was not returned by the sdk's config. Expected: %s, Received: %s", expectedNetwork, network) } - channelOrderers, err := endpointConfig.ChannelOrderers("") - if err != nil { - t.Fatalf("Error getting ChannelOrderers from config: %s", err) + channelOrderers, ok := endpointConfig.ChannelOrderers("") + if !ok { + t.Fatal("Error getting ChannelOrderers from config") } - expectedChannelOrderers, err := co.ChannelOrderers("") - if err != nil { - t.Fatalf("Error getting extecd ChannelOrderers from direct config: %s", err) + expectedChannelOrderers, ok := co.ChannelOrderers("") + if !ok { + t.Fatal("Error getting extecd ChannelOrderers from direct config") } if !reflect.DeepEqual(channelOrderers, expectedChannelOrderers) { t.Fatalf("Expected ChannelOrderers was not returned by the sdk's config. Expected: %s, Received: %s", expectedChannelOrderers, channelOrderers) @@ -353,12 +353,12 @@ func TestWithConfigEndpointAndBadOpt(t *testing.T) { type MockNetworkPeers struct{} -func (M *MockNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, error) { - return []fab.NetworkPeer{{PeerConfig: fab.PeerConfig{URL: "p.com", EventURL: "event.p.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, MSPID: ""}}, nil +func (M *MockNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, bool) { + return []fab.NetworkPeer{{PeerConfig: fab.PeerConfig{URL: "p.com", EventURL: "event.p.com", GRPCOptions: nil, TLSCACerts: endpoint.TLSConfig{Path: "", Pem: ""}}, MSPID: ""}}, true } type MockChannelOrderers struct{} -func (M *MockChannelOrderers) ChannelOrderers(name string) ([]fab.OrdererConfig, error) { - return []fab.OrdererConfig{}, nil +func (M *MockChannelOrderers) ChannelOrderers(name string) ([]fab.OrdererConfig, bool) { + return []fab.OrdererConfig{}, true } diff --git a/pkg/fabsdk/provider/msppvdr/msppvdr.go b/pkg/fabsdk/provider/msppvdr/msppvdr.go index dac7df5f14..08ec419d9b 100644 --- a/pkg/fabsdk/provider/msppvdr/msppvdr.go +++ b/pkg/fabsdk/provider/msppvdr/msppvdr.go @@ -27,9 +27,9 @@ type MSPProvider struct { func New(endpointConfig fab.EndpointConfig, cryptoSuite core.CryptoSuite, userStore msp.UserStore) (*MSPProvider, error) { identityManager := make(map[string]msp.IdentityManager) - netConfig, err := endpointConfig.NetworkConfig() - if err != nil { - return nil, errors.WithMessage(err, "failed to retrieve network config") + netConfig, ok := endpointConfig.NetworkConfig() + if !ok { + return nil, errors.New("failed to retrieve network config") } for orgName := range netConfig.Organizations { mgr, err := mspimpl.NewIdentityManager(orgName, userStore, cryptoSuite, endpointConfig) diff --git a/pkg/msp/caclient.go b/pkg/msp/caclient.go index 0b60a6be24..b44f0f3668 100644 --- a/pkg/msp/caclient.go +++ b/pkg/msp/caclient.go @@ -35,9 +35,9 @@ type CAClientImpl struct { // NewCAClient creates a new CA CAClient instance func NewCAClient(orgName string, ctx contextApi.Client) (*CAClientImpl, error) { - netConfig, err := ctx.EndpointConfig().NetworkConfig() - if err != nil { - return nil, errors.Wrapf(err, "network config retrieval failed") + netConfig, ok := ctx.EndpointConfig().NetworkConfig() + if !ok { + return nil, errors.New("network config retrieval failed") } if orgName == "" { @@ -65,6 +65,7 @@ func NewCAClient(orgName string, ctx contextApi.Client) (*CAClientImpl, error) { var caConfig *msp.CAConfig var adapter *fabricCAAdapter var registrar msp.EnrollCredentials + var err error // Currently, an organization can be associated with only one CA caName := orgConfig.CertificateAuthorities[0] diff --git a/pkg/msp/enrollment_test.go b/pkg/msp/enrollment_test.go index 3e8952308a..c52c9eca44 100644 --- a/pkg/msp/enrollment_test.go +++ b/pkg/msp/enrollment_test.go @@ -76,9 +76,9 @@ func TestGetSigningIdentityWithEnrollment(t *testing.T) { if err != nil { t.Fatalf("Unable to retrieve client config: %v", err) } - netConfig, err := endpointConfig.NetworkConfig() - if err != nil { - t.Fatalf("NetworkConfig failed: %s", err) + netConfig, ok := endpointConfig.NetworkConfig() + if !ok { + t.Fatal("Failed to get network config") } orgName := "Org1" orgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)] diff --git a/pkg/msp/getsigid.go b/pkg/msp/getsigid.go index 5c49eed18f..251d221f14 100644 --- a/pkg/msp/getsigid.go +++ b/pkg/msp/getsigid.go @@ -107,9 +107,9 @@ func (mgr *IdentityManager) GetUser(username string) (*User, error) { //nolint if privateKey == nil { return nil, fmt.Errorf("unable to find private key for user [%s]", username) } - mspID, err := mgr.config.MSPID(mgr.orgName) - if err != nil { - return nil, errors.WithMessage(err, "MSP ID config read failed") + mspID, ok := mgr.config.MSPID(mgr.orgName) + if !ok { + return nil, errors.New("MSP ID config read failed") } u = &User{ id: username, diff --git a/pkg/msp/getsigid_test.go b/pkg/msp/getsigid_test.go index 0f5139784c..220f910b86 100644 --- a/pkg/msp/getsigid_test.go +++ b/pkg/msp/getsigid_test.go @@ -113,9 +113,9 @@ func getConfigs(t *testing.T) (core.CryptoSuiteConfig, providersFab.EndpointConf if err != nil { panic(fmt.Sprintf("Failed to read config: %v", err)) } - netConfig, err := endpointConfig.NetworkConfig() - if err != nil { - t.Fatalf("Failed to setup netConfig: %s", err) + netConfig, ok := endpointConfig.NetworkConfig() + if !ok { + t.Fatal("Failed to setup netConfig") } orgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)] if !ok { diff --git a/pkg/msp/identityconfig.go b/pkg/msp/identityconfig.go index 9eb679c6df..1fdd94ad28 100644 --- a/pkg/msp/identityconfig.go +++ b/pkg/msp/identityconfig.go @@ -206,7 +206,11 @@ func (c *IdentityConfig) networkConfig() (*fab.NetworkConfig, error) { if c.endpointConfig == nil { return nil, errors.New("network config not initialized for identity config") } - return c.endpointConfig.NetworkConfig() + networkConfig, ok := c.endpointConfig.NetworkConfig() + if !ok { + return nil, errors.New("network config not initialized for identity config") + } + return networkConfig, nil } func (c *IdentityConfig) tryMatchingCAConfig(networkConfig *fab.NetworkConfig, caName string) (*msp.CAConfig, string) { @@ -275,12 +279,13 @@ func (c *IdentityConfig) getPortIfPresent(url string) (int, bool) { } func (c *IdentityConfig) compileMatchers() error { - networkConfig, err := c.endpointConfig.NetworkConfig() - if err != nil { - return err + networkConfig, ok := c.endpointConfig.NetworkConfig() + if !ok { + return errors.New("failed to get network config") } if networkConfig.EntityMatchers["certificateauthority"] != nil { certMatchersConfig := networkConfig.EntityMatchers["certificateauthority"] + var err error for i := 0; i < len(certMatchersConfig); i++ { if certMatchersConfig[i].Pattern != "" { c.caMatchers[i], err = regexp.Compile(certMatchersConfig[i].Pattern) diff --git a/pkg/msp/identityconfig_test.go b/pkg/msp/identityconfig_test.go index efdb3b4915..01011a9f2e 100644 --- a/pkg/msp/identityconfig_test.go +++ b/pkg/msp/identityconfig_test.go @@ -61,9 +61,9 @@ func TestCAConfigFailsByNetworkConfig(t *testing.T) { } sampleIdentityConfig := identityCfg.(*IdentityConfig) - sampleIdentityConfig.endpointConfig.(*fab.EndpointConfig).ResetNetworkConfig() - customBackend.KeyValueMap["channels"] = "INVALID" + err = sampleIdentityConfig.endpointConfig.(*fab.EndpointConfig).ResetNetworkConfig() + assert.NotNil(t, err) _, err = sampleIdentityConfig.networkConfig() if err == nil { t.Fatal("Network config load supposed to fail") @@ -179,13 +179,13 @@ func TestInitConfigFromRawWithPem(t *testing.T) { idConfig := config.(*IdentityConfig) - o, err := idConfig.endpointConfig.OrderersConfig() - if err != nil { - t.Fatalf("Failed to load orderers from config. Error: %s", err) + o, ok := idConfig.endpointConfig.OrderersConfig() + if !ok { + t.Fatal("Failed to load orderers from config") } if len(o) == 0 { - t.Fatalf("orderer cannot be nil or empty") + t.Fatal("orderer cannot be nil or empty") } oPem := `-----BEGIN CERTIFICATE----- @@ -207,10 +207,8 @@ SQtE5YgdxkUCIHReNWh/pluHTxeGu2jNCH1eh6o2ajSGeeizoapvdJbN t.Fatalf("Orderer Pem doesn't match. Expected \n'%s'\n, but got \n'%s'\n", oPem, loadedOPem) } - pc, err := idConfig.endpointConfig.PeersConfig(org1) - if err != nil { - t.Fatalf(err.Error()) - } + pc, ok := idConfig.endpointConfig.PeersConfig(org1) + assert.True(t, ok) if len(pc) == 0 { t.Fatalf("peers list of %s cannot be nil or empty", org1) } @@ -237,10 +235,8 @@ SQtE5YgdxkUCIHReNWh/pluHTxeGu2jNCH1eh6o2ajSGeeizoapvdJbN } func checkPeerPem(org string, idConfig *IdentityConfig, peer string, t *testing.T) { - p0, err := idConfig.endpointConfig.PeerConfig(peer) - if err != nil { - t.Fatalf("Failed to load %s of %s from the config. Error: %s", peer, org, err) - } + p0, ok := idConfig.endpointConfig.PeerConfig(peer) + assert.True(t, ok) if p0 == nil { t.Fatalf("%s of %s cannot be nil", peer, org) } @@ -367,14 +363,13 @@ func TestCAConfig(t *testing.T) { assert.True(t, pathvar.Subst(val.(string)) == identityConfig.endpointConfig.CryptoConfigPath(), "Incorrect crypto config path", t) //Testing MSPID - mspID, err := identityConfig.endpointConfig.MSPID(org1) - assert.Nil(t, err, "Get MSP ID failed") + mspID, ok := identityConfig.endpointConfig.MSPID(org1) + assert.True(t, ok, "Get MSP ID failed") assert.True(t, mspID == "Org1MSP", "Get MSP ID failed") // testing empty OrgMSP - _, err = identityConfig.endpointConfig.MSPID("dummyorg1") - assert.NotNil(t, err, "Get MSP ID did not fail for dummyorg1") - assert.True(t, err.Error() == "MSP ID is empty for org: dummyorg1", "Get MSP ID did not fail for dummyorg1") + _, ok = identityConfig.endpointConfig.MSPID("dummyorg1") + assert.False(t, ok, "Get MSP ID did not fail for dummyorg1") //Testing CAConfig caConfig, err := identityConfig.CAConfig(org1) @@ -419,14 +414,13 @@ func TestCAConfigWithCustomEndpointConfig(t *testing.T) { assert.True(t, pathvar.Subst(val.(string)) == identityConfig.endpointConfig.CryptoConfigPath(), "Incorrect crypto config path", t) //Testing MSPID - mspID, err := identityConfig.endpointConfig.MSPID(org1) - assert.Nil(t, err, "Get MSP ID failed") + mspID, ok := identityConfig.endpointConfig.MSPID(org1) + assert.True(t, ok, "Get MSP ID failed") assert.True(t, mspID == "Org1MSP", "Get MSP ID failed") // testing empty OrgMSP - _, err = identityConfig.endpointConfig.MSPID("dummyorg1") - assert.NotNil(t, err, "Get MSP ID did not fail for dummyorg1") - assert.True(t, err.Error() == "MSP ID is empty for org: dummyorg1", "Get MSP ID did not fail for dummyorg1") + _, ok = identityConfig.endpointConfig.MSPID("dummyorg1") + assert.False(t, ok, "Get MSP ID did not fail for dummyorg1") //Testing CAConfig caConfig, err := identityConfig.CAConfig(org1) @@ -572,11 +566,11 @@ type customEndpointConfig struct { fabImpl.EndpointConfig } -func (c *customEndpointConfig) NetworkConfig() (*fabImpl.NetworkConfig, error) { - nConfig, err := c.EndpointConfig.NetworkConfig() - if err != nil { - return nil, err +func (c *customEndpointConfig) NetworkConfig() (*fabImpl.NetworkConfig, bool) { + nConfig, ok := c.EndpointConfig.NetworkConfig() + if !ok { + return nil, ok } nConfig.Client.Organization = "CUSTOM-ORG1" - return nConfig, nil + return nConfig, true } diff --git a/pkg/msp/identitymgr.go b/pkg/msp/identitymgr.go index f2d68affb6..4193c711b4 100644 --- a/pkg/msp/identitymgr.go +++ b/pkg/msp/identitymgr.go @@ -33,9 +33,9 @@ type IdentityManager struct { // NewIdentityManager creates a new instance of IdentityManager func NewIdentityManager(orgName string, userStore msp.UserStore, cryptoSuite core.CryptoSuite, endpointConfig fab.EndpointConfig) (*IdentityManager, error) { - netConfig, err := endpointConfig.NetworkConfig() - if err != nil { - return nil, errors.Wrapf(err, "network config retrieval failed") + netConfig, ok := endpointConfig.NetworkConfig() + if !ok { + return nil, errors.New("network config retrieval failed") } // viper keys are case insensitive @@ -53,6 +53,7 @@ func NewIdentityManager(orgName string, userStore msp.UserStore, cryptoSuite cor orgCryptoPathTemplate := orgConfig.CryptoPath if orgCryptoPathTemplate != "" { + var err error if !filepath.IsAbs(orgCryptoPathTemplate) { orgCryptoPathTemplate = filepath.Join(endpointConfig.CryptoConfigPath(), orgCryptoPathTemplate) } diff --git a/pkg/msp/main_test.go b/pkg/msp/main_test.go index ed2424bb35..34f47156e3 100644 --- a/pkg/msp/main_test.go +++ b/pkg/msp/main_test.go @@ -103,9 +103,9 @@ func (f *textFixture) setup(configBackend ...core.ConfigBackend) { //nolint f.userStore = userStoreFromConfig(nil, f.identityConfig) identityManagers := make(map[string]msp.IdentityManager) - netConfig, err := f.endpointConfig.NetworkConfig() - if err != nil { - panic(fmt.Sprintf("failed to get network config: %v", err)) + netConfig, ok := f.endpointConfig.NetworkConfig() + if !ok { + panic("failed to get network config") } for orgName := range netConfig.Organizations { mgr, err1 := NewIdentityManager(orgName, f.userStore, f.cryptoSuite, f.endpointConfig) @@ -168,15 +168,15 @@ func cleanupTestPath(t *testing.T, storePath string) { } func mspIDByOrgName(t *testing.T, c fab.EndpointConfig, orgName string) string { - netConfig, err := c.NetworkConfig() - if err != nil { - t.Fatalf("network config retrieval failed: %v", err) + netConfig, ok := c.NetworkConfig() + if !ok { + t.Fatal("network config retrieval failed") } // viper keys are case insensitive orgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)] if !ok { - t.Fatalf("org config retrieval failed: %v", err) + t.Fatal("org config retrieval failed ") } return orgConfig.MSPID } diff --git a/pkg/msp/test/mockmspapi/mockmspapi.gen.go b/pkg/msp/test/mockmspapi/mockmspapi.gen.go index bcf3d996b5..43785e2be8 100644 --- a/pkg/msp/test/mockmspapi/mockmspapi.gen.go +++ b/pkg/msp/test/mockmspapi/mockmspapi.gen.go @@ -34,6 +34,19 @@ func (m *MockCAClient) EXPECT() *MockCAClientMockRecorder { return m.recorder } +// CreateIdentity mocks base method +func (m *MockCAClient) CreateIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) { + ret := m.ctrl.Call(m, "CreateIdentity", arg0) + ret0, _ := ret[0].(*api.IdentityResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateIdentity indicates an expected call of CreateIdentity +func (mr *MockCAClientMockRecorder) CreateIdentity(arg0 interface{}) *gomock.Call { + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateIdentity", reflect.TypeOf((*MockCAClient)(nil).CreateIdentity), arg0) +} + // Enroll mocks base method func (m *MockCAClient) Enroll(arg0, arg1 string) error { ret := m.ctrl.Call(m, "Enroll", arg0, arg1) @@ -46,6 +59,45 @@ func (mr *MockCAClientMockRecorder) Enroll(arg0, arg1 interface{}) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Enroll", reflect.TypeOf((*MockCAClient)(nil).Enroll), arg0, arg1) } +// GetAllIdentities mocks base method +func (m *MockCAClient) GetAllIdentities(arg0 string) ([]*api.IdentityResponse, error) { + ret := m.ctrl.Call(m, "GetAllIdentities", arg0) + ret0, _ := ret[0].([]*api.IdentityResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAllIdentities indicates an expected call of GetAllIdentities +func (mr *MockCAClientMockRecorder) GetAllIdentities(arg0 interface{}) *gomock.Call { + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllIdentities", reflect.TypeOf((*MockCAClient)(nil).GetAllIdentities), arg0) +} + +// GetIdentity mocks base method +func (m *MockCAClient) GetIdentity(arg0, arg1 string) (*api.IdentityResponse, error) { + ret := m.ctrl.Call(m, "GetIdentity", arg0, arg1) + ret0, _ := ret[0].(*api.IdentityResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetIdentity indicates an expected call of GetIdentity +func (mr *MockCAClientMockRecorder) GetIdentity(arg0, arg1 interface{}) *gomock.Call { + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIdentity", reflect.TypeOf((*MockCAClient)(nil).GetIdentity), arg0, arg1) +} + +// ModifyIdentity mocks base method +func (m *MockCAClient) ModifyIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) { + ret := m.ctrl.Call(m, "ModifyIdentity", arg0) + ret0, _ := ret[0].(*api.IdentityResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ModifyIdentity indicates an expected call of ModifyIdentity +func (mr *MockCAClientMockRecorder) ModifyIdentity(arg0 interface{}) *gomock.Call { + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ModifyIdentity", reflect.TypeOf((*MockCAClient)(nil).ModifyIdentity), arg0) +} + // Reenroll mocks base method func (m *MockCAClient) Reenroll(arg0 string) error { ret := m.ctrl.Call(m, "Reenroll", arg0) @@ -71,6 +123,19 @@ func (mr *MockCAClientMockRecorder) Register(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Register", reflect.TypeOf((*MockCAClient)(nil).Register), arg0) } +// RemoveIdentity mocks base method +func (m *MockCAClient) RemoveIdentity(arg0 *api.RemoveIdentityRequest) (*api.IdentityResponse, error) { + ret := m.ctrl.Call(m, "RemoveIdentity", arg0) + ret0, _ := ret[0].(*api.IdentityResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// RemoveIdentity indicates an expected call of RemoveIdentity +func (mr *MockCAClientMockRecorder) RemoveIdentity(arg0 interface{}) *gomock.Call { + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveIdentity", reflect.TypeOf((*MockCAClient)(nil).RemoveIdentity), arg0) +} + // Revoke mocks base method func (m *MockCAClient) Revoke(arg0 *api.RevocationRequest) (*api.RevocationResponse, error) { ret := m.ctrl.Call(m, "Revoke", arg0) diff --git a/test/integration/base_test_setup.go b/test/integration/base_test_setup.go index bd34ffbe3b..309a6def5f 100644 --- a/test/integration/base_test_setup.go +++ b/test/integration/base_test_setup.go @@ -146,9 +146,9 @@ func InstallAndInstantiateCC(sdk *fabsdk.FabricSDK, user fabsdk.ContextOption, o return resmgmt.InstantiateCCResponse{}, errors.WithMessage(err, "failed to get endpoint config") } - mspID, err := endpointConfig.MSPID(orgName) - if err != nil { - return resmgmt.InstantiateCCResponse{}, errors.WithMessage(err, "looking up MSP ID failed") + mspID, ok := endpointConfig.MSPID(orgName) + if !ok { + return resmgmt.InstantiateCCResponse{}, errors.New("looking up MSP ID failed") } //prepare context diff --git a/test/integration/e2e/configless/endpointconfig_override_test.go b/test/integration/e2e/configless/endpointconfig_override_test.go index b238432178..34dd5438e4 100644 --- a/test/integration/e2e/configless/endpointconfig_override_test.go +++ b/test/integration/e2e/configless/endpointconfig_override_test.go @@ -307,29 +307,26 @@ func (m *exampleTimeout) Timeout(tType fab.TimeoutType) time.Duration { type exampleMSPID struct{} //MSPID overrides EndpointConfig's MSPID function which returns the mspID for the given org name in the arg -func (m *exampleMSPID) MSPID(org string) (string, error) { +func (m *exampleMSPID) MSPID(org string) (string, bool) { //lowercase org name to make it case insensitive, depends on application preference, for the sake of this example, make it case in-sensitive mspID := orgsConfig[strings.ToLower(org)].MSPID if mspID == "" { - return "", errors.Errorf("MSP ID is empty for org: %s", org) + return "", false } - return mspID, nil + return mspID, true } type examplePeerMSPID struct{} //PeerMSPID overrides EndpointConfig's PeerMSPID function which returns the mspID for the given org name in the arg -func (m *examplePeerMSPID) PeerMSPID(name string) (string, error) { - var mspID string - +func (m *examplePeerMSPID) PeerMSPID(name string) (string, bool) { // Find organisation/msp that peer belongs to for _, org := range orgsConfig { for i := 0; i < len(org.Peers); i++ { if strings.EqualFold(org.Peers[i], name) { // peer belongs to this org add org msp - mspID = org.MSPID - break + return org.MSPID, true // EntityMatchers are not used in this implementation, below is an example of how to use them if needed //} else { // @@ -342,7 +339,7 @@ func (m *examplePeerMSPID) PeerMSPID(name string) (string, error) { } } - return mspID, nil + return "", false } func verifyIsLocalCAsURLs(caConfigs map[string]msp.CAConfig) map[string]msp.CAConfig { @@ -407,7 +404,7 @@ type exampleOrderersConfig struct { } //OrderersConfig overrides EndpointConfig's OrderersConfig function which returns the ordererConfigs list -func (m *exampleOrderersConfig) OrderersConfig() ([]fab.OrdererConfig, error) { +func (m *exampleOrderersConfig) OrderersConfig() ([]fab.OrdererConfig, bool) { orderers := []fab.OrdererConfig{} for _, orderer := range orderersConfig { @@ -415,19 +412,18 @@ func (m *exampleOrderersConfig) OrderersConfig() ([]fab.OrdererConfig, error) { if orderer.TLSCACerts.Path != "" { orderer.TLSCACerts.Path = pathvar.Subst(orderer.TLSCACerts.Path) } else if len(orderer.TLSCACerts.Pem) == 0 && !m.isSystemCertPool { - return nil, errors.Errorf("Orderer has no certs configured. Make sure TLSCACerts.Pem or TLSCACerts.Path is set for %s", orderer.URL) + return nil, false } - orderers = append(orderers, orderer) } - return orderers, nil + return orderers, true } type exampleOrdererConfig struct{} //OrdererConfig overrides EndpointConfig's OrdererConfig function which returns the ordererConfig instance for the name/URL arg -func (m *exampleOrdererConfig) OrdererConfig(ordererNameOrURL string) (*fab.OrdererConfig, error) { +func (m *exampleOrdererConfig) OrdererConfig(ordererNameOrURL string) (*fab.OrdererConfig, bool) { orderer, ok := networkConfig.Orderers[strings.ToLower(ordererNameOrURL)] if !ok { // EntityMatchers are not used in this implementation, below is an example of how to use them if needed, see default implementation for live example @@ -436,14 +432,14 @@ func (m *exampleOrdererConfig) OrdererConfig(ordererNameOrURL string) (*fab.Orde // return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingOrdererEntity.ToInt32(), "no matching orderer config found", nil)) //} //orderer = *matchingOrdererConfig - return nil, errors.Errorf("orderer '%s' not found in the configs", ordererNameOrURL) + return nil, false } if orderer.TLSCACerts.Path != "" { orderer.TLSCACerts.Path = pathvar.Subst(orderer.TLSCACerts.Path) } - return &orderer, nil + return &orderer, true } type examplePeersConfig struct { @@ -478,7 +474,7 @@ func newPeersConfigImpl() *examplePeersConfig { } //PeersConfig overrides EndpointConfig's PeersConfig function which returns the peersConfig list -func (m *examplePeersConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { +func (m *examplePeersConfig) PeersConfig(org string) ([]fab.PeerConfig, bool) { orgPeers := orgsConfig[strings.ToLower(org)].Peers peers := []fab.PeerConfig{} @@ -492,7 +488,7 @@ func (m *examplePeersConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { //} // //p = *matchingPeerConfig - return nil, err + return nil, false } if p.TLSCACerts.Path != "" { p.TLSCACerts.Path = pathvar.Subst(p.TLSCACerts.Path) @@ -500,7 +496,7 @@ func (m *examplePeersConfig) PeersConfig(org string) ([]fab.PeerConfig, error) { peers = append(peers, p) } - return peers, nil + return peers, true } func (m *examplePeersConfig) verifyPeerConfig(p fab.PeerConfig, peerName string, tlsEnabled bool) error { @@ -516,10 +512,10 @@ func (m *examplePeersConfig) verifyPeerConfig(p fab.PeerConfig, peerName string, type examplePeerConfig struct{} // PeerConfig overrides EndpointConfig's PeerConfig function which returns the peerConfig instance for the name/URL arg -func (m *examplePeerConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error) { +func (m *examplePeerConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, bool) { pcfg, ok := peersConfig[nameOrURL] if ok { - return &pcfg, nil + return &pcfg, true } if pcfg.TLSCACerts.Path != "" { pcfg.TLSCACerts.Path = pathvar.Subst(pcfg.TLSCACerts.Path) @@ -527,14 +523,14 @@ func (m *examplePeerConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, error // EntityMatchers are not used in this implementation // see default implementation (pkg/fab/endpointconfig.go) to see how they're used - return nil, errors.Errorf("peer '%s' not found in the configs", nameOrURL) + return nil, false } type exampleNetworkConfig struct{} // NetworkConfig overrides EndpointConfig's NetworkConfig function which returns the full network Config instance -func (m *exampleNetworkConfig) NetworkConfig() (*fab.NetworkConfig, error) { - return &networkConfig, nil +func (m *exampleNetworkConfig) NetworkConfig() (*fab.NetworkConfig, bool) { + return &networkConfig, true } type exampleNetworkPeers struct { @@ -542,7 +538,7 @@ type exampleNetworkPeers struct { } //NetworkPeers overrides EndpointConfig's NetworkPeers function which returns the networkPeers list -func (m *exampleNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, error) { +func (m *exampleNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, bool) { netPeers := []fab.NetworkPeer{} // referencing another interface to call PeerMSPID to match config yaml content peerMSPID := &examplePeerMSPID{} @@ -550,23 +546,23 @@ func (m *exampleNetworkPeers) NetworkPeers() ([]fab.NetworkPeer, error) { for name, p := range networkConfig.Peers { if err := m.verifyPeerConfig(p, name, endpoint.IsTLSEnabled(p.URL)); err != nil { - return nil, err + return nil, false } if p.TLSCACerts.Path != "" { p.TLSCACerts.Path = pathvar.Subst(p.TLSCACerts.Path) } - mspID, err := peerMSPID.PeerMSPID(name) - if err != nil { - return nil, errors.Errorf("failed to retrieve msp id for peer %s", name) + mspID, ok := peerMSPID.PeerMSPID(name) + if !ok { + return nil, false } netPeer := fab.NetworkPeer{PeerConfig: p, MSPID: mspID} netPeers = append(netPeers, netPeer) } - return netPeers, nil + return netPeers, true } func (m *exampleNetworkPeers) verifyPeerConfig(p fab.PeerConfig, peerName string, tlsEnabled bool) error { if p.URL == "" { @@ -581,7 +577,7 @@ func (m *exampleNetworkPeers) verifyPeerConfig(p fab.PeerConfig, peerName string type exampleChannelConfig struct{} // ChannelConfig overrides EndpointConfig's ChannelConfig function which returns the channelConfig instance for the channel name arg -func (m *exampleChannelConfig) ChannelConfig(channelName string) (*fab.ChannelNetworkConfig, error) { +func (m *exampleChannelConfig) ChannelConfig(channelName string) (*fab.ChannelNetworkConfig, bool) { ch, ok := channelsConfig[strings.ToLower(channelName)] if !ok { // EntityMatchers are not used in this implementation, below is an example of how to use them if needed @@ -590,10 +586,10 @@ func (m *exampleChannelConfig) ChannelConfig(channelName string) (*fab.ChannelNe // return nil, errors.WithMessage(matchErr, "channel config not found") //} //return matchingChannel, nil - return nil, errors.Errorf("No channel found for '%s'", channelName) + return nil, false } - return &ch, nil + return &ch, true } type exampleChannelPeers struct { @@ -601,7 +597,7 @@ type exampleChannelPeers struct { } // ChannelPeers overrides EndpointConfig's ChannelPeers function which returns the list of peers for the channel name arg -func (m *exampleChannelPeers) ChannelPeers(channelName string) ([]fab.ChannelPeer, error) { +func (m *exampleChannelPeers) ChannelPeers(channelName string) ([]fab.ChannelPeer, bool) { peers := []fab.ChannelPeer{} // referencing another interface to call PeerMSPID to match config yaml content peerMSPID := &examplePeerMSPID{} @@ -616,7 +612,7 @@ func (m *exampleChannelPeers) ChannelPeers(channelName string) ([]fab.ChannelPee // //// reset 'name' with the mappedChannel as it's referenced further below //chConfig = *matchingChannel - return nil, errors.Errorf("No channel found for '%s'", channelName) + return nil, false } for peerName, chPeerConfig := range chConfig.Peers { @@ -630,20 +626,20 @@ func (m *exampleChannelPeers) ChannelPeers(channelName string) ([]fab.ChannelPee // continue //} //p = *matchingPeerConfig - return nil, errors.Errorf("No peer found '%s'", peerName) + return nil, false } if err := m.verifyPeerConfig(p, peerName, endpoint.IsTLSEnabled(p.URL)); err != nil { - return nil, err + return nil, false } if p.TLSCACerts.Path != "" { p.TLSCACerts.Path = pathvar.Subst(p.TLSCACerts.Path) } - mspID, err := peerMSPID.PeerMSPID(peerName) - if err != nil { - return nil, errors.Errorf("failed to retrieve msp id for peer %s", peerName) + mspID, ok := peerMSPID.PeerMSPID(peerName) + if !ok { + return nil, false } networkPeer := fab.NetworkPeer{PeerConfig: p, MSPID: mspID} @@ -653,7 +649,7 @@ func (m *exampleChannelPeers) ChannelPeers(channelName string) ([]fab.ChannelPee peers = append(peers, peer) } - return peers, nil + return peers, true } func (m *exampleChannelPeers) verifyPeerConfig(p fab.PeerConfig, peerName string, tlsEnabled bool) error { @@ -669,27 +665,27 @@ func (m *exampleChannelPeers) verifyPeerConfig(p fab.PeerConfig, peerName string type exampleChannelOrderers struct{} // ChannelOrderers overrides EndpointConfig's ChannelOrderers function which returns the list of orderers for the channel name arg -func (m *exampleChannelOrderers) ChannelOrderers(channelName string) ([]fab.OrdererConfig, error) { +func (m *exampleChannelOrderers) ChannelOrderers(channelName string) ([]fab.OrdererConfig, bool) { // referencing other interfaces to call ChannelConfig and OrdererConfig to match config yaml content chCfg := &exampleChannelConfig{} oCfg := &exampleOrdererConfig{} orderers := []fab.OrdererConfig{} - channel, err := chCfg.ChannelConfig(channelName) - if err != nil || channel == nil { - return nil, errors.Errorf("Unable to retrieve channel config: %s", err) + channel, ok := chCfg.ChannelConfig(channelName) + if !ok || channel == nil { + return nil, false } for _, chOrderer := range channel.Orderers { - orderer, err := oCfg.OrdererConfig(chOrderer) - if err != nil || orderer == nil { - return nil, errors.Errorf("unable to retrieve orderer config: %s", err) + orderer, ok := oCfg.OrdererConfig(chOrderer) + if !ok || orderer == nil { + return nil, false } orderers = append(orderers, *orderer) } - return orderers, nil + return orderers, true } type exampleTLSCACertPool struct { diff --git a/test/integration/msp/user_data_mgmt_test.go b/test/integration/msp/user_data_mgmt_test.go index 661ca060aa..45bdc08761 100644 --- a/test/integration/msp/user_data_mgmt_test.go +++ b/test/integration/msp/user_data_mgmt_test.go @@ -184,9 +184,9 @@ func getMyMSPID(t *testing.T, ctxProvider context.ClientProvider) string { t.Fatalf("config.Client() failed: %v", err) } - netConfig, err := ctx.EndpointConfig().NetworkConfig() - if err != nil { - t.Fatalf("NetworkConfig failed: %v", err) + netConfig, ok := ctx.EndpointConfig().NetworkConfig() + if !ok { + t.Fatal("Failed to get networkConfig ") } myOrg, ok := netConfig.Organizations[strings.ToLower(clientConfig.Organization)] if !ok { diff --git a/test/integration/orgs/multiple_orgs_test.go b/test/integration/orgs/multiple_orgs_test.go index 2b45d59536..02dfa65d00 100644 --- a/test/integration/orgs/multiple_orgs_test.go +++ b/test/integration/orgs/multiple_orgs_test.go @@ -41,6 +41,7 @@ import ( mspclient "github.com/hyperledger/fabric-sdk-go/pkg/client/msp" "github.com/hyperledger/fabric-sdk-go/pkg/fab/resource" "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/common/cauthdsl" + "github.com/stretchr/testify/assert" ) const ( @@ -551,15 +552,11 @@ func loadOrgPeers(t *testing.T, ctxProvider contextAPI.ClientProvider) { t.Fatalf("context creation failed: %s", err) } - org1Peers, err := ctx.EndpointConfig().PeersConfig(org1) - if err != nil { - t.Fatal(err) - } + org1Peers, ok := ctx.EndpointConfig().PeersConfig(org1) + assert.True(t, ok) - org2Peers, err := ctx.EndpointConfig().PeersConfig(org2) - if err != nil { - t.Fatal(err) - } + org2Peers, ok := ctx.EndpointConfig().PeersConfig(org2) + assert.True(t, ok) orgTestPeer0, err = ctx.InfraProvider().CreatePeerFromConfig(&fab.NetworkPeer{PeerConfig: org1Peers[0]}) if err != nil { diff --git a/test/integration/revoked/revoked_peer_test.go b/test/integration/revoked/revoked_peer_test.go index ae81188609..bf6ecb6930 100644 --- a/test/integration/revoked/revoked_peer_test.go +++ b/test/integration/revoked/revoked_peer_test.go @@ -34,6 +34,7 @@ import ( "github.com/hyperledger/fabric-sdk-go/pkg/core/mocks" "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/common/cauthdsl" "github.com/pkg/errors" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -223,15 +224,11 @@ func loadOrgPeers(t *testing.T, ctxProvider contextAPI.ClientProvider) { t.Fatalf("context creation failed: %s", err) } - org1Peers, err := ctx.EndpointConfig().PeersConfig(org1) - if err != nil { - t.Fatal(err) - } + org1Peers, ok := ctx.EndpointConfig().PeersConfig(org1) + assert.True(t, ok) - org2Peers, err := ctx.EndpointConfig().PeersConfig(org2) - if err != nil { - t.Fatal(err) - } + org2Peers, ok := ctx.EndpointConfig().PeersConfig(org2) + assert.True(t, ok) orgTestPeer0, err = ctx.InfraProvider().CreatePeerFromConfig(&fab.NetworkPeer{PeerConfig: org1Peers[0]}) if err != nil { diff --git a/test/integration/sdk/channel_config_test.go b/test/integration/sdk/channel_config_test.go index 365179f340..232a97f0ef 100644 --- a/test/integration/sdk/channel_config_test.go +++ b/test/integration/sdk/channel_config_test.go @@ -188,8 +188,8 @@ func (f *ChannelConfigFromOrdererProviderFactory) CreateInfraProvider(config fab func setupOrderer(t *testing.T, endPointConfig fab.EndpointConfig, address string) fab.Orderer { //Get orderer config by orderer address - oCfg, err := endPointConfig.OrdererConfig(resolveOrdererAddress(address)) - require.Nil(t, err) + oCfg, ok := endPointConfig.OrdererConfig(resolveOrdererAddress(address)) + require.True(t, ok) o, err := orderer.New(endPointConfig, orderer.FromOrdererConfig(oCfg)) require.Nil(t, err) diff --git a/test/integration/sdk/ledger_queries_test.go b/test/integration/sdk/ledger_queries_test.go index 1dd95d5d76..5394075ef1 100644 --- a/test/integration/sdk/ledger_queries_test.go +++ b/test/integration/sdk/ledger_queries_test.go @@ -49,8 +49,8 @@ func TestLedgerClientQueries(t *testing.T) { t.Fatalf("failed to get endpoint config, error: %v", err) } - expectedPeerConfig, err := endpointConfig.PeerConfig("peer0.org1.example.com") - if err != nil { + expectedPeerConfig, ok := endpointConfig.PeerConfig("peer0.org1.example.com") + if !ok { t.Fatalf("Unable to fetch Peer config for %s", "peer0.org1.example.com") }