Skip to content

Commit cbf51b2

Browse files
committed
Satisfy linter
This mostly relates to integer conversions. In the most cases, the conversions are safe and thus disabled. Signed-off-by: Matej Pavlovic <[email protected]>
1 parent ea51d81 commit cbf51b2

File tree

17 files changed

+106
-52
lines changed

17 files changed

+106
-52
lines changed

cmd/mircat/debug.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ func debug(args *arguments) error {
111111
for _, event := range entry.Events {
112112

113113
// Set the index of the event in the event log.
114-
metadata.index = uint64(index)
114+
metadata.index = uint64(index) //nolint:gosec
115115

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

207204
node, err := mir.NewNode(id, mir.DefaultNodeConfig().WithLogger(logger), nodeModules, nil)
208205
if err != nil {

cmd/mircat/display.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func displayEvents(args *arguments) error { //nolint:gocognit
6969
}
7070
// getting events from entry
7171
for _, event := range entry.Events {
72-
metadata.index = uint64(index)
72+
metadata.index = uint64(index) //nolint:gosec
7373

7474
_, validEvent := args.selectedEventNames[eventName(event)]
7575
_, validDest := args.selectedEventDests[event.DestModule]

node_test.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package mir
33
import (
44
"context"
55
"fmt"
6+
"math"
67
"sync"
78
"sync/atomic"
89
"testing"
@@ -140,7 +141,7 @@ func TestNode_Backpressure(t *testing.T) {
140141
nodeConfig.Stats.Period = 100 * time.Millisecond
141142

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

145146
// Set the event consumption rate to 1/2 of the input rate (i.e., draining the buffer in 2 seconds)
146147
// and create the consumer module.
@@ -181,8 +182,8 @@ func TestNode_Backpressure(t *testing.T) {
181182
fmt.Printf("Total submitted events: %d\n", atomic.LoadUint64(&blabberModule.totalSubmitted))
182183
totalSubmitted := atomic.LoadUint64(&blabberModule.totalSubmitted)
183184
expectSubmitted := atomic.LoadUint64(&consumerModule.numProcessed) +
184-
uint64(nodeConfig.PauseInputThreshold) + // Events left in the buffer
185-
uint64(nodeConfig.MaxEventBatchSize) + // Events in the consumer's processing queue
185+
uint64(nodeConfig.PauseInputThreshold) + //nolint:gosec // Events left in the buffer
186+
uint64(nodeConfig.MaxEventBatchSize) + //nolint:gosec // Events in the consumer's processing queue
186187
2*blabberModule.batchSize // one batch of overshooting, one batch waiting in the babbler's output channel.
187188
assert.LessOrEqual(t, totalSubmitted, expectSubmitted, "too many events submitted (node event buffer overflow)")
188189
}
@@ -223,9 +224,12 @@ func (b *blabber) Go() {
223224
return
224225
default:
225226
}
227+
if b.batchSize > math.MaxInt {
228+
panic("batch size too big for int")
229+
}
226230
evts := stdtypes.ListOf(sliceutil.Repeat(
227231
stdtypes.Event(stdevents.NewTestUint64("consumer", 0)),
228-
int(b.batchSize),
232+
int(b.batchSize), //nolint:gosec
229233
)...)
230234
select {
231235
case <-b.stop:

pkg/availability/multisigcollector/multisigcollector.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package multisigcollector
22

33
import (
4+
"fmt"
45
"math"
56

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

73+
// Check for integer overflow
74+
if mscParams.MaxRequests > math.MaxInt {
75+
return nil, fmt.Errorf("max requests too high for int type: %d", mscParams.MaxRequests)
76+
}
77+
7278
// Fill in instance-specific parameters.
7379
moduleParams := paramsTemplate
7480
moduleParams.InstanceUID = []byte(mscID)
7581
moduleParams.EpochNr = mscParams.Epoch
7682
moduleParams.Membership = mscParams.Membership
77-
moduleParams.MaxRequests = int(mscParams.MaxRequests)
83+
moduleParams.MaxRequests = int(mscParams.MaxRequests) //nolint:gosec
7884
// TODO: Use InstanceUIDs properly.
7985
// (E.g., concatenate this with the instantiating protocol's InstanceUID when introduced.)
8086

pkg/checkpoint/chkpvalidator/conservativecv.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
package chkpvalidator
22

33
import (
4-
es "github.com/go-errors/errors"
4+
"math"
55

6-
t "github.com/filecoin-project/mir/stdtypes"
6+
es "github.com/go-errors/errors"
77

88
"github.com/filecoin-project/mir/pkg/checkpoint"
99
"github.com/filecoin-project/mir/pkg/crypto"
1010
checkpointpbtypes "github.com/filecoin-project/mir/pkg/pb/checkpointpb/types"
1111
trantorpbtypes "github.com/filecoin-project/mir/pkg/pb/trantorpb/types"
1212
tt "github.com/filecoin-project/mir/pkg/trantor/types"
13+
t "github.com/filecoin-project/mir/stdtypes"
1314
)
1415

1516
type ConservativeCV struct {
@@ -55,14 +56,25 @@ func (ccv *ConservativeCV) Verify(
5556
return es.Errorf("nodeID not in membership")
5657
}
5758

59+
// Check if epoch is in integer bounds.
60+
if sc.Epoch() > math.MaxInt || epochNr > math.MaxInt {
61+
return es.Errorf("epoch number out of integer range")
62+
}
63+
5864
// Check how far the received stable checkpoint is ahead of the local node's state.
59-
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(epochNr)
65+
// Integer casting required here to prevent underflow.
66+
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(epochNr) //nolint:gosec
6067
if chkpMembershipOffset <= 0 {
6168
// Ignore stable checkpoints that are not far enough
6269
// ahead of the current state of the local node.
6370
return es.Errorf("checkpoint not far ahead enough")
6471
}
6572

73+
// Make sure ccv.configOffset is non-negative before conversion
74+
if ccv.configOffset < 0 {
75+
return es.Errorf("configOffset cannot be negative")
76+
}
77+
6678
if chkpMembershipOffset > ccv.configOffset {
6779
// cannot verify checkpoint signatures, too far ahead
6880
return es.Errorf("checkpoint too far ahead")

pkg/checkpoint/chkpvalidator/permissivecv.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
package chkpvalidator
22

33
import (
4-
es "github.com/go-errors/errors"
5-
6-
t "github.com/filecoin-project/mir/stdtypes"
4+
"math"
75

8-
"github.com/filecoin-project/mir/pkg/logging"
6+
es "github.com/go-errors/errors"
97

108
"github.com/filecoin-project/mir/pkg/checkpoint"
119
"github.com/filecoin-project/mir/pkg/crypto"
10+
"github.com/filecoin-project/mir/pkg/logging"
1211
checkpointpbtypes "github.com/filecoin-project/mir/pkg/pb/checkpointpb/types"
1312
trantorpbtypes "github.com/filecoin-project/mir/pkg/pb/trantorpb/types"
1413
tt "github.com/filecoin-project/mir/pkg/trantor/types"
14+
t "github.com/filecoin-project/mir/stdtypes"
1515
)
1616

1717
type PermissiveCV struct {
@@ -50,13 +50,19 @@ func (pcv *PermissiveCV) Verify(chkp *checkpointpbtypes.StableCheckpoint, epochN
5050
return es.Errorf("nodeID not in membership")
5151
}
5252

53+
// Check if epoch is in integer bounds.
54+
if sc.Epoch() > math.MaxInt || epochNr > math.MaxInt {
55+
return es.Errorf("epoch number out of integer range")
56+
}
57+
5358
// ATTENTION: We are using the membership contained in the checkpoint itself
5459
// as the one to verify its certificate against.
5560
// This is a vulnerability, since any the state of any node can be corrupted
5661
// simply by receiving a maliciously crafted checkpoint.
5762
// Thus, the permissive checker is a form of a stub and should not be used in production.
5863
chkpMembership := sc.PreviousMembership()
59-
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(epochNr)
64+
// Integer casting required here to prevent underflow.
65+
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(epochNr) //nolint:gosec
6066

6167
if chkpMembershipOffset > pcv.configOffset {
6268
// cannot verify checkpoint signatures, too far ahead

pkg/deploytest/deployment.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,8 @@ func (d *Deployment) Run(ctx context.Context) (nodeErrors []error, heapObjects i
179179
<-ctx.Done()
180180
runtime.GC()
181181
runtime.ReadMemStats(&m2)
182-
heapObjects = int64(m2.HeapObjects - m1.HeapObjects)
183-
heapAlloc = int64(m2.HeapAlloc - m1.HeapAlloc)
182+
heapObjects = int64(m2.HeapObjects - m1.HeapObjects) //nolint:gosec
183+
heapAlloc = int64(m2.HeapAlloc - m1.HeapAlloc) //nolint:gosec
184184
cancel()
185185
}()
186186

pkg/deploytest/testreplica.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ func (tr *TestReplica) submitFakeTransactions(ctx context.Context, node *mir.Nod
183183
destModule,
184184
[]*trantorpbtypes.Transaction{{
185185
ClientId: tt.NewClientIDFromInt(0),
186-
TxNo: tt.TxNo(i),
186+
TxNo: tt.TxNo(i), //nolint:gosec
187187
Data: []byte(fmt.Sprintf("Transaction %d", i)),
188188
}},
189189
).Pb())

pkg/dsl/test/dslmodule_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ func newContextTestingModule(mc *contextTestingModuleModuleConfig) dsl.Module {
278278

279279
// NB: avoid using primitive types as the context in the actual implementation, prefer named structs,
280280
// remember that the context type is used to match requests with responses.
281-
cryptopbdsl.VerifySigs(m, mc.Crypto, sliceutil.Repeat(msg, int(u)), signatures, nodeIDs, &u)
281+
cryptopbdsl.VerifySigs(m, mc.Crypto, sliceutil.Repeat(msg, int(u)), signatures, nodeIDs, &u) //nolint:gosec
282282
}
283283
return nil
284284
})

pkg/iss/iss.go

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ package iss
1414
import (
1515
"encoding/binary"
1616
"fmt"
17+
"math"
1718

1819
es "github.com/go-errors/errors"
1920
"google.golang.org/protobuf/proto"
@@ -342,7 +343,7 @@ func New(
342343

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

347348
// Serialize checkpoint, so it can be proposed as a value.
348349
stableCheckpoint := checkpointpbtypes.StableCheckpoint{
@@ -408,7 +409,7 @@ func New(
408409
// that are not yet part of the system for those checkpoints.
409410
var delayed []stdtypes.NodeID
410411
for n := range membership.Nodes {
411-
if epoch > iss.nodeEpochMap[n]+tt.EpochNr(iss.Params.RetainedEpochs) {
412+
if epoch > iss.nodeEpochMap[n]+tt.EpochNr(iss.Params.RetainedEpochs) { //nolint:gosec
412413
delayed = append(delayed, n)
413414
}
414415
}
@@ -438,7 +439,11 @@ func New(
438439

439440
sc := checkpoint.StableCheckpointFromPb(chkp.Pb())
440441
// Check how far the received stable checkpoint is ahead of the local node's state.
441-
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(iss.epoch.Nr())
442+
if sc.Epoch() > math.MaxInt || iss.epoch.Nr() > math.MaxInt {
443+
return es.Errorf("epoch number out of integer range")
444+
}
445+
// Integer casting required here to prevent underflow.
446+
chkpMembershipOffset := int(sc.Epoch()) - 1 - int(iss.epoch.Nr()) //nolint:gosec
442447
if chkpMembershipOffset <= 0 {
443448
// Ignore stable checkpoints that are not far enough
444449
// ahead of the current state of the local node.
@@ -465,7 +470,11 @@ func New(
465470
}
466471

467472
chkp := checkpoint.StableCheckpointFromPb(c.checkpoint.Pb())
468-
chkpMembershipOffset := int(chkp.Epoch()) - 1 - int(iss.epoch.Nr())
473+
if chkp.Epoch() > math.MaxInt || iss.epoch.Nr() > math.MaxInt {
474+
return es.Errorf("epoch number out of integer range")
475+
}
476+
// Integer casting required here to prevent underflow.
477+
chkpMembershipOffset := int(chkp.Epoch()) - 1 - int(iss.epoch.Nr()) //nolint:gosec
469478
if chkpMembershipOffset <= 0 {
470479
// Ignore stable checkpoints that have been lagged behind
471480
// during validation
@@ -564,7 +573,7 @@ func InitialStateSnapshot(
564573
return nil, err
565574
}
566575

567-
firstEpochLength := uint64(params.SegmentLength * len(params.InitialMembership.Nodes))
576+
firstEpochLength := uint64(params.SegmentLength * len(params.InitialMembership.Nodes)) //nolint:gosec
568577
return &trantorpbtypes.StateSnapshot{
569578
AppData: appState,
570579
EpochData: &trantorpbtypes.EpochData{
@@ -624,7 +633,7 @@ func (iss *ISS) initAvailability() {
624633
(*multisigcollector.InstanceParams)(&mscpbtypes.InstanceParams{
625634
Epoch: iss.epoch.Nr(),
626635
Membership: iss.memberships[0],
627-
MaxRequests: uint64(iss.Params.SegmentLength),
636+
MaxRequests: uint64(iss.Params.SegmentLength), //nolint:gosec
628637
}),
629638
stdtypes.RetentionIndex(iss.epoch.Nr()),
630639
)
@@ -640,12 +649,12 @@ func (iss *ISS) initOrderers() error {
640649

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

650659
// Instantiate a new PBFT orderer.
651660
stddsl.NewSubmodule(iss.m, iss.moduleConfig.Ordering,
@@ -792,7 +801,7 @@ func (iss *ISS) advanceEpoch() error {
792801
EpochConfig: &trantorpbtypes.EpochConfig{ // nolint:govet
793802
iss.epoch.Nr(),
794803
iss.epoch.FirstSN(),
795-
uint64(iss.epoch.Len()),
804+
uint64(iss.epoch.Len()), //nolint:gosec
796805
iss.memberships,
797806
},
798807
},
@@ -904,8 +913,9 @@ func (iss *ISS) deliverCommonCheckpoint(chkpData []byte) error {
904913
// The state to prune is determined according to the retention index
905914
// which is derived from the epoch number the new
906915
// stable checkpoint is associated with.
907-
pruneIndex := int(chkp.Epoch()) - iss.Params.RetainedEpochs
908-
if pruneIndex > 0 { // "> 0" and not ">= 0", since only entries strictly smaller than the index are pruned.
916+
// Integer casting required here to prevent underflow.
917+
pruneIndex := int(chkp.Epoch()) - iss.Params.RetainedEpochs //nolint:gosec
918+
if pruneIndex > 0 { // "> 0" and not ">= 0", since only entries strictly smaller than the index are pruned.
909919

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

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

0 commit comments

Comments
 (0)