Skip to content

Commit

Permalink
Additional Go linting (#201)
Browse files Browse the repository at this point in the history
Some cyclomatic or cognitive complexity failures are suppressed since
they are in existing code - some of which is lifted from Fabric
internals - and not trivially fixed as part of this change.

Closes #117

Signed-off-by: Mark S. Lewis <[email protected]>
  • Loading branch information
bestbeforetoday authored Sep 18, 2024
1 parent f896a39 commit b61ba94
Show file tree
Hide file tree
Showing 19 changed files with 191 additions and 118 deletions.
25 changes: 25 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
root = true

[*]
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
max_line_length = 120
indent_style = space
indent_size = 4

[Makefile]
indent_style = tab

[*.{yaml,yml}]
indent_size = 2

[*.html]
indent_size = 2

[*.md]
indent_size = 2

[*.{mj,cj,j,t}s]
quote_type = single
30 changes: 15 additions & 15 deletions .github/workflows/golang.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.20'
go-version: "1.21"
- name: Generate test mocks
run: make generate
- name: Unit test
Expand All @@ -22,7 +22,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.20'
go-version: stable
- name: Generate test mocks
run: make generate
- name: Staticcheck
Expand All @@ -38,29 +38,29 @@ jobs:
fail-fast: false
matrix:
include:
- FABRIC_VERSION: '2.5.3'
CREATE_CHANNEL: 'create_channel'
- FABRIC_VERSION: "2.5.3"
CREATE_CHANNEL: "create_channel"
CONSENSUS: RAFT
- FABRIC_VERSION: '2.5.3'
CREATE_CHANNEL: 'existing_channel'
- FABRIC_VERSION: "2.5.3"
CREATE_CHANNEL: "existing_channel"
CONSENSUS: RAFT
- FABRIC_VERSION: '3.0.0-preview'
CREATE_CHANNEL: 'create_channel'
- FABRIC_VERSION: "3.0.0-preview"
CREATE_CHANNEL: "create_channel"
CONSENSUS: RAFT
- FABRIC_VERSION: '3.0.0-preview'
CREATE_CHANNEL: 'existing_channel'
- FABRIC_VERSION: "3.0.0-preview"
CREATE_CHANNEL: "existing_channel"
CONSENSUS: RAFT
- FABRIC_VERSION: '3.0.0-preview'
CREATE_CHANNEL: 'create_channel'
- FABRIC_VERSION: "3.0.0-preview"
CREATE_CHANNEL: "create_channel"
CONSENSUS: BFT
- FABRIC_VERSION: '3.0.0-preview'
CREATE_CHANNEL: 'existing_channel'
- FABRIC_VERSION: "3.0.0-preview"
CREATE_CHANNEL: "existing_channel"
CONSENSUS: BFT
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.20'
go-version: "1.21"
- name: run end to end test
env:
FABRIC_VERSION: ${{matrix.FABRIC_VERSION}}
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ concurrency:
jobs:
go:
uses: ./.github/workflows/golang.yml

node:
uses: ./.github/workflows/node.yml

Expand All @@ -23,4 +23,4 @@ jobs:
name: Pull request success
runs-on: ubuntu-latest
steps:
- run: true
- run: "true"
5 changes: 3 additions & 2 deletions .github/workflows/schedule.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ name: Scheduled build

on:
schedule:
- cron: "10 01 * * *"
- cron: "10 01 * * 0"
workflow_dispatch:

jobs:
go:
uses: ./.github/workflows/golang.yml

node:
uses: ./.github/workflows/node.yml
2 changes: 1 addition & 1 deletion .github/workflows/vulnerability-scan.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Security vulnerability scan

on:
schedule:
- cron: '20 02 * * *'
- cron: "20 02 * * 0"
workflow_dispatch:

permissions:
Expand Down
18 changes: 16 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,23 @@ run:
timeout: 5m

linters:
disable-all: true
enable:
- errcheck
- gocognit
- gocyclo
- gofmt
- goimports
- gosec
disable:
- staticcheck
- gosimple
- govet
- ineffassign
- misspell
- typecheck
- unused

linters-settings:
gocognit:
min-complexity: 15
gocyclo:
min-complexity: 10
7 changes: 6 additions & 1 deletion internal/configtxgen/encoder/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ func NewConfigGroup() *cb.ConfigGroup {
// NewOrdererGroup, NewConsortiumsGroup, and NewApplicationGroup depending on whether these sub-elements are set in the
// configuration. All mod_policy values are set to "Admins" for this group, with the exception of the OrdererAddresses
// value which is set to "/Channel/Orderer/Admins".
//
//nolint:gocyclo
func NewChannelGroup(conf *genesisconfig.Profile) (*cb.ConfigGroup, error) {
channelGroup := NewConfigGroup()
if err := AddPolicies(channelGroup, conf.Policies, icc.AdminsPolicyKey); err != nil {
Expand Down Expand Up @@ -182,6 +184,8 @@ func NewChannelGroup(conf *genesisconfig.Profile) (*cb.ConfigGroup, error) {
// NewOrdererGroup returns the orderer component of the channel configuration. It defines parameters of the ordering service
// about how large blocks should be, how frequently they should be emitted, etc. as well as the organizations of the ordering network.
// It sets the mod_policy of all elements to "Admins". This group is always present in any channel configuration.
//
//nolint:gocyclo
func NewOrdererGroup(conf *genesisconfig.Orderer) (*cb.ConfigGroup, error) {
ordererGroup := NewConfigGroup()
if err := AddOrdererPolicies(ordererGroup, conf.Policies, icc.AdminsPolicyKey); err != nil {
Expand Down Expand Up @@ -341,7 +345,7 @@ func NewApplicationOrgGroup(conf *genesisconfig.Organization) (*cb.ConfigGroup,
for _, anchorPeer := range conf.AnchorPeers {
anchorProtos = append(anchorProtos, &pb.AnchorPeer{
Host: anchorPeer.Host,
Port: int32(anchorPeer.Port),
Port: anchorPeer.Port,
})
}

Expand Down Expand Up @@ -555,6 +559,7 @@ func (bs *Bootstrapper) GenesisBlockForChannel(channelID string) *cb.Block {
return genesis.NewFactoryImpl(bs.channelGroup).Block(channelID)
}

//nolint:gocognit
func consenterProtosFromConfig(consenterMapping []*genesisconfig.Consenter) ([]*cb.Consenter, error) {
var consenterProtos []*cb.Consenter
for _, consenter := range consenterMapping {
Expand Down
5 changes: 3 additions & 2 deletions internal/configtxgen/genesisconfig/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ type Organization struct {
// AnchorPeer encodes the necessary fields to identify an anchor peer.
type AnchorPeer struct {
Host string `yaml:"Host"`
Port int `yaml:"Port"`
Port int32 `yaml:"Port"`
}

// Orderer contains configuration associated to a channel.
Expand Down Expand Up @@ -260,7 +260,7 @@ func Load(profile string, configPaths ...string) (*Profile, error) {

result, ok := uconf.Profiles[profile]
if !ok {
panic(fmt.Errorf("Could not find profile: " + profile))
panic(fmt.Errorf("could not find profile: %s", profile))
}

result.completeInitialization(filepath.Dir(config.ConfigFileUsed()))
Expand Down Expand Up @@ -316,6 +316,7 @@ func (org *Organization) completeInitialization(configDir string) {
translatePaths(configDir, org)
}

//nolint:gocognit,gocyclo
func (ord *Orderer) completeInitialization(configDir string) {
loop:
for {
Expand Down
2 changes: 2 additions & 0 deletions internal/configtxgen/viperutil/config_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ func (c *ConfigParser) getFromEnv(key string) string {
// Prototype declaration for getFromEnv function.
type envGetter func(key string) string

//nolint:gocognit,gocyclo
func getKeysRecursively(base string, getenv envGetter, nodeKeys map[string]interface{}, oType reflect.Type) map[string]interface{} {
subTypes := map[string]reflect.Type{}

Expand Down Expand Up @@ -296,6 +297,7 @@ func stringFromFileDecodeHook(f reflect.Kind, t reflect.Kind, data interface{})
return data, nil
}

//nolint:gocognit,gocyclo
func pemBlocksFromFileDecodeHook(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
// "to" type should be string
if t != reflect.Slice {
Expand Down
32 changes: 12 additions & 20 deletions internal/configtxlator/update/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,7 @@ func computeGroupUpdate(original, updated *common.ConfigGroup) (readSet, writeSe
if !(policiesMembersUpdated || valuesMembersUpdated || groupsMembersUpdated || original.ModPolicy != updated.ModPolicy) {

// If there were no modified entries in any of the policies/values/groups maps
if len(readSetPolicies) == 0 &&
len(writeSetPolicies) == 0 &&
len(readSetValues) == 0 &&
len(writeSetValues) == 0 &&
len(readSetGroups) == 0 &&
len(writeSetGroups) == 0 {
if len(readSetPolicies)+len(writeSetPolicies)+len(readSetValues)+len(writeSetValues)+len(readSetGroups)+len(writeSetGroups) == 0 {
return &common.ConfigGroup{
Version: original.Version,
}, &common.ConfigGroup{
Expand All @@ -189,20 +184,9 @@ func computeGroupUpdate(original, updated *common.ConfigGroup) (readSet, writeSe
}, true
}

for k, samePolicy := range sameSetPolicies {
readSetPolicies[k] = samePolicy
writeSetPolicies[k] = samePolicy
}

for k, sameValue := range sameSetValues {
readSetValues[k] = sameValue
writeSetValues[k] = sameValue
}

for k, sameGroup := range sameSetGroups {
readSetGroups[k] = sameGroup
writeSetGroups[k] = sameGroup
}
copyMap(sameSetPolicies, readSetPolicies, writeSetPolicies)
copyMap(sameSetValues, readSetValues, writeSetValues)
copyMap(sameSetGroups, readSetGroups, writeSetGroups)

return &common.ConfigGroup{
Version: original.Version,
Expand All @@ -218,6 +202,14 @@ func computeGroupUpdate(original, updated *common.ConfigGroup) (readSet, writeSe
}, true
}

func copyMap[K comparable, V any](source map[K]V, targets ...map[K]V) {
for key, value := range source {
for _, target := range targets {
target[key] = value
}
}
}

func Compute(original, updated *common.Config) (*common.ConfigUpdate, error) {
if original.ChannelGroup == nil {
return nil, fmt.Errorf("no channel group included for original config")
Expand Down
2 changes: 2 additions & 0 deletions internal/msp/msp.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ func ProviderTypeToString(id ProviderType) string {

return ""
}

//nolint:gocognit,gocyclo
func getMspConfig(dir string, ID string, sigid *msp.SigningIdentityInfo) (*msp.MSPConfig, error) {
cacertDir := filepath.Join(dir, cacerts)
admincertDir := filepath.Join(dir, admincerts)
Expand Down
6 changes: 3 additions & 3 deletions internal/policies/policies.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func EncodeBFTBlockVerificationPolicy(consenterProtos []*cb.Consenter, ordererGr
for i, consenter := range consenterProtos {
pols = append(pols, &cb.SignaturePolicy{
Type: &cb.SignaturePolicy_SignedBy{
SignedBy: int32(i),
SignedBy: int32(i), //#nosec:G115
},
})
identities = append(identities, &msp.MSPPrincipal{
Expand All @@ -143,6 +143,6 @@ func EncodeBFTBlockVerificationPolicy(consenterProtos []*cb.Consenter, ordererGr
}
}

func ComputeBFTQuorum(totalNodes, faultyNodes int) int {
return int(math.Ceil(float64(totalNodes+faultyNodes+1) / 2))
func ComputeBFTQuorum(totalNodes, faultyNodes int) int32 {
return int32(math.Ceil(float64(totalNodes+faultyNodes+1) / 2))
}
14 changes: 8 additions & 6 deletions internal/policydsl/policydsl.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func or(args ...interface{}) (interface{}, error) {
return outof(args...)
}

//nolint:gocognit,gocyclo
func FromString(policy string) (*cb.SignaturePolicyEnvelope, error) {
// first we translate the and/or business into outof gates
intermediate, err := govaluate.NewEvaluableExpressionWithFunctions(
Expand Down Expand Up @@ -217,14 +218,15 @@ func firstPass(args ...interface{}) (interface{}, error) {
}

type context struct {
IDNum int
IDNum int32
principals []*mb.MSPPrincipal
}

func newContext() *context {
return &context{IDNum: 0, principals: make([]*mb.MSPPrincipal, 0)}
}

//nolint:gocognit,gocyclo
func secondPass(args ...interface{}) (interface{}, error) {
/* general sanity check, we expect at least 3 args */
if len(args) < 3 {
Expand All @@ -242,10 +244,10 @@ func secondPass(args ...interface{}) (interface{}, error) {

/* get the second argument, we expect an integer telling us
how many of the remaining we expect to have*/
var t int
var t int32
switch arg := args[1].(type) {
case float64:
t = int(arg)
t = int32(arg)
default:
return nil, fmt.Errorf("unrecognized type, expected a number, got %s", reflect.TypeOf(args[1]))
}
Expand All @@ -254,7 +256,7 @@ func secondPass(args ...interface{}) (interface{}, error) {
n := len(args) - 2

/* sanity check - t should be positive, permit equal to n+1, but disallow over n+1 */
if t < 0 || t > n+1 {
if t < 0 || int(t) > n+1 {
return nil, fmt.Errorf("invalid t-out-of-n predicate, t %d, n %d", t, n)
}

Expand Down Expand Up @@ -305,7 +307,7 @@ func secondPass(args ...interface{}) (interface{}, error) {

/* create a SignaturePolicy that requires a signature from
the principal we've just built*/
dapolicy := SignedBy(int32(ctx.IDNum))
dapolicy := SignedBy(ctx.IDNum)
policies = append(policies, dapolicy)

/* increment the identity counter. Note that this is
Expand All @@ -324,7 +326,7 @@ func secondPass(args ...interface{}) (interface{}, error) {
}
}

return NOutOf(int32(t), policies), nil
return NOutOf(t, policies), nil
}

// SignedBy creates a SignaturePolicy requiring a given signer's signature
Expand Down
Loading

0 comments on commit b61ba94

Please sign in to comment.