Skip to content

Commit

Permalink
[FAB-3279]: Fix gossip related golint warnings
Browse files Browse the repository at this point in the history
There are quite a few gossip related golint warnings
produced during the validation. This commit takes care
to fix them.

Change-Id: I9c224cc7bb709688f2d7ff93d4740472ebea9d3c
Signed-off-by: Artem Barger <bartem@il.ibm.com>
  • Loading branch information
C0rWin committed Apr 20, 2017
1 parent e4074ce commit 847bc16
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 52 deletions.
2 changes: 1 addition & 1 deletion gossip/comm/comm_test.go
Expand Up @@ -192,7 +192,7 @@ func TestViperConfig(t *testing.T) {
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
panic(fmt.Errorf("fatal error config file: %s", err))
}

assert.Equal(t, time.Duration(2)*time.Second, util.GetDurationOrDefault("peer.gossip.connTimeout", 0))
Expand Down
8 changes: 4 additions & 4 deletions gossip/discovery/discovery.go
Expand Up @@ -90,11 +90,11 @@ func (n *NetworkMember) String() string {
// PreferredEndpoint computes the endpoint to connect to,
// while preferring internal endpoint over the standard
// endpoint
func (nm NetworkMember) PreferredEndpoint() string {
if nm.InternalEndpoint != "" {
return nm.InternalEndpoint
func (n NetworkMember) PreferredEndpoint() string {
if n.InternalEndpoint != "" {
return n.InternalEndpoint
}
return nm.Endpoint
return n.Endpoint
}

// Discovery is the interface that represents a discovery module
Expand Down
8 changes: 8 additions & 0 deletions gossip/election/election.go
Expand Up @@ -383,18 +383,25 @@ func (le *leaderElectionSvcImpl) Stop() {
le.stopWG.Wait()
}

// SetStartupGracePeriod configures startup grace period interval,
// the period of time to wait until election algorithm will start
func SetStartupGracePeriod(t time.Duration) {
viper.Set("peer.gossip.election.startupGracePeriod", t)
}

// SetMembershipSampleInterval setups/initializes the frequency the
// membership view should be checked
func SetMembershipSampleInterval(t time.Duration) {
viper.Set("peer.gossip.election.membershipSampleInterval", t)
}

// SetLeaderAliveThreshold configures leader election alive threshold
func SetLeaderAliveThreshold(t time.Duration) {
viper.Set("peer.gossip.election.leaderAliveThreshold", t)
}

// SetLeaderElectionDuration configures expected leadership election duration,
// interval to wait until leader election will be completed
func SetLeaderElectionDuration(t time.Duration) {
viper.Set("peer.gossip.election.leaderElectionDuration", t)
}
Expand All @@ -419,6 +426,7 @@ func getLeaderElectionDuration() time.Duration {
return util.GetDurationOrDefault("peer.gossip.election.leaderElectionDuration", time.Second*5)
}

// GetMsgExpirationTimeout return leadership message expiration timeout
func GetMsgExpirationTimeout() time.Duration {
return getLeaderAliveThreshold() * 10
}
2 changes: 1 addition & 1 deletion gossip/gossip/certstore_test.go
Expand Up @@ -109,7 +109,7 @@ func TestCertStoreShouldSucceed(t *testing.T) {
}

func testCertificateUpdate(t *testing.T, updateFactory func(uint64) proto.ReceivedMessage, shouldSucceed bool) {
config := pull.PullConfig{
config := pull.Config{
MsgType: proto.PullMsgType_IDENTITY_MSG,
PeerCountToSelect: 1,
PullInterval: time.Millisecond * 500,
Expand Down
14 changes: 7 additions & 7 deletions gossip/gossip/channel/channel.go
Expand Up @@ -257,7 +257,7 @@ func (gc *gossipChannel) publishStateInfo() {
}

func (gc *gossipChannel) createBlockPuller() pull.Mediator {
conf := pull.PullConfig{
conf := pull.Config{
MsgType: proto.PullMsgType_BLOCK_MSG,
Channel: []byte(gc.chainID),
ID: gc.GetConf().ID,
Expand Down Expand Up @@ -491,7 +491,7 @@ func (gc *gossipChannel) handleStateInfSnapshot(m *proto.GossipMessage, sender c
return
}

expectedMAC := ChannelMAC(si.PkiId, gc.chainID)
expectedMAC := GenerateMAC(si.PkiId, gc.chainID)
if !bytes.Equal(si.ChannelMAC, expectedMAC) {
gc.logger.Warning("Channel", chanName, ": StateInfo message", stateInf,
", has an invalid MAC. Expected", expectedMAC, ", got", si.ChannelMAC, ", sent from", sender)
Expand Down Expand Up @@ -561,7 +561,7 @@ func (gc *gossipChannel) verifyMsg(msg proto.ReceivedMessage) bool {

if m.IsStateInfoMsg() {
si := m.GetStateInfo()
expectedMAC := ChannelMAC(si.PkiId, gc.chainID)
expectedMAC := GenerateMAC(si.PkiId, gc.chainID)
if !bytes.Equal(expectedMAC, si.ChannelMAC) {
gc.logger.Warning("Message contains wrong channel MAC(", si.ChannelMAC, "), expected", expectedMAC)
return false
Expand All @@ -571,7 +571,7 @@ func (gc *gossipChannel) verifyMsg(msg proto.ReceivedMessage) bool {

if m.IsStateInfoPullRequestMsg() {
sipr := m.GetStateInfoPullReq()
expectedMAC := ChannelMAC(msg.GetConnectionInfo().ID, gc.chainID)
expectedMAC := GenerateMAC(msg.GetConnectionInfo().ID, gc.chainID)
if !bytes.Equal(expectedMAC, sipr.ChannelMAC) {
gc.logger.Warning("Message contains wrong channel MAC(", sipr.ChannelMAC, "), expected", expectedMAC)
return false
Expand All @@ -592,7 +592,7 @@ func (gc *gossipChannel) createStateInfoRequest() *proto.SignedGossipMessage {
Nonce: 0,
Content: &proto.GossipMessage_StateInfoPullReq{
StateInfoPullReq: &proto.StateInfoPullRequest{
ChannelMAC: ChannelMAC(gc.pkiID, gc.chainID),
ChannelMAC: GenerateMAC(gc.pkiID, gc.chainID),
},
},
}).NoopSign()
Expand Down Expand Up @@ -658,9 +658,9 @@ func (cache *stateInfoCache) Add(msg *proto.SignedGossipMessage) bool {
return added
}

// ChannelMAC returns a byte slice that is derived from the peer's PKI-ID
// GenerateMAC returns a byte slice that is derived from the peer's PKI-ID
// and a channel name
func ChannelMAC(pkiID common.PKIidType, channelID common.ChainID) []byte {
func GenerateMAC(pkiID common.PKIidType, channelID common.ChainID) []byte {
// Hash is computed on (PKI-ID || channel ID)
preImage := append([]byte(pkiID), []byte(channelID)...)
return common_utils.ComputeSHA256(preImage)
Expand Down
10 changes: 5 additions & 5 deletions gossip/gossip/channel/channel_test.go
Expand Up @@ -434,7 +434,7 @@ func TestChannelPeerNotInChannel(t *testing.T) {

// Ensure we don't respond to a StateInfoRequest in the wrong channel from a peer in the right org
req2 := gc.(*gossipChannel).createStateInfoRequest()
req2.GetStateInfoPullReq().ChannelMAC = ChannelMAC(pkiIDInOrg1, common.ChainID("B"))
req2.GetStateInfoPullReq().ChannelMAC = GenerateMAC(pkiIDInOrg1, common.ChainID("B"))
invalidReceivedMsg2 := &receivedMsg{
msg: req2,
PKIID: pkiIDInOrg1,
Expand Down Expand Up @@ -809,7 +809,7 @@ func TestChannelStateInfoSnapshot(t *testing.T) {
Tag: proto.GossipMessage_CHAN_OR_ORG,
Content: &proto.GossipMessage_StateInfoPullReq{
StateInfoPullReq: &proto.StateInfoPullRequest{
ChannelMAC: append(ChannelMAC(pkiIDInOrg1, channelA), 1),
ChannelMAC: append(GenerateMAC(pkiIDInOrg1, channelA), 1),
},
},
}).NoopSign(),
Expand All @@ -832,7 +832,7 @@ func TestChannelStateInfoSnapshot(t *testing.T) {
Tag: proto.GossipMessage_CHAN_OR_ORG,
Content: &proto.GossipMessage_StateInfoPullReq{
StateInfoPullReq: &proto.StateInfoPullRequest{
ChannelMAC: ChannelMAC(pkiIDInOrg1, channelA),
ChannelMAC: GenerateMAC(pkiIDInOrg1, channelA),
},
},
}).NoopSign(),
Expand Down Expand Up @@ -1083,7 +1083,7 @@ func TestChannelGetPeers(t *testing.T) {
// and ensure that the StateInfo message doesn't count
gc = NewGossipChannel(pkiIDInOrg1, cs, channelA, adapter, &joinChanMsg{})
msg := &receivedMsg{PKIID: pkiIDInOrg1, msg: createStateInfoMsg(1, pkiIDInOrg1, channelA)}
msg.GetGossipMessage().GetStateInfo().ChannelMAC = ChannelMAC(pkiIDinOrg2, channelA)
msg.GetGossipMessage().GetStateInfo().ChannelMAC = GenerateMAC(pkiIDinOrg2, channelA)
gc.HandleMessage(msg)
assert.Len(t, gc.GetPeers(), 0)
}
Expand Down Expand Up @@ -1201,7 +1201,7 @@ func createStateInfoMsg(ledgerHeight int, pkiID common.PKIidType, channel common
Tag: proto.GossipMessage_CHAN_OR_ORG,
Content: &proto.GossipMessage_StateInfo{
StateInfo: &proto.StateInfo{
ChannelMAC: ChannelMAC(pkiID, channel),
ChannelMAC: GenerateMAC(pkiID, channel),
Timestamp: &proto.PeerTime{IncNumber: uint64(time.Now().UnixNano()), SeqNum: 1},
Metadata: []byte(fmt.Sprintf("%d", ledgerHeight)),
PkiId: []byte(pkiID),
Expand Down
2 changes: 1 addition & 1 deletion gossip/gossip/chanstate.go
Expand Up @@ -86,7 +86,7 @@ func (cs *channelState) getGossipChannelByMAC(receivedMAC []byte, pkiID common.P
cs.RLock()
defer cs.RUnlock()
for chanName, gc := range cs.channels {
mac := channel.ChannelMAC(pkiID, common.ChainID(chanName))
mac := channel.GenerateMAC(pkiID, common.ChainID(chanName))
if bytes.Equal(mac, receivedMAC) {
return gc
}
Expand Down
4 changes: 2 additions & 2 deletions gossip/gossip/gossip_impl.go
Expand Up @@ -912,7 +912,7 @@ func (sa *discoverySecurityAdapter) validateAliveMsgSignature(m *proto.SignedGos
}

func (g *gossipServiceImpl) createCertStorePuller() pull.Mediator {
conf := pull.PullConfig{
conf := pull.Config{
MsgType: proto.PullMsgType_IDENTITY_MSG,
Channel: []byte(""),
ID: g.conf.InternalEndpoint,
Expand Down Expand Up @@ -952,7 +952,7 @@ func (g *gossipServiceImpl) createCertStorePuller() pull.Mediator {
func (g *gossipServiceImpl) createStateInfoMsg(metadata []byte, chainID common.ChainID) (*proto.SignedGossipMessage, error) {
pkiID := g.comm.GetPKIid()
stateInfMsg := &proto.StateInfo{
ChannelMAC: channel.ChannelMAC(pkiID, chainID),
ChannelMAC: channel.GenerateMAC(pkiID, chainID),
Metadata: metadata,
PkiId: g.comm.GetPKIid(),
Timestamp: &proto.PeerTime{
Expand Down
2 changes: 1 addition & 1 deletion gossip/gossip/orgs_test.go
Expand Up @@ -61,7 +61,7 @@ func (c *configurableCryptoService) OrgByPeerIdentity(identity api.PeerIdentityT

// VerifyByChannel verifies a peer's signature on a message in the context
// of a specific channel
func (cs *configurableCryptoService) VerifyByChannel(_ common.ChainID, identity api.PeerIdentityType, _, _ []byte) error {
func (c *configurableCryptoService) VerifyByChannel(_ common.ChainID, identity api.PeerIdentityType, _, _ []byte) error {
return nil
}

Expand Down
42 changes: 21 additions & 21 deletions gossip/gossip/pull/pullstore.go
Expand Up @@ -31,14 +31,14 @@ import (

// Constants go here.
const (
HelloMsgType PullMsgType = iota
HelloMsgType MsgType = iota
DigestMsgType
RequestMsgType
ResponseMsgType
)

// PullMsgType defines the type of a message that is sent to the PullStore
type PullMsgType int
// MsgType defines the type of a message that is sent to the PullStore
type MsgType int

// MessageHook defines a function that will run after a certain pull message is received
type MessageHook func(itemIDs []string, items []*proto.SignedGossipMessage, msg proto.ReceivedMessage)
Expand All @@ -55,6 +55,16 @@ type MembershipService interface {
GetMembership() []discovery.NetworkMember
}

// Config defines the configuration of the pull mediator
type Config struct {
ID string
PullInterval time.Duration // Duration between pull invocations
PeerCountToSelect int // Number of peers to initiate pull with
Tag proto.GossipMessage_Tag
Channel common.ChainID
MsgType proto.PullMsgType
}

// DigestFilter filters digests to be sent to a remote peer, that
// sent a hello with the following message
type DigestFilter func(helloMsg proto.ReceivedMessage) func(digestItem string) bool
Expand All @@ -68,16 +78,6 @@ func (df DigestFilter) byContext() algo.DigestFilter {
}
}

// PullConfig defines the configuration of the pull mediator
type PullConfig struct {
ID string
PullInterval time.Duration // Duration between pull invocations
PeerCountToSelect int // Number of peers to initiate pull with
Tag proto.GossipMessage_Tag
Channel common.ChainID
MsgType proto.PullMsgType
}

// PullAdapter defines methods of the pullStore to interact
// with various modules of gossip
type PullAdapter struct {
Expand All @@ -99,7 +99,7 @@ type Mediator interface {
Stop()

// RegisterMsgHook registers a message hook to a specific type of pull message
RegisterMsgHook(PullMsgType, MessageHook)
RegisterMsgHook(MsgType, MessageHook)

// Add adds a GossipMessage to the Mediator
Add(*proto.SignedGossipMessage)
Expand All @@ -115,18 +115,18 @@ type Mediator interface {
type pullMediatorImpl struct {
sync.RWMutex
Sender
msgType2Hook map[PullMsgType][]MessageHook
msgType2Hook map[MsgType][]MessageHook
idExtractor proto.IdentifierExtractor
msgCons proto.MsgConsumer
config PullConfig
config Config
logger *logging.Logger
itemID2Msg map[string]*proto.SignedGossipMessage
memBvc MembershipService
engine *algo.PullEngine
}

// NewPullMediator returns a new Mediator
func NewPullMediator(config PullConfig, adapter PullAdapter) Mediator {
func NewPullMediator(config Config, adapter PullAdapter) Mediator {
digFilter := adapter.DigFilter

acceptAllFilter := func(_ proto.ReceivedMessage) func(string) bool {
Expand All @@ -141,7 +141,7 @@ func NewPullMediator(config PullConfig, adapter PullAdapter) Mediator {

p := &pullMediatorImpl{
msgCons: adapter.MsgCons,
msgType2Hook: make(map[PullMsgType][]MessageHook),
msgType2Hook: make(map[MsgType][]MessageHook),
idExtractor: adapter.IdExtractor,
config: config,
logger: util.GetLogger(util.LoggingPullModule, config.ID),
Expand Down Expand Up @@ -169,7 +169,7 @@ func (p *pullMediatorImpl) HandleMessage(m proto.ReceivedMessage) {

itemIDs := []string{}
items := []*proto.SignedGossipMessage{}
var pullMsgType PullMsgType
var pullMsgType MsgType

if helloMsg := msg.GetHello(); helloMsg != nil {
pullMsgType = HelloMsgType
Expand Down Expand Up @@ -216,7 +216,7 @@ func (p *pullMediatorImpl) Stop() {
}

// RegisterMsgHook registers a message hook to a specific type of pull message
func (p *pullMediatorImpl) RegisterMsgHook(pullMsgType PullMsgType, hook MessageHook) {
func (p *pullMediatorImpl) RegisterMsgHook(pullMsgType MsgType, hook MessageHook) {
p.Lock()
defer p.Unlock()
p.msgType2Hook[pullMsgType] = append(p.msgType2Hook[pullMsgType], hook)
Expand Down Expand Up @@ -348,7 +348,7 @@ func (p *pullMediatorImpl) peersWithEndpoints(endpoints ...string) []*comm.Remot
return peers
}

func (p *pullMediatorImpl) hooksByMsgType(msgType PullMsgType) []MessageHook {
func (p *pullMediatorImpl) hooksByMsgType(msgType MsgType) []MessageHook {
p.RLock()
defer p.RUnlock()
returnedHooks := []MessageHook{}
Expand Down
4 changes: 2 additions & 2 deletions gossip/gossip/pull/pullstore_test.go
Expand Up @@ -121,7 +121,7 @@ func createPullInstanceWithFilters(endpoint string, peer2PullInst map[string]*pu

peer2PullInst[endpoint] = inst

conf := PullConfig{
conf := Config{
MsgType: proto.PullMsgType_BLOCK_MSG,
Channel: []byte(""),
ID: endpoint,
Expand Down Expand Up @@ -179,7 +179,7 @@ func TestRegisterMsgHook(t *testing.T) {

receivedMsgTypes := util.NewSet()

for _, msgType := range []PullMsgType{HelloMsgType, DigestMsgType, RequestMsgType, ResponseMsgType} {
for _, msgType := range []MsgType{HelloMsgType, DigestMsgType, RequestMsgType, ResponseMsgType} {
mType := msgType
inst1.mediator.RegisterMsgHook(mType, func(_ []string, items []*proto.SignedGossipMessage, _ proto.ReceivedMessage) {
receivedMsgTypes.Add(mType)
Expand Down
2 changes: 1 addition & 1 deletion gossip/integration/integration_test.go
Expand Up @@ -77,7 +77,7 @@ func setupTestEnv() {
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
panic(fmt.Errorf("fatal error config file: %s", err))
}
}

Expand Down
2 changes: 1 addition & 1 deletion gossip/service/gossip_service.go
Expand Up @@ -125,7 +125,7 @@ func InitGossipService(peerIdentity []byte, endpoint string, s *grpc.Server, mcs
InitGossipServiceCustomDeliveryFactory(peerIdentity, endpoint, s, &deliveryFactoryImpl{}, mcs, bootPeers...)
}

// InitGossipService initialize gossip service with customize delivery factory
// InitGossipServiceCustomDeliveryFactory initialize gossip service with customize delivery factory
// implementation, might be useful for testing and mocking purposes
func InitGossipServiceCustomDeliveryFactory(peerIdentity []byte, endpoint string, s *grpc.Server, factory DeliveryServiceFactory, mcs api.MessageCryptoService, bootPeers ...string) {
once.Do(func() {
Expand Down
4 changes: 2 additions & 2 deletions gossip/service/gossip_service_test.go
Expand Up @@ -449,12 +449,12 @@ func (jmc *joinChanMsg) SequenceNumber() uint64 {
}

// Members returns the organizations of the channel
func (jcm *joinChanMsg) Members() []api.OrgIdentityType {
func (jmc *joinChanMsg) Members() []api.OrgIdentityType {
return []api.OrgIdentityType{orgInChannelA}
}

// AnchorPeersOf returns the anchor peers of the given organization
func (jcm *joinChanMsg) AnchorPeersOf(org api.OrgIdentityType) []api.AnchorPeer {
func (jmc *joinChanMsg) AnchorPeersOf(org api.OrgIdentityType) []api.AnchorPeer {
return []api.AnchorPeer{}
}

Expand Down
2 changes: 1 addition & 1 deletion gossip/state/state.go
Expand Up @@ -562,7 +562,7 @@ func (s *GossipStateProviderImpl) selectPeerToRequestFrom(height uint64) (*comm.

n := len(peers)
if n == 0 {
return nil, errors.New("There are no peers to ask for missing blocks from.")
return nil, errors.New("there are no peers to ask for missing blocks from")
}

// Select peers to ask for blocks
Expand Down
2 changes: 1 addition & 1 deletion gossip/util/misc.go
Expand Up @@ -151,7 +151,7 @@ func GetIntOrDefault(key string, defVal int) int {
return defVal
}

// GetIntOrDefault returns the Duration value from config if present otherwise default value
// GetDurationOrDefault returns the Duration value from config if present otherwise default value
func GetDurationOrDefault(key string, defVal time.Duration) time.Duration {
if val := viper.GetDuration(key); val != 0 {
return val
Expand Down

0 comments on commit 847bc16

Please sign in to comment.