From a5c9ea334327d4271ca47db0afe62bd26706918e Mon Sep 17 00:00:00 2001 From: Firas Qutishat Date: Wed, 11 Apr 2018 16:53:26 -0400 Subject: [PATCH] [FAB-9312] Resolve metalinter warnings Change-Id: I68d740f03825136b13ea36cdbd58a0268416b3bd Signed-off-by: Firas Qutishat --- pkg/fab/endpointconfig.go | 452 +++++++++++++++------------ pkg/fab/endpointconfig_test.go | 69 ++-- pkg/fab/mocks/mockbroadcastserver.go | 22 +- pkg/fab/mocks/mockchprovider.go | 3 +- pkg/fab/mocks/mockcontext.go | 2 +- pkg/fab/mocks/mockendorserserver.go | 6 +- pkg/fab/mocks/mockeventserver.go | 21 +- pkg/fab/mocks/mockfabricprovider.go | 2 - pkg/fab/mocks/mockidentity.go | 6 - pkg/fab/mocks/mocktransactor.go | 2 +- pkg/fab/peer/peerendorser.go | 23 +- pkg/fab/resource/cscc.go | 2 +- pkg/fab/resource/resource.go | 42 +-- pkg/fab/signingmgr/signingmgr.go | 2 +- pkg/fab/txn/env.go | 2 +- pkg/fab/txn/proposal_test.go | 11 +- pkg/fab/txn/txn.go | 12 +- pkg/fab/txn/txn_test.go | 58 ++-- test/scripts/check_lint.sh | 7 +- 19 files changed, 414 insertions(+), 330 deletions(-) diff --git a/pkg/fab/endpointconfig.go b/pkg/fab/endpointconfig.go index 3e3907da17..bc00dac9af 100644 --- a/pkg/fab/endpointconfig.go +++ b/pkg/fab/endpointconfig.go @@ -9,29 +9,25 @@ package fab import ( "crypto/tls" "crypto/x509" + "io/ioutil" + "regexp" "sort" "strconv" "strings" + "sync" "time" "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/core/config/cryptoutil" - "github.com/hyperledger/fabric-sdk-go/pkg/core/config/endpoint" - "github.com/pkg/errors" - - "regexp" - - "sync" - - "io/ioutil" - "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp" + "github.com/hyperledger/fabric-sdk-go/pkg/core/config/cryptoutil" + "github.com/hyperledger/fabric-sdk-go/pkg/core/config/endpoint" "github.com/hyperledger/fabric-sdk-go/pkg/core/config/lookup" - cs "github.com/hyperledger/fabric-sdk-go/pkg/core/cryptosuite" + "github.com/hyperledger/fabric-sdk-go/pkg/core/cryptosuite" "github.com/hyperledger/fabric-sdk-go/pkg/util/pathvar" + "github.com/pkg/errors" ) var logger = logging.NewLogger("fabsdk/fab") @@ -154,8 +150,8 @@ 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") == false { - errors.Errorf("Orderer has no certs configured. Make sure TLSCACerts.Pem or TLSCACerts.Path is set for %s", orderer.URL) + } 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) } orderers = append(orderers, orderer) @@ -441,32 +437,16 @@ func (c *EndpointConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { chPeerKey := "channels." + name + ".peers." + peerName // Default value for endorsing peer key is true - endorsingPeerKey := strings.ToLower(chPeerKey + ".endorsingPeer") - _, ok = c.backend.Lookup(endorsingPeerKey) - if !ok { - chPeerConfig.EndorsingPeer = true - } + setEndorsingPeer(chPeerKey, c, chPeerConfig) // Default value for chaincode query key is true - ccQueryKey := strings.ToLower(chPeerKey + ".chaincodeQuery") - _, ok = c.backend.Lookup(ccQueryKey) - if !ok { - chPeerConfig.ChaincodeQuery = true - } + setChaincodeQuery(chPeerKey, c, chPeerConfig) // Default value for ledger query key is true - ledgerQueryKey := strings.ToLower(chPeerKey + ".ledgerQuery") - _, ok = c.backend.Lookup(ledgerQueryKey) - if !ok { - chPeerConfig.LedgerQuery = true - } + setLedgerQuery(chPeerKey, c, chPeerConfig) // Default value for event source key is true - eventSourceKey := strings.ToLower(chPeerKey + ".eventSource") - _, ok = c.backend.Lookup(eventSourceKey) - if !ok { - chPeerConfig.EventSource = true - } + setEventSource(chPeerKey, c, chPeerConfig) mspID, err := c.PeerMSPID(peerName) if err != nil { @@ -484,6 +464,38 @@ func (c *EndpointConfig) ChannelPeers(name string) ([]fab.ChannelPeer, error) { } +func setEndorsingPeer(chPeerKey string, c *EndpointConfig, chPeerConfig fab.PeerChannelConfig) { + endorsingPeerKey := strings.ToLower(chPeerKey + ".endorsingPeer") + _, ok := c.backend.Lookup(endorsingPeerKey) + if !ok { + chPeerConfig.EndorsingPeer = true + } +} + +func setEventSource(chPeerKey string, c *EndpointConfig, chPeerConfig fab.PeerChannelConfig) { + eventSourceKey := strings.ToLower(chPeerKey + ".eventSource") + _, ok := c.backend.Lookup(eventSourceKey) + if !ok { + chPeerConfig.EventSource = true + } +} + +func setLedgerQuery(chPeerKey string, c *EndpointConfig, chPeerConfig fab.PeerChannelConfig) { + ledgerQueryKey := strings.ToLower(chPeerKey + ".ledgerQuery") + _, ok := c.backend.Lookup(ledgerQueryKey) + if !ok { + chPeerConfig.LedgerQuery = true + } +} + +func setChaincodeQuery(chPeerKey string, c *EndpointConfig, chPeerConfig fab.PeerChannelConfig) { + ccQueryKey := strings.ToLower(chPeerKey + ".chaincodeQuery") + _, ok := c.backend.Lookup(ccQueryKey) + if !ok { + chPeerConfig.ChaincodeQuery = true + } +} + // ChannelOrderers returns a list of channel orderers func (c *EndpointConfig) ChannelOrderers(name string) ([]fab.OrdererConfig, error) { orderers := []fab.OrdererConfig{} @@ -551,7 +563,7 @@ func (c *EndpointConfig) TLSClientCerts() ([]tls.Certificate, error) { return nil, err } var clientCerts tls.Certificate - var cb, kb []byte + var cb []byte cb, err = clientConfig.TLSCerts.Client.Cert.Bytes() if err != nil { return nil, errors.Wrapf(err, "failed to load tls client cert") @@ -563,31 +575,13 @@ func (c *EndpointConfig) TLSClientCerts() ([]tls.Certificate, error) { } // Load private key from cert using default crypto suite - cs := cs.GetDefault() + cs := cryptosuite.GetDefault() pk, err := cryptoutil.GetPrivateKeyFromCert(cb, cs) // If CryptoSuite fails to load private key from cert then load private key from config if err != nil || pk == nil { logger.Debugf("Reading pk from config, unable to retrieve from cert: %s", err) - if clientConfig.TLSCerts.Client.Key.Pem != "" { - kb = []byte(clientConfig.TLSCerts.Client.Key.Pem) - } else if clientConfig.TLSCerts.Client.Key.Path != "" { - kb, err = loadByteKeyOrCertFromFile(clientConfig, true) - if err != nil { - return nil, errors.Wrapf(err, "Failed to load key from file path '%s'", clientConfig.TLSCerts.Client.Key.Path) - } - } - - // load the key/cert pair from []byte - clientCerts, err = tls.X509KeyPair(cb, kb) - if err != nil { - return nil, errors.Errorf("Error loading cert/key pair as TLS client credentials: %v", err) - } - - logger.Debug("pk read from config successfully") - - return []tls.Certificate{clientCerts}, nil - + return c.loadPrivateKeyFromConfig(clientConfig, clientCerts, cb) } // private key was retrieved from cert @@ -599,12 +593,35 @@ func (c *EndpointConfig) TLSClientCerts() ([]tls.Certificate, error) { return []tls.Certificate{clientCerts}, nil } +func (c *EndpointConfig) loadPrivateKeyFromConfig(clientConfig *msp.ClientConfig, clientCerts tls.Certificate, cb []byte) ([]tls.Certificate, error) { + var kb []byte + var err error + if clientConfig.TLSCerts.Client.Key.Pem != "" { + kb = []byte(clientConfig.TLSCerts.Client.Key.Pem) + } else if clientConfig.TLSCerts.Client.Key.Path != "" { + kb, err = loadByteKeyOrCertFromFile(clientConfig, true) + if err != nil { + return nil, errors.Wrapf(err, "Failed to load key from file path '%s'", clientConfig.TLSCerts.Client.Key.Path) + } + } + + // load the key/cert pair from []byte + clientCerts, err = tls.X509KeyPair(cb, kb) + if err != nil { + return nil, errors.Errorf("Error loading cert/key pair as TLS client credentials: %v", err) + } + + logger.Debug("pk read from config successfully") + + return []tls.Certificate{clientCerts}, nil +} + // CryptoConfigPath ... func (c *EndpointConfig) CryptoConfigPath() string { return pathvar.Subst(c.backend.GetString("client.cryptoconfig.path")) } -func (c *EndpointConfig) getTimeout(tType fab.TimeoutType) time.Duration { +func (c *EndpointConfig) getTimeout(tType fab.TimeoutType) time.Duration { //nolint var timeout time.Duration switch tType { case fab.EndorserConnection: @@ -772,85 +789,89 @@ func (c *EndpointConfig) tryMatchingPeerConfig(peerName string) (*fab.PeerConfig for _, k := range keys { v := c.peerMatchers[k] if v.MatchString(peerName) { - // get the matching matchConfig from the index number - peerMatchConfig := networkConfig.EntityMatchers["peer"][k] - //Get the peerConfig from mapped host - peerConfig, ok := networkConfig.Peers[strings.ToLower(peerMatchConfig.MappedHost)] - if !ok { - return nil, errors.New("failed to load config from matched Peer") - } + return c.matchPeer(networkConfig, peerName, k, v) + } + } - // Make a copy of GRPC options (as it is manipulated below) - peerConfig.GRPCOptions = copyPropertiesMap(peerConfig.GRPCOptions) - - _, isPortPresentInPeerName := c.getPortIfPresent(peerName) - //if substitution url is empty, use the same network peer url - if peerMatchConfig.URLSubstitutionExp == "" { - port, isPortPresent := c.getPortIfPresent(peerConfig.URL) - peerConfig.URL = peerName - //append port of matched config - if isPortPresent && !isPortPresentInPeerName { - peerConfig.URL += ":" + strconv.Itoa(port) - } - } else { - //else, replace url with urlSubstitutionExp if it doesnt have any variable declarations like $ - if strings.Index(peerMatchConfig.URLSubstitutionExp, "$") < 0 { - peerConfig.URL = peerMatchConfig.URLSubstitutionExp - } else { - //if the urlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with substituionexp pattern - peerConfig.URL = v.ReplaceAllString(peerName, peerMatchConfig.URLSubstitutionExp) - } + return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingPeerEntity.ToInt32(), "no matching peer config found", nil)) +} - } +func (c *EndpointConfig) matchPeer(networkConfig *fab.NetworkConfig, peerName string, k int, v *regexp.Regexp) (*fab.PeerConfig, error) { + // get the matching matchConfig from the index number + peerMatchConfig := networkConfig.EntityMatchers["peer"][k] + //Get the peerConfig from mapped host + peerConfig, ok := networkConfig.Peers[strings.ToLower(peerMatchConfig.MappedHost)] + if !ok { + return nil, errors.New("failed to load config from matched Peer") + } - //if eventSubstitution url is empty, use the same network peer url - if peerMatchConfig.EventURLSubstitutionExp == "" { - port, isPortPresent := c.getPortIfPresent(peerConfig.EventURL) - peerConfig.EventURL = peerName - //append port of matched config - if isPortPresent && !isPortPresentInPeerName { - peerConfig.EventURL += ":" + strconv.Itoa(port) - } - } else { - //else, replace url with eventUrlSubstitutionExp if it doesnt have any variable declarations like $ - if strings.Index(peerMatchConfig.EventURLSubstitutionExp, "$") < 0 { - peerConfig.EventURL = peerMatchConfig.EventURLSubstitutionExp - } else { - //if the eventUrlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with eventsubstituionexp pattern - peerConfig.EventURL = v.ReplaceAllString(peerName, peerMatchConfig.EventURLSubstitutionExp) - } + // Make a copy of GRPC options (as it is manipulated below) + peerConfig.GRPCOptions = copyPropertiesMap(peerConfig.GRPCOptions) - } + _, isPortPresentInPeerName := c.getPortIfPresent(peerName) + //if substitution url is empty, use the same network peer url + if peerMatchConfig.URLSubstitutionExp == "" { + peerConfig.URL = getPeerConfigURL(c, peerName, peerConfig.URL, isPortPresentInPeerName) + } else { + //else, replace url with urlSubstitutionExp if it doesnt have any variable declarations like $ + if !strings.Contains(peerMatchConfig.URLSubstitutionExp, "$") { + peerConfig.URL = peerMatchConfig.URLSubstitutionExp + } else { + //if the urlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with substituionexp pattern + peerConfig.URL = v.ReplaceAllString(peerName, peerMatchConfig.URLSubstitutionExp) + } - //if sslTargetOverrideUrlSubstitutionExp is empty, use the same network peer host - if peerMatchConfig.SSLTargetOverrideURLSubstitutionExp == "" { - if strings.Index(peerName, ":") < 0 { - peerConfig.GRPCOptions["ssl-target-name-override"] = peerName - } else { - //Remove port and protocol of the peerName - s := strings.Split(peerName, ":") - if isPortPresentInPeerName { - peerConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-2] - } else { - peerConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-1] - } - } + } - } else { - //else, replace url with sslTargetOverrideUrlSubstitutionExp if it doesnt have any variable declarations like $ - if strings.Index(peerMatchConfig.SSLTargetOverrideURLSubstitutionExp, "$") < 0 { - peerConfig.GRPCOptions["ssl-target-name-override"] = peerMatchConfig.SSLTargetOverrideURLSubstitutionExp - } else { - //if the sslTargetOverrideUrlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with eventsubstituionexp pattern - peerConfig.GRPCOptions["ssl-target-name-override"] = v.ReplaceAllString(peerName, peerMatchConfig.SSLTargetOverrideURLSubstitutionExp) - } + //if eventSubstitution url is empty, use the same network peer url + if peerMatchConfig.EventURLSubstitutionExp == "" { + peerConfig.EventURL = getPeerConfigURL(c, peerName, peerConfig.EventURL, isPortPresentInPeerName) + } else { + //else, replace url with eventUrlSubstitutionExp if it doesnt have any variable declarations like $ + if !strings.Contains(peerMatchConfig.EventURLSubstitutionExp, "$") { + peerConfig.EventURL = peerMatchConfig.EventURLSubstitutionExp + } else { + //if the eventUrlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with eventsubstituionexp pattern + peerConfig.EventURL = v.ReplaceAllString(peerName, peerMatchConfig.EventURLSubstitutionExp) + } + + } + //if sslTargetOverrideUrlSubstitutionExp is empty, use the same network peer host + if peerMatchConfig.SSLTargetOverrideURLSubstitutionExp == "" { + if !strings.Contains(peerName, ":") { + peerConfig.GRPCOptions["ssl-target-name-override"] = peerName + } else { + //Remove port and protocol of the peerName + s := strings.Split(peerName, ":") + if isPortPresentInPeerName { + peerConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-2] + } else { + peerConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-1] } - return &peerConfig, nil } + + } else { + //else, replace url with sslTargetOverrideUrlSubstitutionExp if it doesnt have any variable declarations like $ + if !strings.Contains(peerMatchConfig.SSLTargetOverrideURLSubstitutionExp, "$") { + peerConfig.GRPCOptions["ssl-target-name-override"] = peerMatchConfig.SSLTargetOverrideURLSubstitutionExp + } else { + //if the sslTargetOverrideUrlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with eventsubstituionexp pattern + peerConfig.GRPCOptions["ssl-target-name-override"] = v.ReplaceAllString(peerName, peerMatchConfig.SSLTargetOverrideURLSubstitutionExp) + } + } + return &peerConfig, nil +} - return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingPeerEntity.ToInt32(), "no matching peer config found", nil)) +func getPeerConfigURL(c *EndpointConfig, peerName, peerConfigURL string, isPortPresentInPeerName bool) string { + port, isPortPresent := c.getPortIfPresent(peerConfigURL) + url := peerName + //append port of matched config + if isPortPresent && !isPortPresentInPeerName { + url += ":" + strconv.Itoa(port) + } + return url } func (c *EndpointConfig) tryMatchingOrdererConfig(ordererName string) (*fab.OrdererConfig, error) { @@ -874,66 +895,70 @@ func (c *EndpointConfig) tryMatchingOrdererConfig(ordererName string) (*fab.Orde for _, k := range keys { v := c.ordererMatchers[k] if v.MatchString(ordererName) { - // get the matching matchConfig from the index number - ordererMatchConfig := networkConfig.EntityMatchers["orderer"][k] - //Get the ordererConfig from mapped host - ordererConfig, ok := networkConfig.Orderers[strings.ToLower(ordererMatchConfig.MappedHost)] - if !ok { - return nil, errors.New("failed to load config from matched Orderer") - } + return c.matchOrderer(networkConfig, ordererName, k, v) + } + } - // Make a copy of GRPC options (as it is manipulated below) - ordererConfig.GRPCOptions = copyPropertiesMap(ordererConfig.GRPCOptions) + return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingOrdererEntity.ToInt32(), "no matching orderer config found", nil)) +} - _, isPortPresentInOrdererName := c.getPortIfPresent(ordererName) - //if substitution url is empty, use the same network orderer url - if ordererMatchConfig.URLSubstitutionExp == "" { - port, isPortPresent := c.getPortIfPresent(ordererConfig.URL) - ordererConfig.URL = ordererName +func (c *EndpointConfig) matchOrderer(networkConfig *fab.NetworkConfig, ordererName string, k int, v *regexp.Regexp) (*fab.OrdererConfig, error) { + // get the matching matchConfig from the index number + ordererMatchConfig := networkConfig.EntityMatchers["orderer"][k] + //Get the ordererConfig from mapped host + ordererConfig, ok := networkConfig.Orderers[strings.ToLower(ordererMatchConfig.MappedHost)] + if !ok { + return nil, errors.New("failed to load config from matched Orderer") + } - //append port of matched config - if isPortPresent && !isPortPresentInOrdererName { - ordererConfig.URL += ":" + strconv.Itoa(port) - } - } else { - //else, replace url with urlSubstitutionExp if it doesnt have any variable declarations like $ - if strings.Index(ordererMatchConfig.URLSubstitutionExp, "$") < 0 { - ordererConfig.URL = ordererMatchConfig.URLSubstitutionExp - } else { - //if the urlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with substituionexp pattern - ordererConfig.URL = v.ReplaceAllString(ordererName, ordererMatchConfig.URLSubstitutionExp) - } - } + // Make a copy of GRPC options (as it is manipulated below) + ordererConfig.GRPCOptions = copyPropertiesMap(ordererConfig.GRPCOptions) - //if sslTargetOverrideUrlSubstitutionExp is empty, use the same network peer host - if ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp == "" { - if strings.Index(ordererName, ":") < 0 { - ordererConfig.GRPCOptions["ssl-target-name-override"] = ordererName - } else { - //Remove port and protocol of the ordererName - s := strings.Split(ordererName, ":") - if isPortPresentInOrdererName { - ordererConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-2] - } else { - ordererConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-1] - } - } + _, isPortPresentInOrdererName := c.getPortIfPresent(ordererName) + //if substitution url is empty, use the same network orderer url + if ordererMatchConfig.URLSubstitutionExp == "" { + port, isPortPresent := c.getPortIfPresent(ordererConfig.URL) + ordererConfig.URL = ordererName - } else { - //else, replace url with sslTargetOverrideUrlSubstitutionExp if it doesnt have any variable declarations like $ - if strings.Index(ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp, "$") < 0 { - ordererConfig.GRPCOptions["ssl-target-name-override"] = ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp - } else { - //if the sslTargetOverrideUrlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with eventsubstituionexp pattern - ordererConfig.GRPCOptions["ssl-target-name-override"] = v.ReplaceAllString(ordererName, ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp) - } + //append port of matched config + if isPortPresent && !isPortPresentInOrdererName { + ordererConfig.URL += ":" + strconv.Itoa(port) + } + } else { + //else, replace url with urlSubstitutionExp if it doesnt have any variable declarations like $ + if !strings.Contains(ordererMatchConfig.URLSubstitutionExp, "$") { + ordererConfig.URL = ordererMatchConfig.URLSubstitutionExp + } else { + //if the urlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with substituionexp pattern + ordererConfig.URL = v.ReplaceAllString(ordererName, ordererMatchConfig.URLSubstitutionExp) + } + } + //if sslTargetOverrideUrlSubstitutionExp is empty, use the same network peer host + if ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp == "" { + if !strings.Contains(ordererName, ":") { + ordererConfig.GRPCOptions["ssl-target-name-override"] = ordererName + } else { + //Remove port and protocol of the ordererName + s := strings.Split(ordererName, ":") + if isPortPresentInOrdererName { + ordererConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-2] + } else { + ordererConfig.GRPCOptions["ssl-target-name-override"] = s[len(s)-1] } - return &ordererConfig, nil } - } - return nil, errors.WithStack(status.New(status.ClientStatus, status.NoMatchingOrdererEntity.ToInt32(), "no matching orderer config found", nil)) + } else { + //else, replace url with sslTargetOverrideUrlSubstitutionExp if it doesnt have any variable declarations like $ + if !strings.Contains(ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp, "$") { + ordererConfig.GRPCOptions["ssl-target-name-override"] = ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp + } else { + //if the sslTargetOverrideUrlSubstitutionExp has $ variable declarations, use regex replaceallstring to replace networkhostname with eventsubstituionexp pattern + ordererConfig.GRPCOptions["ssl-target-name-override"] = v.ReplaceAllString(ordererName, ordererMatchConfig.SSLTargetOverrideURLSubstitutionExp) + } + + } + return &ordererConfig, nil } func (c *EndpointConfig) tryMatchingChannelConfig(channelName string) (*fab.ChannelNetworkConfig, string, error) { @@ -1005,28 +1030,42 @@ func (c *EndpointConfig) compileMatchers() error { return nil } - if networkConfig.EntityMatchers["peer"] != nil { - peerMatchersConfig := networkConfig.EntityMatchers["peer"] - for i := 0; i < len(peerMatchersConfig); i++ { - if peerMatchersConfig[i].Pattern != "" { - c.peerMatchers[i], err = regexp.Compile(peerMatchersConfig[i].Pattern) - if err != nil { - return err - } - } - } + err = c.compilePeerMatcher(networkConfig) + if err != nil { + return err } - if networkConfig.EntityMatchers["orderer"] != nil { - ordererMatchersConfig := networkConfig.EntityMatchers["orderer"] - for i := 0; i < len(ordererMatchersConfig); i++ { - if ordererMatchersConfig[i].Pattern != "" { - c.ordererMatchers[i], err = regexp.Compile(ordererMatchersConfig[i].Pattern) + err = c.compileOrdererMatcher(networkConfig) + if err != nil { + return err + } + + err = c.compileCertificateAuthorityMatcher(networkConfig) + if err != nil { + return err + } + + err = c.compileChannelMatcher(networkConfig) + return err +} + +func (c *EndpointConfig) compileChannelMatcher(networkConfig *fab.NetworkConfig) error { + var err error + if networkConfig.EntityMatchers["channel"] != nil { + channelMatchers := networkConfig.EntityMatchers["channel"] + for i, matcher := range channelMatchers { + if matcher.Pattern != "" { + c.channelMatchers[i], err = regexp.Compile(matcher.Pattern) if err != nil { return err } } } } + return nil +} + +func (c *EndpointConfig) compileCertificateAuthorityMatcher(networkConfig *fab.NetworkConfig) error { + var err error if networkConfig.EntityMatchers["certificateauthority"] != nil { certMatchersConfig := networkConfig.EntityMatchers["certificateauthority"] for i := 0; i < len(certMatchersConfig); i++ { @@ -1038,11 +1077,32 @@ func (c *EndpointConfig) compileMatchers() error { } } } - if networkConfig.EntityMatchers["channel"] != nil { - channelMatchers := networkConfig.EntityMatchers["channel"] - for i, matcher := range channelMatchers { - if matcher.Pattern != "" { - c.channelMatchers[i], err = regexp.Compile(matcher.Pattern) + return nil +} + +func (c *EndpointConfig) compileOrdererMatcher(networkConfig *fab.NetworkConfig) error { + var err error + if networkConfig.EntityMatchers["orderer"] != nil { + ordererMatchersConfig := networkConfig.EntityMatchers["orderer"] + for i := 0; i < len(ordererMatchersConfig); i++ { + if ordererMatchersConfig[i].Pattern != "" { + c.ordererMatchers[i], err = regexp.Compile(ordererMatchersConfig[i].Pattern) + if err != nil { + return err + } + } + } + } + return nil +} + +func (c *EndpointConfig) compilePeerMatcher(networkConfig *fab.NetworkConfig) error { + var err error + if networkConfig.EntityMatchers["peer"] != nil { + peerMatchersConfig := networkConfig.EntityMatchers["peer"] + for i := 0; i < len(peerMatchersConfig); i++ { + if peerMatchersConfig[i].Pattern != "" { + c.peerMatchers[i], err = regexp.Compile(peerMatchersConfig[i].Pattern) if err != nil { return err } @@ -1079,7 +1139,7 @@ func (c *EndpointConfig) verifyPeerConfig(p fab.PeerConfig, peerName string, tls if p.URL == "" { return errors.Errorf("URL does not exist or empty for peer %s", peerName) } - if tlsEnabled && len(p.TLSCACerts.Pem) == 0 && p.TLSCACerts.Path == "" && c.backend.GetBool("client.tlsCerts.systemCertPool") == false { + if tlsEnabled && len(p.TLSCACerts.Pem) == 0 && p.TLSCACerts.Path == "" && !c.backend.GetBool("client.tlsCerts.systemCertPool") { return errors.Errorf("tls.certificate does not exist or empty for peer %s", peerName) } return nil @@ -1097,7 +1157,7 @@ func (c *EndpointConfig) containsCert(newCert *x509.Certificate) bool { func (c *EndpointConfig) getCertPool() (*x509.CertPool, error) { tlsCertPool := x509.NewCertPool() - if c.backend.GetBool("client.tlsCerts.systemCertPool") == true { + if c.backend.GetBool("client.tlsCerts.systemCertPool") { var err error if tlsCertPool, err = x509.SystemCertPool(); err != nil { return nil, err diff --git a/pkg/fab/endpointconfig_test.go b/pkg/fab/endpointconfig_test.go index d84c416d77..2c8ac87ab4 100644 --- a/pkg/fab/endpointconfig_test.go +++ b/pkg/fab/endpointconfig_test.go @@ -109,24 +109,25 @@ func TestCAConfigFailsByNetworkConfig(t *testing.T) { t.Fatal("Testing PeersConfig supposed to fail") } + checkCAConfigFailsByNetworkConfig(sampleEndpointConfig, t) +} + +func checkCAConfigFailsByNetworkConfig(sampleEndpointConfig *EndpointConfig, t *testing.T) { //Testing PeersConfig failure scenario pConfig, err := sampleEndpointConfig.PeerConfig("peerorg1", "peer1") if pConfig != nil || err == nil { t.Fatal("Testing PeerConfig supposed to fail") } - //Testing ChannelConfig failure scenario chConfig, err := sampleEndpointConfig.ChannelConfig("invalid") if chConfig != nil || err == nil { t.Fatal("Testing ChannelConfig supposed to fail") } - //Testing ChannelPeers failure scenario cpConfigs, err := sampleEndpointConfig.ChannelPeers("invalid") if cpConfigs != nil || err == nil { t.Fatal("Testing ChannelPeeers supposed to fail") } - //Testing ChannelOrderers failure scenario coConfigs, err := sampleEndpointConfig.ChannelOrderers("invalid") if coConfigs != nil || err == nil { @@ -143,12 +144,12 @@ func TestTLSCAConfig(t *testing.T) { t.Fatalf("Failed to get TLS CA Cert, reason: %v", err) } - config, err := ConfigFromBackend(configBackend) + configBackend1, err := ConfigFromBackend(configBackend) if err != nil { t.Fatalf("Failed to get endpoint config, reason: %v", err) } - endpointConfig := config.(*EndpointConfig) + endpointConfig := configBackend1.(*EndpointConfig) _, err = endpointConfig.TLSCACertPool(cert) if err != nil { @@ -175,6 +176,10 @@ func TestTLSCAConfig(t *testing.T) { _, err = endpointConfig.TLSCACertPool(badCert) + if err != nil { + t.Fatalf(err.Error()) + } + keyConfig := endpoint.TLSConfig{Path: keyPath} key, err := keyConfig.TLSCert() @@ -184,6 +189,9 @@ func TestTLSCAConfig(t *testing.T) { } _, err = endpointConfig.TLSCACertPool(key) + if err != nil { + t.Fatalf(err.Error()) + } } func TestTimeouts(t *testing.T) { @@ -233,7 +241,11 @@ func TestTimeouts(t *testing.T) { if t1 != time.Millisecond*2 { t.Fatalf(errStr, "OrdererConnection", t1) } - t1 = endpointConfig.Timeout(fab.OrdererResponse) + checkTimeouts(endpointConfig, t, errStr) +} + +func checkTimeouts(endpointConfig fab.EndpointConfig, t *testing.T, errStr string) { + t1 := endpointConfig.Timeout(fab.OrdererResponse) if t1 != time.Second*6 { t.Fatalf(errStr, "OrdererResponse", t1) } @@ -314,7 +326,11 @@ func TestDefaultTimeouts(t *testing.T) { if t1 != defaultOrdererConnectionTimeout { t.Fatalf(errStr, "OrdererConnection", t1) } - t1 = endpointConfig.Timeout(fab.OrdererResponse) + checkDefaultTimeout(endpointConfig, t, errStr) +} + +func checkDefaultTimeout(endpointConfig fab.EndpointConfig, t *testing.T, errStr string) { + t1 := endpointConfig.Timeout(fab.OrdererResponse) if t1 != defaultOrdererResponseTimeout { t.Fatalf(errStr, "OrdererResponse", t1) } @@ -406,12 +422,12 @@ func TestPeerConfigByUrl_entityMatchers(t *testing.T) { } func testCommonConfigPeerByURL(t *testing.T, expectedConfigURL string, fetchedConfigURL string) { - config, err := ConfigFromBackend(configBackend) + config1, err := ConfigFromBackend(configBackend) if err != nil { t.Fatal("Failed to get endpoint config from backend") } - endpointConfig := config.(*EndpointConfig) + endpointConfig := config1.(*EndpointConfig) expectedConfig, err := endpointConfig.peerConfig(expectedConfigURL) if err != nil { @@ -419,6 +435,9 @@ func testCommonConfigPeerByURL(t *testing.T, expectedConfigURL string, fetchedCo } fetchedConfig, err := endpointConfig.PeerConfigByURL(fetchedConfigURL) + if err != nil { + t.Fatalf(err.Error()) + } if fetchedConfig.URL == "" { t.Fatalf("Url value for the host is empty") @@ -617,12 +636,12 @@ func TestPeerConfig(t *testing.T) { func testCommonConfigPeer(t *testing.T, expectedConfigHost string, fetchedConfigHost string) (expectedConfig *fab.PeerConfig, fetchedConfig *fab.PeerConfig) { - config, err := ConfigFromBackend(configBackend) + config1, err := ConfigFromBackend(configBackend) if err != nil { t.Fatal("Failed to get endpoint config from backend") } - endpointConfig := config.(*EndpointConfig) + endpointConfig := config1.(*EndpointConfig) expectedConfig, err = endpointConfig.peerConfig(expectedConfigHost) if err != nil { @@ -781,19 +800,19 @@ func TestInitConfigFromRawWithPem(t *testing.T) { t.Fatalf("Failed to initialize config from bytes array. Error: %s", err) } - config, err := ConfigFromBackend(backend) + config1, err := ConfigFromBackend(backend) if err != nil { t.Fatalf("Failed to initialize config from bytes array. Error: %s", err) } - endpointConfig := config.(*EndpointConfig) + endpointConfig := config1.(*EndpointConfig) o, err := endpointConfig.OrderersConfig() if err != nil { t.Fatalf("Failed to load orderers from config. Error: %s", err) } - if o == nil || len(o) == 0 { + if len(o) == 0 { t.Fatalf("orderer cannot be nil or empty") } @@ -820,9 +839,14 @@ SQtE5YgdxkUCIHReNWh/pluHTxeGu2jNCH1eh6o2ajSGeeizoapvdJbN if err != nil { t.Fatalf(err.Error()) } - if pc == nil || len(pc) == 0 { + if len(pc) == 0 { t.Fatalf("peers list of %s cannot be nil or empty", org1) } + checkPem(endpointConfig, t) + +} + +func checkPem(endpointConfig *EndpointConfig, t *testing.T) { peer0 := "peer0.org1.example.com" p0, err := endpointConfig.PeerConfig(org1, peer0) if err != nil { @@ -846,12 +870,11 @@ V842OVjxCYYQwCjPIY+5e9ORR+8pxVzcMAoGCCqGSM49BAMCA0cAMEQCIGZ+KTfS eezqv0ml1VeQEmnAEt5sJ2RJA58+LegUYMd6AiAfEe6BKqdY03qFUgEYmtKG+3Dr O94CDp7l2k7hMQI0zQ== -----END CERTIFICATE-----` - - loadedPPem := strings.TrimSpace(p0.TLSCACerts.Pem) // viper's unmarshall adds a \n to the end of a string, hence the TrimeSpace + loadedPPem := strings.TrimSpace(p0.TLSCACerts.Pem) + // viper's unmarshall adds a \n to the end of a string, hence the TrimeSpace if loadedPPem != pPem { t.Fatalf("%s Pem doesn't match. Expected \n'%s'\n, but got \n'%s'\n", peer0, pPem, loadedPPem) } - } func loadConfigBytesFromFile(t *testing.T, filePath string) ([]byte, error) { @@ -866,7 +889,7 @@ func loadConfigBytesFromFile(t *testing.T, filePath string) ([]byte, error) { t.Fatalf("Failed to read config file stat. Error: %s", err) } s := fi.Size() - cBytes := make([]byte, s, s) + cBytes := make([]byte, s) n, err := f.Read(cBytes) if err != nil { t.Fatalf("Failed to read test config for bytes array testing. Error: %s", err) @@ -879,12 +902,12 @@ func loadConfigBytesFromFile(t *testing.T, filePath string) ([]byte, error) { func TestLoadConfigWithEmbeddedUsersWithPems(t *testing.T) { // get a config file with embedded users - configBackend, err := config.FromFile(configEmbeddedUsersTestFilePath)() + configBackend1, err := config.FromFile(configEmbeddedUsersTestFilePath)() if err != nil { t.Fatal(err) } - endpointConfig, err := ConfigFromBackend(configBackend) + endpointConfig, err := ConfigFromBackend(configBackend1) if err != nil { t.Fatal(err) } @@ -914,12 +937,12 @@ func TestLoadConfigWithEmbeddedUsersWithPems(t *testing.T) { func TestLoadConfigWithEmbeddedUsersWithPaths(t *testing.T) { // get a config file with embedded users - configBackend, err := config.FromFile(configEmbeddedUsersTestFilePath)() + configBackend1, err := config.FromFile(configEmbeddedUsersTestFilePath)() if err != nil { t.Fatal(err) } - endpointConfig, err := ConfigFromBackend(configBackend) + endpointConfig, err := ConfigFromBackend(configBackend1) if err != nil { t.Fatal(err) } diff --git a/pkg/fab/mocks/mockbroadcastserver.go b/pkg/fab/mocks/mockbroadcastserver.go index a4deea8eda..dbf6182bb5 100644 --- a/pkg/fab/mocks/mockbroadcastserver.go +++ b/pkg/fab/mocks/mockbroadcastserver.go @@ -71,13 +71,21 @@ func (m *MockBroadcastServer) Deliver(server po.AtomicBroadcast_DeliverServer) e } if m.DeliverResponse != nil { - server.Recv() - server.SendMsg(m.DeliverResponse) + if _, err := server.Recv(); err != nil { + return err + } + if err := server.SendMsg(m.DeliverResponse); err != nil { + return err + } return nil } - server.Recv() - server.Send(TestBlock) + if _, err := server.Recv(); err != nil { + return err + } + if err := server.Send(TestBlock); err != nil { + return err + } return nil } @@ -92,7 +100,11 @@ func StartMockBroadcastServer(broadcastTestURL string, grpcServer *grpc.Server) broadcastServer := new(MockBroadcastServer) po.RegisterAtomicBroadcastServer(grpcServer, broadcastServer) - go grpcServer.Serve(lis) + go func() { + if err := grpcServer.Serve(lis); err != nil { + panic(err.Error()) + } + }() return broadcastServer, addr } diff --git a/pkg/fab/mocks/mockchprovider.go b/pkg/fab/mocks/mockchprovider.go index a4e1464722..2bbe1d41f8 100644 --- a/pkg/fab/mocks/mockchprovider.go +++ b/pkg/fab/mocks/mockchprovider.go @@ -8,7 +8,6 @@ package mocks import ( "github.com/hyperledger/fabric-sdk-go/pkg/common/options" - "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" ) @@ -29,7 +28,7 @@ type MockChannelService struct { } // NewMockChannelProvider returns a mock ChannelProvider -func NewMockChannelProvider(ctx context.Client) (*MockChannelProvider, error) { +func NewMockChannelProvider(ctx core.Providers) (*MockChannelProvider, error) { // Create a mock client with the mock channel cp := MockChannelProvider{ ctx: ctx, diff --git a/pkg/fab/mocks/mockcontext.go b/pkg/fab/mocks/mockcontext.go index 816a598d43..3253d74d01 100644 --- a/pkg/fab/mocks/mockcontext.go +++ b/pkg/fab/mocks/mockcontext.go @@ -334,7 +334,7 @@ type MockTransactionHeader struct { // TransactionID returns the transaction's computed identifier. func (th *MockTransactionHeader) TransactionID() fab.TransactionID { - return fab.TransactionID(th.MockID) + return th.MockID } // Creator returns the transaction creator's identity bytes. diff --git a/pkg/fab/mocks/mockendorserserver.go b/pkg/fab/mocks/mockendorserserver.go index a2601dd249..03d36e0cce 100644 --- a/pkg/fab/mocks/mockendorserserver.go +++ b/pkg/fab/mocks/mockendorserserver.go @@ -82,6 +82,10 @@ func StartEndorserServer(endorserTestURL string) *MockEndorserServer { endorserServer := &MockEndorserServer{} pb.RegisterEndorserServer(grpcServer, endorserServer) fmt.Printf("Test endorser server started\n") - go grpcServer.Serve(lis) + go func() { + if err := grpcServer.Serve(lis); err != nil { + panic(err.Error()) + } + }() return endorserServer } diff --git a/pkg/fab/mocks/mockeventserver.go b/pkg/fab/mocks/mockeventserver.go index 35e9ce3364..bddeb19754 100644 --- a/pkg/fab/mocks/mockeventserver.go +++ b/pkg/fab/mocks/mockeventserver.go @@ -33,7 +33,11 @@ func StartMockEventServer(testAddress string) (*MockEventServer, error) { eventServer := &MockEventServer{grpcServer: grpcServer} pb.RegisterEventsServer(grpcServer, eventServer) fmt.Printf("Starting mock event server\n") - go grpcServer.Serve(lis) + go func() { + if err := grpcServer.Serve(lis); err != nil { + panic(err.Error()) + } + }() return eventServer, nil } @@ -42,19 +46,26 @@ func StartMockEventServer(testAddress string) (*MockEventServer, error) { func (m *MockEventServer) Chat(srv pb.Events_ChatServer) error { m.server = srv m.channel = make(chan *pb.Event) - in, _ := srv.Recv() + in, err := srv.Recv() + if err != nil { + return err + } evt := &pb.Event{} - err := proto.Unmarshal(in.EventBytes, evt) + err = proto.Unmarshal(in.EventBytes, evt) if err != nil { return fmt.Errorf("error unmarshaling the event bytes in the SignedEvent: %s", err) } switch evt.Event.(type) { case *pb.Event_Register: - srv.Send(&pb.Event{Event: &pb.Event_Register{Register: &pb.Register{}}}) + if err := srv.Send(&pb.Event{Event: &pb.Event_Register{Register: &pb.Register{}}}); err != nil { + return err + } } for { event := <-m.channel - srv.Send(event) + if err := srv.Send(event); err != nil { + return err + } } } diff --git a/pkg/fab/mocks/mockfabricprovider.go b/pkg/fab/mocks/mockfabricprovider.go index ae0c87ccdf..fbccaee8df 100644 --- a/pkg/fab/mocks/mockfabricprovider.go +++ b/pkg/fab/mocks/mockfabricprovider.go @@ -12,13 +12,11 @@ import ( reqContext "context" "github.com/hyperledger/fabric-sdk-go/pkg/common/options" - "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" ) // MockInfraProvider represents the default implementation of Fabric objects. type MockInfraProvider struct { - providerContext context.Providers customOrderer fab.Orderer customTransactor fab.Transactor } diff --git a/pkg/fab/mocks/mockidentity.go b/pkg/fab/mocks/mockidentity.go index d7871d5394..b7cc6a5b61 100644 --- a/pkg/fab/mocks/mockidentity.go +++ b/pkg/fab/mocks/mockidentity.go @@ -12,7 +12,6 @@ import ( "time" "github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/msp" - "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" msp_protos "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/msp" ) @@ -74,11 +73,6 @@ func (id *MockIdentity) Serialize() ([]byte, error) { return nil, nil } -func (id *MockIdentity) getHashOpt(hashFamily string) (core.HashOpts, error) { - - return nil, nil -} - // MockSigningIdentity ... type MockSigningIdentity struct { // we embed everything from a base identity diff --git a/pkg/fab/mocks/mocktransactor.go b/pkg/fab/mocks/mocktransactor.go index 8e3cc58a40..298ee098bd 100644 --- a/pkg/fab/mocks/mocktransactor.go +++ b/pkg/fab/mocks/mocktransactor.go @@ -27,7 +27,7 @@ func (t *MockTransactor) CreateTransactionHeader() (fab.TransactionHeader, error // SendTransactionProposal sends a TransactionProposal to the target peers. func (t *MockTransactor) SendTransactionProposal(proposal *fab.TransactionProposal, targets []fab.ProposalProcessor) ([]*fab.TransactionProposalResponse, error) { - response := make([]*fab.TransactionProposalResponse, 1, 1) + response := make([]*fab.TransactionProposalResponse, 1) response[0] = &fab.TransactionProposalResponse{Endorser: "example.com", Status: 99, ProposalResponse: &pb.ProposalResponse{Response: &pb.Response{Payload: []byte("abc")}}, } diff --git a/pkg/fab/peer/peerendorser.go b/pkg/fab/peer/peerendorser.go index 60481f8a47..39249ea0ff 100644 --- a/pkg/fab/peer/peerendorser.go +++ b/pkg/fab/peer/peerendorser.go @@ -157,11 +157,11 @@ func (p *peerEndorser) sendProposal(ctx reqContext.Context, proposal fab.Process if ok { code, message, extractErr := extractChaincodeError(rpcStatus) if extractErr != nil { - code, message, extractErr := extractPrematureExecutionError(rpcStatus) + code, message1, extractErr := extractPrematureExecutionError(rpcStatus) if extractErr != nil { err = status.NewFromGRPCStatus(rpcStatus) } else { - err = status.New(status.EndorserClientStatus, code, message, nil) + err = status.New(status.EndorserClientStatus, code, message1, nil) } } else { err = status.NewFromExtractedChaincodeError(code, message) @@ -184,14 +184,22 @@ func extractChaincodeError(status *grpcstatus.Status) (int, string, error) { if i >= 0 { j := strings.Index(status.Message()[i:], ",") if j > statusLength { - i, err := strconv.Atoi(strings.TrimSpace(status.Message()[i+statusLength : i+j])) + i1, err := strconv.Atoi(strings.TrimSpace(status.Message()[i+statusLength : i+j])) if err != nil { - return 0, "", errors.Errorf("Non-number returned as GRPC status [%s] ", strings.TrimSpace(status.Message()[i+statusLength:i+j])) + return 0, "", errors.Errorf("Non-number returned as GRPC status [%s] ", strings.TrimSpace(status.Message()[i1+statusLength:i1+j])) } - code = i + code = i1 } } } + message = checkMessage(status, messageLength, message) + if code != 0 && message != "" { + return code, message, nil + } + return code, message, errors.Errorf("Unable to parse GRPC Status Message Code: %v Message: %v", code, message) +} + +func checkMessage(status *grpcstatus.Status, messageLength int, message string) string { if strings.Contains(status.Message(), "message:") { i := strings.Index(status.Message(), "message:") if i >= 0 { @@ -201,10 +209,7 @@ func extractChaincodeError(status *grpcstatus.Status) (int, string, error) { } } } - if code != 0 && message != "" { - return code, message, nil - } - return code, message, errors.Errorf("Unable to parse GRPC Status Message Code: %v Message: %v", code, message) + return message } func extractPrematureExecutionError(grpcstat *grpcstatus.Status) (int32, string, error) { diff --git a/pkg/fab/resource/cscc.go b/pkg/fab/resource/cscc.go index bb72f56731..3e5c00dd6c 100644 --- a/pkg/fab/resource/cscc.go +++ b/pkg/fab/resource/cscc.go @@ -19,7 +19,7 @@ const ( csccChannels = "GetChannels" ) -func createJoinChannelInvokeRequest(genesisBlock *common.Block) (fab.ChaincodeInvokeRequest, error) { +func createJoinChannelInvokeRequest(genesisBlock *common.Block) (fab.ChaincodeInvokeRequest, error) { //nolint genesisBlockBytes, err := proto.Marshal(genesisBlock) if err != nil { diff --git a/pkg/fab/resource/resource.go b/pkg/fab/resource/resource.go index 4c7226991f..383e5980d2 100644 --- a/pkg/fab/resource/resource.go +++ b/pkg/fab/resource/resource.go @@ -107,9 +107,9 @@ func CreateChannel(reqCtx reqContext.Context, request api.CreateChannelRequest, return fab.EmptyTransactionID, errors.WithMessage(err, "creation of transaction header failed") } - options := getOpts(opts...) + optionsValue := getOpts(opts...) - _, err = retry.NewInvoker(retry.New(options.retry)).Invoke( + _, err = retry.NewInvoker(retry.New(optionsValue.retry)).Invoke( func() (interface{}, error) { return nil, createOrUpdateChannel(reqCtx, txh, request) }, @@ -134,8 +134,8 @@ func createChannelFromEnvelope(reqCtx reqContext.Context, request api.CreateChan // GenesisBlockFromOrderer returns the genesis block from the defined orderer that may be // used in a join request func GenesisBlockFromOrderer(reqCtx reqContext.Context, channelName string, orderer fab.Orderer, opts ...Opt) (*common.Block, error) { - options := getOpts(opts...) - return retrieveBlock(reqCtx, []fab.Orderer{orderer}, channelName, newSpecificSeekPosition(0), options) + optionsValue := getOpts(opts...) + return retrieveBlock(reqCtx, []fab.Orderer{orderer}, channelName, newSpecificSeekPosition(0), optionsValue) } // LastConfigFromOrderer fetches the current configuration block for the specified channel @@ -143,10 +143,10 @@ func GenesisBlockFromOrderer(reqCtx reqContext.Context, channelName string, orde func LastConfigFromOrderer(reqCtx reqContext.Context, channelName string, orderer fab.Orderer, opts ...Opt) (*common.Block, error) { logger.Debugf("channelConfig - start for channel %s", channelName) - options := getOpts(opts...) + optionsValue := getOpts(opts...) // Get the newest block - block, err := retrieveBlock(reqCtx, []fab.Orderer{orderer}, channelName, newNewestSeekPosition(), options) + block, err := retrieveBlock(reqCtx, []fab.Orderer{orderer}, channelName, newNewestSeekPosition(), optionsValue) if err != nil { return nil, err } @@ -160,7 +160,7 @@ func LastConfigFromOrderer(reqCtx reqContext.Context, channelName string, ordere logger.Debugf("channelConfig - Last config index: %d\n", lastConfig.Index) // Get the last config block - block, err = retrieveBlock(reqCtx, []fab.Orderer{orderer}, channelName, newSpecificSeekPosition(lastConfig.Index), options) + block, err = retrieveBlock(reqCtx, []fab.Orderer{orderer}, channelName, newSpecificSeekPosition(lastConfig.Index), optionsValue) if err != nil { return nil, errors.WithMessage(err, "retrieve block failed") } @@ -182,14 +182,14 @@ func JoinChannel(reqCtx reqContext.Context, request api.JoinChannelRequest, targ return errors.New("missing block input parameter with the required genesis block") } - options := getOpts(opts...) + optionsValue := getOpts(opts...) cir, err := createJoinChannelInvokeRequest(request.GenesisBlock) if err != nil { return errors.WithMessage(err, "creation of join channel invoke request failed") } - var errors multi.Errors + var errors1 multi.Errors var mutex sync.Mutex var wg sync.WaitGroup @@ -199,9 +199,9 @@ func JoinChannel(reqCtx reqContext.Context, request api.JoinChannelRequest, targ target := t go func() { defer wg.Done() - if _, err := queryChaincodeWithTarget(reqCtx, cir, target, options); err != nil { + if _, err := queryChaincodeWithTarget(reqCtx, cir, target, optionsValue); err != nil { mutex.Lock() - errors = append(errors, err) + errors1 = append(errors1, err) mutex.Unlock() } }() @@ -209,7 +209,7 @@ func JoinChannel(reqCtx reqContext.Context, request api.JoinChannelRequest, targ wg.Wait() - return errors.ToError() + return errors1.ToError() } func extractSignedEnvelope(reqEnvelope []byte) (*fab.SignedEnvelope, error) { @@ -269,10 +269,10 @@ func QueryChannels(reqCtx reqContext.Context, peer fab.ProposalProcessor, opts . return nil, errors.New("peer required") } - options := getOpts(opts...) + optionsValue := getOpts(opts...) cir := createChannelsInvokeRequest() - payload, err := queryChaincodeWithTarget(reqCtx, cir, peer, options) + payload, err := queryChaincodeWithTarget(reqCtx, cir, peer, optionsValue) if err != nil { return nil, errors.WithMessage(err, "cscc.GetChannels failed") } @@ -293,10 +293,10 @@ func QueryInstalledChaincodes(reqCtx reqContext.Context, peer fab.ProposalProces return nil, errors.New("peer required") } - options := getOpts(opts...) + optionsValue := getOpts(opts...) cir := createInstalledChaincodesInvokeRequest() - payload, err := queryChaincodeWithTarget(reqCtx, cir, peer, options) + payload, err := queryChaincodeWithTarget(reqCtx, cir, peer, optionsValue) if err != nil { return nil, errors.WithMessage(err, "lscc.getinstalledchaincodes failed") } @@ -351,9 +351,9 @@ func InstallChaincode(reqCtx reqContext.Context, req api.InstallChaincodeRequest return nil, fab.EmptyTransactionID, errors.WithMessage(err, "creation of install chaincode proposal failed") } - options := getOpts(opts...) + optionsValue := getOpts(opts...) - resp, err := retry.NewInvoker(retry.New(options.retry)).Invoke( + resp, err := retry.NewInvoker(retry.New(optionsValue.retry)).Invoke( func() (interface{}, error) { return txn.SendProposal(reqCtx, prop, targets) }, @@ -411,9 +411,9 @@ func validateResponse(response *fab.TransactionProposalResponse) error { } func getOpts(opts ...Opt) options { - var options options + var optionsValue options for _, opt := range opts { - opt(&options) + opt(&optionsValue) } - return options + return optionsValue } diff --git a/pkg/fab/signingmgr/signingmgr.go b/pkg/fab/signingmgr/signingmgr.go index 3ff6f2d737..29054cb455 100644 --- a/pkg/fab/signingmgr/signingmgr.go +++ b/pkg/fab/signingmgr/signingmgr.go @@ -31,7 +31,7 @@ func New(cryptoProvider core.CryptoSuite) (*SigningManager, error) { // Sign will sign the given object using provided key func (mgr *SigningManager) Sign(object []byte, key core.Key) ([]byte, error) { - if object == nil || len(object) == 0 { + if len(object) == 0 { return nil, errors.New("object (to sign) required") } diff --git a/pkg/fab/txn/env.go b/pkg/fab/txn/env.go index 55e27b82a7..17b0e0c790 100644 --- a/pkg/fab/txn/env.go +++ b/pkg/fab/txn/env.go @@ -163,7 +163,7 @@ func CreateChannelHeader(headerType common.HeaderType, opts ChannelHeaderOpts) ( } // createHeader creates a Header from a ChannelHeader. -func createHeader(th *TransactionHeader, channelHeader *common.ChannelHeader) (*common.Header, error) { +func createHeader(th *TransactionHeader, channelHeader *common.ChannelHeader) (*common.Header, error) { //nolint signatureHeader := &common.SignatureHeader{ Creator: th.creator, diff --git a/pkg/fab/txn/proposal_test.go b/pkg/fab/txn/proposal_test.go index 47ea3945ea..8513e8542a 100644 --- a/pkg/fab/txn/proposal_test.go +++ b/pkg/fab/txn/proposal_test.go @@ -28,7 +28,6 @@ import ( const ( testChannel = "testchannel" - testAddress = "127.0.0.1:0" ) func TestNewTransactionProposal(t *testing.T) { @@ -89,12 +88,12 @@ func TestSendTransactionProposal(t *testing.T) { reqCtx, cancel := context.NewRequest(ctx, context.WithTimeout(10*time.Second)) defer cancel() - tpr, err := SendProposal(reqCtx, tp, []fab.ProposalProcessor{nil}) + _, err = SendProposal(reqCtx, tp, []fab.ProposalProcessor{nil}) if err == nil || !strings.Contains(err.Error(), "target is nil") { t.Fatalf("Should have failed due to nil target") } - tpr, err = SendProposal(reqCtx, tp, []fab.ProposalProcessor{&peer}) + tpr, err := SendProposal(reqCtx, tp, []fab.ProposalProcessor{&peer}) if err != nil { t.Fatalf("send transaction proposal failed: %s", err) } @@ -137,7 +136,7 @@ func TestNewTransactionProposalParams(t *testing.T) { Fcn: "Hello", } - tp, err = CreateChaincodeInvokeProposal(txh, request) + _, err = CreateChaincodeInvokeProposal(txh, request) if err == nil { t.Fatalf("Expected error") } @@ -146,7 +145,7 @@ func TestNewTransactionProposalParams(t *testing.T) { ChaincodeID: "cc", } - tp, err = CreateChaincodeInvokeProposal(txh, request) + _, err = CreateChaincodeInvokeProposal(txh, request) if err == nil { t.Fatalf("Expected error") } @@ -155,7 +154,7 @@ func TestNewTransactionProposalParams(t *testing.T) { ChaincodeID: "cc", Fcn: "Hello", } - tp, err = CreateChaincodeInvokeProposal(txh, request) + _, err = CreateChaincodeInvokeProposal(txh, request) if err != nil { t.Fatalf("new transaction proposal failed: %s", err) } diff --git a/pkg/fab/txn/txn.go b/pkg/fab/txn/txn.go index a46933dd3f..a269e6c87c 100644 --- a/pkg/fab/txn/txn.go +++ b/pkg/fab/txn/txn.go @@ -100,7 +100,7 @@ func New(request fab.TransactionRequest) (*fab.Transaction, error) { // Send send a transaction to the chain’s orderer service (one or more orderer endpoints) for consensus and committing to the ledger. func Send(reqCtx reqContext.Context, tx *fab.Transaction, orderers []fab.Orderer) (*fab.TransactionResponse, error) { - if orderers == nil || len(orderers) == 0 { + if len(orderers) == 0 { return nil, errors.New("orderers is nil") } if tx == nil { @@ -162,9 +162,7 @@ func broadcastEnvelope(reqCtx reqContext.Context, envelope *fab.SignedEnvelope, // Copy aside the ordering service endpoints randOrderers := []fab.Orderer{} - for _, o := range orderers { - randOrderers = append(randOrderers, o) - } + randOrderers = append(randOrderers, orderers...) // Iterate them in a random order and try broadcasting 1 by 1 var errResp error @@ -193,7 +191,7 @@ func sendBroadcast(reqCtx reqContext.Context, envelope *fab.SignedEnvelope, orde // SendPayload sends the given payload to each orderer and returns a block response func SendPayload(reqCtx reqContext.Context, payload *common.Payload, orderers []fab.Orderer) (*common.Block, error) { - if orderers == nil || len(orderers) == 0 { + if len(orderers) == 0 { return nil, errors.New("orderers not set") } @@ -208,9 +206,7 @@ func SendPayload(reqCtx reqContext.Context, payload *common.Payload, orderers [] // Copy aside the ordering service endpoints randOrderers := []fab.Orderer{} - for _, o := range orderers { - randOrderers = append(randOrderers, o) - } + randOrderers = append(randOrderers, orderers...) // Iterate them in a random order and try broadcasting 1 by 1 var errResp error diff --git a/pkg/fab/txn/txn_test.go b/pkg/fab/txn/txn_test.go index ef09970f7c..26fdf23408 100644 --- a/pkg/fab/txn/txn_test.go +++ b/pkg/fab/txn/txn_test.go @@ -7,7 +7,7 @@ SPDX-License-Identifier: Apache-2.0 package txn import ( - "crypto/rand" + reqContext "context" "fmt" "os" "strconv" @@ -106,39 +106,29 @@ func TestNewTransaction(t *testing.T) { } //Test repeated field header nil scenario + checkRepeatedFieldHeader(proposal, th, proposalResp, txnReq, t) + + //TODO: Need actual sample payload for success case + +} + +func checkRepeatedFieldHeader(proposal fab.TransactionProposal, th TransactionHeader, proposalResp fab.TransactionProposalResponse, txnReq fab.TransactionRequest, t *testing.T) { proposal = fab.TransactionProposal{ TxnID: fab.TransactionID(th.id), Proposal: &pb.Proposal{Header: []byte(""), Extension: []byte(""), Payload: []byte("")}, } - proposalResp = fab.TransactionProposalResponse{ Endorser: "http://peer1.com", ProposalResponse: &pb.ProposalResponse{Response: &pb.Response{Message: "success", Status: 200, Payload: []byte("")}}, } - txnReq = fab.TransactionRequest{ Proposal: &proposal, ProposalResponses: []*fab.TransactionProposalResponse{&proposalResp}, } - _, err = New(txnReq) + _, err := New(txnReq) if err == nil || err.Error() != "repeated field endorsements has nil element" { t.Fatal("Proposal response was supposed to fail in Create Transaction") } - - //TODO: Need actual sample payload for success case - -} - -type mockReader struct { - err error -} - -func (r *mockReader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - n, _ := rand.Read(p) - return n, nil } func TestBroadcastEnvelope(t *testing.T) { @@ -191,27 +181,28 @@ func TestBroadcastEnvelope(t *testing.T) { } // It should always succeed even though one of them has failed for i := 0; i < broadcastCount; i++ { - if res, err := broadcastEnvelope(reqCtx, sigEnvelope, orderers); err != nil { - t.Fatalf("Test Broadcast Envelope Failed, cause %v %v", err, res) + if res, err1 := broadcastEnvelope(reqCtx, sigEnvelope, orderers); err1 != nil { + t.Fatalf("Test Broadcast Envelope Failed, cause %v %v", err1, res) } } // Now, fail both and ensure any attempt fails + checkBroadcastCount(broadcastCount, orderer1, orderer2, reqCtx, sigEnvelope, orderers, t) +} + +func checkBroadcastCount(broadcastCount int, orderer1 *mocks.MockOrderer, orderer2 *mocks.MockOrderer, reqCtx reqContext.Context, sigEnvelope *fab.SignedEnvelope, orderers []fab.Orderer, t *testing.T) { for i := 0; i < broadcastCount; i++ { orderer1.EnqueueSendBroadcastError(errors.New("Service Unavailable")) orderer2.EnqueueSendBroadcastError(errors.New("Service Unavailable")) } - for i := 0; i < broadcastCount; i++ { - _, err := broadcastEnvelope(reqCtx, sigEnvelope, orderers) - if !strings.Contains(err.Error(), "Service Unavailable") { + _, err1 := broadcastEnvelope(reqCtx, sigEnvelope, orderers) + if !strings.Contains(err1.Error(), "Service Unavailable") { t.Fatal("Test Broadcast failed but didn't return the correct reason(should contain 'Service Unavailable')") } } - emptyOrderers := []fab.Orderer{} - _, err = broadcastEnvelope(reqCtx, sigEnvelope, emptyOrderers) - + _, err := broadcastEnvelope(reqCtx, sigEnvelope, emptyOrderers) if err == nil || err.Error() != "orderers not set" { t.Fatal("orderers not set validation on broadcast envelope is not working as expected") } @@ -244,6 +235,10 @@ func TestSendTransaction(t *testing.T) { t.Fatal("Test SendTransaction failed, it was supposed to fail with 'transaction is nil' error") } + testSendTransaction(reqCtx, orderers, t) +} + +func testSendTransaction(reqCtx reqContext.Context, orderers []fab.Orderer, t *testing.T) { //Create tx with nil proposal txn := fab.Transaction{ Proposal: &fab.TransactionProposal{ @@ -251,15 +246,12 @@ func TestSendTransaction(t *testing.T) { }, Transaction: &pb.Transaction{}, } - //Call Send Transaction with nil proposal - response, err = Send(reqCtx, &txn, orderers) - + response, err := Send(reqCtx, &txn, orderers) //Expect proposal is nil error if response != nil || err == nil || err.Error() != "proposal is nil" { t.Fatal("Test SendTransaction failed, it was supposed to fail with 'proposal is nil' error") } - //Create tx with improper proposal header txn = fab.Transaction{ Proposal: &fab.TransactionProposal{ @@ -269,12 +261,10 @@ func TestSendTransaction(t *testing.T) { } //Call Send Transaction response, err = Send(reqCtx, &txn, orderers) - //Expect header unmarshal error if response != nil || err == nil || !strings.Contains(err.Error(), "unmarshal") { t.Fatal("Test SendTransaction failed, it was supposed to fail with '...unmarshal...' error") } - //Create tx with proper proposal header txn = fab.Transaction{ Proposal: &fab.TransactionProposal{ @@ -282,10 +272,8 @@ func TestSendTransaction(t *testing.T) { }, Transaction: &pb.Transaction{}, } - //Call Send Transaction response, err = Send(reqCtx, &txn, orderers) - if response == nil || err != nil { t.Fatalf("Test SendTransaction failed, reason : '%s'", err.Error()) } diff --git a/test/scripts/check_lint.sh b/test/scripts/check_lint.sh index 9f38a1a7b0..8c165ac69d 100755 --- a/test/scripts/check_lint.sh +++ b/test/scripts/check_lint.sh @@ -69,12 +69,7 @@ declare -a arr1=( "./pkg/common" "./pkg/context" "./pkg/core" -"./pkg/fab/ccpackager" -"./pkg/fab/channel" -"./pkg/fab/chconfig" -"./pkg/fab/comm" -"./pkg/fab/events" -"./pkg/fab/keyvaluestore" +"./pkg/fab" )