Skip to content

Commit

Permalink
Satisfy linter
Browse files Browse the repository at this point in the history
This mostly relates to integer conversions.
In the most cases, the conversions are safe and thus disabled.

Signed-off-by: Matej Pavlovic <matopavlovic@gmail.com>
  • Loading branch information
matejpavlovic committed Nov 27, 2024
1 parent ea51d81 commit b66ac95
Show file tree
Hide file tree
Showing 17 changed files with 79 additions and 48 deletions.
5 changes: 1 addition & 4 deletions cmd/mircat/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func debug(args *arguments) error {
for _, event := range entry.Events {

// Set the index of the event in the event log.
metadata.index = uint64(index)
metadata.index = uint64(index) //nolint:gosec

// If the event was selected by the user for inspection, pause before submitting it to the node.
// The processing continues after the user's interactive confirmation.
Expand Down Expand Up @@ -200,9 +200,6 @@ func debuggerNode(id stdtypes.NodeID, membership *trantorpbtypes.Membership) (*m
"iss": protocol,
"timer": timer.New(),
}
if err != nil {
panic(fmt.Errorf("error initializing the Mir modules: %w", err))
}

node, err := mir.NewNode(id, mir.DefaultNodeConfig().WithLogger(logger), nodeModules, nil)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/mircat/display.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func displayEvents(args *arguments) error { //nolint:gocognit
}
// getting events from entry
for _, event := range entry.Events {
metadata.index = uint64(index)
metadata.index = uint64(index) //nolint:gosec

_, validEvent := args.selectedEventNames[eventName(event)]
_, validDest := args.selectedEventDests[event.DestModule]
Expand Down
12 changes: 8 additions & 4 deletions node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mir
import (
"context"
"fmt"
"math"
"sync"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -140,7 +141,7 @@ func TestNode_Backpressure(t *testing.T) {
nodeConfig.Stats.Period = 100 * time.Millisecond

// Set an input event rate that would fill the node's event buffers in one second in 10 batches.
blabberModule := newBlabber(uint64(nodeConfig.PauseInputThreshold/10), 100*time.Millisecond)
blabberModule := newBlabber(uint64(nodeConfig.PauseInputThreshold/10), 100*time.Millisecond) //nolint:gosec

// Set the event consumption rate to 1/2 of the input rate (i.e., draining the buffer in 2 seconds)
// and create the consumer module.
Expand Down Expand Up @@ -181,8 +182,8 @@ func TestNode_Backpressure(t *testing.T) {
fmt.Printf("Total submitted events: %d\n", atomic.LoadUint64(&blabberModule.totalSubmitted))
totalSubmitted := atomic.LoadUint64(&blabberModule.totalSubmitted)
expectSubmitted := atomic.LoadUint64(&consumerModule.numProcessed) +
uint64(nodeConfig.PauseInputThreshold) + // Events left in the buffer
uint64(nodeConfig.MaxEventBatchSize) + // Events in the consumer's processing queue
uint64(nodeConfig.PauseInputThreshold) + //nolint:gosec // Events left in the buffer
uint64(nodeConfig.MaxEventBatchSize) + //nolint:gosec // Events in the consumer's processing queue
2*blabberModule.batchSize // one batch of overshooting, one batch waiting in the babbler's output channel.
assert.LessOrEqual(t, totalSubmitted, expectSubmitted, "too many events submitted (node event buffer overflow)")
}
Expand Down Expand Up @@ -223,9 +224,12 @@ func (b *blabber) Go() {
return
default:
}
if b.batchSize > math.MaxInt {
panic("batch size too big for int")
}
evts := stdtypes.ListOf(sliceutil.Repeat(
stdtypes.Event(stdevents.NewTestUint64("consumer", 0)),
int(b.batchSize),
int(b.batchSize), //nolint:gosec
)...)
select {
case <-b.stop:
Expand Down
8 changes: 7 additions & 1 deletion pkg/availability/multisigcollector/multisigcollector.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package multisigcollector

import (
"fmt"
"math"

"google.golang.org/protobuf/proto"
Expand Down Expand Up @@ -69,12 +70,17 @@ func NewReconfigurableModule(mc ModuleConfig, paramsTemplate ModuleParams, logge
submc := mc
submc.Self = mscID

// Check for integer overflow
if mscParams.MaxRequests > math.MaxInt {
return nil, fmt.Errorf("max requests too high for int type: %d", mscParams.MaxRequests)
}

// Fill in instance-specific parameters.
moduleParams := paramsTemplate
moduleParams.InstanceUID = []byte(mscID)
moduleParams.EpochNr = mscParams.Epoch
moduleParams.Membership = mscParams.Membership
moduleParams.MaxRequests = int(mscParams.MaxRequests)
moduleParams.MaxRequests = int(mscParams.MaxRequests) //nolint:gosec
// TODO: Use InstanceUIDs properly.
// (E.g., concatenate this with the instantiating protocol's InstanceUID when introduced.)

Expand Down
9 changes: 7 additions & 2 deletions pkg/checkpoint/chkpvalidator/conservativecv.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,19 @@ func (ccv *ConservativeCV) Verify(
}

// Check how far the received stable checkpoint is ahead of the local node's state.
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(epochNr)
chkpMembershipOffset := sc.Epoch() - tt.EpochNr(1) - epochNr
if chkpMembershipOffset <= 0 {
// Ignore stable checkpoints that are not far enough
// ahead of the current state of the local node.
return es.Errorf("checkpoint not far ahead enough")
}

if chkpMembershipOffset > ccv.configOffset {
// Make sure ccv.configOffset is non-negative before conversion
if ccv.configOffset < 0 {
return es.Errorf("configOffset cannot be negative")
}

if chkpMembershipOffset > tt.EpochNr(ccv.configOffset) { //nolint:gosec
// cannot verify checkpoint signatures, too far ahead
return es.Errorf("checkpoint too far ahead")
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/checkpoint/chkpvalidator/permissivecv.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ func (pcv *PermissiveCV) Verify(chkp *checkpointpbtypes.StableCheckpoint, epochN
// simply by receiving a maliciously crafted checkpoint.
// Thus, the permissive checker is a form of a stub and should not be used in production.
chkpMembership := sc.PreviousMembership()
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(epochNr)
chkpMembershipOffset := sc.Epoch() - tt.EpochNr(1) - epochNr

if chkpMembershipOffset > pcv.configOffset {
if chkpMembershipOffset > tt.EpochNr(pcv.configOffset) { //nolint:gosec
// cannot verify checkpoint signatures, too far ahead
pcv.logger.Log(logging.LevelWarn, "-----------------------------------------------------\n",
"ATTENTION: cannot verify membership of checkpoint, too far ahead, proceed with caution\n",
Expand Down
4 changes: 2 additions & 2 deletions pkg/deploytest/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ func (d *Deployment) Run(ctx context.Context) (nodeErrors []error, heapObjects i
<-ctx.Done()
runtime.GC()
runtime.ReadMemStats(&m2)
heapObjects = int64(m2.HeapObjects - m1.HeapObjects)
heapAlloc = int64(m2.HeapAlloc - m1.HeapAlloc)
heapObjects = int64(m2.HeapObjects - m1.HeapObjects) //nolint:gosec
heapAlloc = int64(m2.HeapAlloc - m1.HeapAlloc) //nolint:gosec
cancel()
}()

Expand Down
2 changes: 1 addition & 1 deletion pkg/deploytest/testreplica.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func (tr *TestReplica) submitFakeTransactions(ctx context.Context, node *mir.Nod
destModule,
[]*trantorpbtypes.Transaction{{
ClientId: tt.NewClientIDFromInt(0),
TxNo: tt.TxNo(i),
TxNo: tt.TxNo(i), //nolint:gosec
Data: []byte(fmt.Sprintf("Transaction %d", i)),
}},
).Pb())
Expand Down
2 changes: 1 addition & 1 deletion pkg/dsl/test/dslmodule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ func newContextTestingModule(mc *contextTestingModuleModuleConfig) dsl.Module {

// NB: avoid using primitive types as the context in the actual implementation, prefer named structs,
// remember that the context type is used to match requests with responses.
cryptopbdsl.VerifySigs(m, mc.Crypto, sliceutil.Repeat(msg, int(u)), signatures, nodeIDs, &u)
cryptopbdsl.VerifySigs(m, mc.Crypto, sliceutil.Repeat(msg, int(u)), signatures, nodeIDs, &u) //nolint:gosec
}
return nil
})
Expand Down
26 changes: 13 additions & 13 deletions pkg/iss/iss.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ func New(

// Choose a leader for the new orderer instance.
// TODO: Use the corresponding epoch's leader set to pick a leader, instead of just selecting one from all nodes.
leader := maputil.GetSortedKeys(membership.Nodes)[int(epoch)%len(membership.Nodes)]
leader := maputil.GetSortedKeys(membership.Nodes)[int(epoch)%len(membership.Nodes)] //nolint:gosec

// Serialize checkpoint, so it can be proposed as a value.
stableCheckpoint := checkpointpbtypes.StableCheckpoint{
Expand Down Expand Up @@ -408,7 +408,7 @@ func New(
// that are not yet part of the system for those checkpoints.
var delayed []stdtypes.NodeID
for n := range membership.Nodes {
if epoch > iss.nodeEpochMap[n]+tt.EpochNr(iss.Params.RetainedEpochs) {
if epoch > iss.nodeEpochMap[n]+tt.EpochNr(iss.Params.RetainedEpochs) { //nolint:gosec
delayed = append(delayed, n)
}
}
Expand Down Expand Up @@ -438,7 +438,7 @@ func New(

sc := checkpoint.StableCheckpointFromPb(chkp.Pb())
// Check how far the received stable checkpoint is ahead of the local node's state.
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(iss.epoch.Nr())
chkpMembershipOffset := sc.Epoch() - tt.EpochNr(1) - iss.epoch.Nr()
if chkpMembershipOffset <= 0 {
// Ignore stable checkpoints that are not far enough
// ahead of the current state of the local node.
Expand All @@ -465,7 +465,7 @@ func New(
}

chkp := checkpoint.StableCheckpointFromPb(c.checkpoint.Pb())
chkpMembershipOffset := int(chkp.Epoch()) - 1 - int(iss.epoch.Nr())
chkpMembershipOffset := chkp.Epoch() - tt.EpochNr(1) - iss.epoch.Nr()
if chkpMembershipOffset <= 0 {
// Ignore stable checkpoints that have been lagged behind
// during validation
Expand Down Expand Up @@ -564,7 +564,7 @@ func InitialStateSnapshot(
return nil, err
}

firstEpochLength := uint64(params.SegmentLength * len(params.InitialMembership.Nodes))
firstEpochLength := uint64(params.SegmentLength * len(params.InitialMembership.Nodes)) //nolint:gosec
return &trantorpbtypes.StateSnapshot{
AppData: appState,
EpochData: &trantorpbtypes.EpochData{
Expand Down Expand Up @@ -624,7 +624,7 @@ func (iss *ISS) initAvailability() {
(*multisigcollector.InstanceParams)(&mscpbtypes.InstanceParams{
Epoch: iss.epoch.Nr(),
Membership: iss.memberships[0],
MaxRequests: uint64(iss.Params.SegmentLength),
MaxRequests: uint64(iss.Params.SegmentLength), //nolint:gosec
}),
stdtypes.RetentionIndex(iss.epoch.Nr()),
)
Expand All @@ -640,12 +640,12 @@ func (iss *ISS) initOrderers() error {

// Create segment.
// The sequence proposals are all set to nil, so that the orderer proposes new availability certificates.
proposals := freeProposals(iss.nextDeliveredSN+tt.SeqNr(i), tt.SeqNr(len(leaders)), iss.Params.SegmentLength)
proposals := freeProposals(iss.nextDeliveredSN+tt.SeqNr(i), tt.SeqNr(len(leaders)), iss.Params.SegmentLength) //nolint:gosec
seg, err := common.NewSegment(leader, iss.epoch.Membership, proposals)
if err != nil {
return es.Errorf("error creating new segment: %w", err)
}
iss.newEpochSN += tt.SeqNr(seg.Len())
iss.newEpochSN += tt.SeqNr(seg.Len()) //nolint:gosec

// Instantiate a new PBFT orderer.
stddsl.NewSubmodule(iss.m, iss.moduleConfig.Ordering,
Expand Down Expand Up @@ -792,7 +792,7 @@ func (iss *ISS) advanceEpoch() error {
EpochConfig: &trantorpbtypes.EpochConfig{ // nolint:govet
iss.epoch.Nr(),
iss.epoch.FirstSN(),
uint64(iss.epoch.Len()),
uint64(iss.epoch.Len()), //nolint:gosec
iss.memberships,
},
},
Expand Down Expand Up @@ -904,8 +904,8 @@ func (iss *ISS) deliverCommonCheckpoint(chkpData []byte) error {
// The state to prune is determined according to the retention index
// which is derived from the epoch number the new
// stable checkpoint is associated with.
pruneIndex := int(chkp.Epoch()) - iss.Params.RetainedEpochs
if pruneIndex > 0 { // "> 0" and not ">= 0", since only entries strictly smaller than the index are pruned.
pruneIndex := chkp.Epoch() - tt.EpochNr(iss.Params.RetainedEpochs) //nolint:gosec
if pruneIndex > 0 { // "> 0" and not ">= 0", since only entries strictly smaller than the index are pruned.

// Prune timer, checkpointing, availability, orderers, and other modules.
stddsl.GarbageCollect(iss.m, iss.moduleConfig.Timer, stdtypes.RetentionIndex(pruneIndex))
Expand All @@ -917,7 +917,7 @@ func (iss *ISS) deliverCommonCheckpoint(chkpData []byte) error {

// Prune epoch state.
for epoch := range iss.epochs {
if epoch < tt.EpochNr(pruneIndex) {
if epoch < pruneIndex {
delete(iss.epochs, epoch)
}
}
Expand All @@ -931,7 +931,7 @@ func (iss *ISS) deliverCommonCheckpoint(chkpData []byte) error {
// Note that we are not using the current epoch number here, because it is not relevant for checkpoints.
// Using pruneIndex makes sure that the re-transmission is stopped
// on every stable checkpoint (when another one is started).
stdtypes.RetentionIndex(pruneIndex),
stdtypes.RetentionIndex(pruneIndex), //nolint:gosec
isspbevents.PushCheckpoint(iss.moduleConfig.Self).Pb(),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
package formbatchesint

import (
"fmt"
"math"

"github.com/filecoin-project/mir/pkg/clientprogress"
"github.com/filecoin-project/mir/pkg/dsl"
"github.com/filecoin-project/mir/pkg/logging"
Expand Down Expand Up @@ -156,7 +159,7 @@ func IncludeBatchCreation( // nolint:gocognit
cutBatch(origin)
} else {
reqID := storePendingRequest(origin)
stddsl.TimerDelay(m, mc.Timer, params.BatchTimeout, mppbevents.BatchTimeout(mc.Self, uint64(reqID)).Pb())
stddsl.TimerDelay(m, mc.Timer, params.BatchTimeout, mppbevents.BatchTimeout(mc.Self, uint64(reqID)).Pb()) //nolint:gosec
}
}

Expand Down Expand Up @@ -266,6 +269,9 @@ func IncludeBatchCreation( // nolint:gocognit

mppbdsl.UponBatchTimeout(m, func(batchReqID uint64) error {

if batchReqID > math.MaxInt {
return fmt.Errorf("batch request ID too big for an integer: %d", batchReqID)
}
reqID := int(batchReqID)

// Load the request origin.
Expand Down
7 changes: 6 additions & 1 deletion pkg/orderers/common/segment.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package common

import (
"math"

es "github.com/go-errors/errors"

"github.com/filecoin-project/mir/pkg/orderers/types"
Expand Down Expand Up @@ -44,7 +46,10 @@ func (seg *Segment) NodeIDs() []t.NodeID {
}

func (seg *Segment) PrimaryNode(view types.ViewNr) t.NodeID {
return seg.NodeIDs()[(seg.LeaderIndex()+int(view))%len(seg.NodeIDs())]
if view > math.MaxInt {
panic("view number out of integer range")
}
return seg.NodeIDs()[(seg.LeaderIndex()+int(view))%len(seg.NodeIDs())] //nolint:gosec
}

func (seg *Segment) LeaderIndex() int {
Expand Down
8 changes: 4 additions & 4 deletions pkg/orderers/internal/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ type PbftProposalState struct {
// ============================================================

// NumCommitted returns the number of slots that are already committed in the given view.
func (state *State) NumCommitted(view ot.ViewNr) int {
numCommitted := 0
func (state *State) NumCommitted(view ot.ViewNr) uint64 {
numCommitted := uint64(0)
for _, slot := range state.Slots[view] {
if slot.Committed {
numCommitted++
Expand Down Expand Up @@ -151,7 +151,7 @@ func (state *State) InitView(
pbftpbevents.ViewChangeSNTimeout(
moduleConfig.Self,
view,
uint64(state.NumCommitted(view))).Pb(),
state.NumCommitted(view)).Pb(), //nolint:gosec
)
stddsl.TimerDelay(
m,
Expand All @@ -168,7 +168,7 @@ func (state *State) InitView(
// AllCommitted returns true if all slots of this pbftInstance in the current view are in the committed state
// (i.e., have the committed flag set).
func (state *State) AllCommitted() bool {
return state.NumCommitted(state.View) == len(state.Slots[state.View])
return state.NumCommitted(state.View) == uint64(len(state.Slots[state.View]))
}

func (state *State) LookUpPreprepare(sn tt.SeqNr, digest []byte) *pbftpbtypes.Preprepare {
Expand Down
8 changes: 6 additions & 2 deletions pkg/orderers/internal/parts/goodcase/pbftgoodcase.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package goodcase

import (
"fmt"
"math"

es "github.com/go-errors/errors"
"google.golang.org/protobuf/proto"
Expand Down Expand Up @@ -119,6 +120,9 @@ func IncludeGoodCase(
})

pbftpbdsl.UponProposeTimeout(m, func(proposeTimeout uint64) error {
if proposeTimeout > math.MaxInt {
return es.Errorf("propose timeout too large (maximal allowed value: %d)", math.MaxInt)
}
return applyProposeTimeout(m, state, params, moduleConfig, int(proposeTimeout), logger)
})

Expand Down Expand Up @@ -255,7 +259,7 @@ func propose(
// Set up a new timer for the next proposal.
timeoutEvent := pbftpbevents.ProposeTimeout(
moduleConfig.Self,
uint64(state.Proposal.ProposalsMade+1))
uint64(state.Proposal.ProposalsMade+1)) //nolint:gosec

stddsl.TimerDelay(
m,
Expand Down Expand Up @@ -548,7 +552,7 @@ func advanceSlotState(
pbftpbevents.ViewChangeSNTimeout(
moduleConfig.Self,
state.View,
uint64(state.NumCommitted(state.View)),
state.NumCommitted(state.View),
).Pb(),
)
}
Expand Down
Loading

0 comments on commit b66ac95

Please sign in to comment.