Skip to content

Commit

Permalink
Merge pull request #2785 from OffchainLabs/lint-type-checks
Browse files Browse the repository at this point in the history
Make golangci-lint 1.62.0 happy
  • Loading branch information
PlasmaPower authored Nov 12, 2024
2 parents a3ad260 + 86b6cf0 commit 9ad3707
Show file tree
Hide file tree
Showing 14 changed files with 112 additions and 29 deletions.
6 changes: 5 additions & 1 deletion arbnode/delayed.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,11 @@ func (b *DelayedBridge) parseMessage(ctx context.Context, ethLog types.Log) (*bi
if err != nil {
return nil, nil, err
}
return parsedLog.MessageNum, args["messageData"].([]byte), nil
dataBytes, ok := args["messageData"].([]byte)
if !ok {
return nil, nil, errors.New("messageData not a byte array")
}
return parsedLog.MessageNum, dataBytes, nil
default:
return nil, nil, errors.New("unexpected log type")
}
Expand Down
6 changes: 5 additions & 1 deletion arbnode/sequencer_inbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,11 @@ func (m *SequencerInboxBatch) getSequencerData(ctx context.Context, client *ethc
if err != nil {
return nil, err
}
return args["data"].([]byte), nil
dataBytes, ok := args["data"].([]byte)
if !ok {
return nil, errors.New("args[\"data\"] not a byte array")
}
return dataBytes, nil
case batchDataSeparateEvent:
var numberAsHash common.Hash
binary.BigEndian.PutUint64(numberAsHash[(32-8):], m.SequenceNumber)
Expand Down
21 changes: 18 additions & 3 deletions broadcastclient/broadcastclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,11 @@ func TestInvalidSignature(t *testing.T) {
badPrivateKey, err := crypto.GenerateKey()
Require(t, err)
badPublicKey := badPrivateKey.Public()
badSequencerAddr := crypto.PubkeyToAddress(*badPublicKey.(*ecdsa.PublicKey))
badECDSA, ok := badPublicKey.(*ecdsa.PublicKey)
if !ok {
t.Fatal("badPublicKey is not an ecdsa.PublicKey")
}
badSequencerAddr := crypto.PubkeyToAddress(*badECDSA)
config := DefaultTestConfig

ts := NewDummyTransactionStreamer(chainId, &badSequencerAddr)
Expand All @@ -151,6 +155,7 @@ func TestInvalidSignature(t *testing.T) {
nil,
fatalErrChan,
&badSequencerAddr,
t,
)
Require(t, err)
broadcastClient.Start(ctx)
Expand Down Expand Up @@ -201,8 +206,9 @@ func (ts *dummyTransactionStreamer) AddBroadcastMessages(feedMessages []*m.Broad
return nil
}

func newTestBroadcastClient(config Config, listenerAddress net.Addr, chainId uint64, currentMessageCount arbutil.MessageIndex, txStreamer TransactionStreamerInterface, confirmedSequenceNumberListener chan arbutil.MessageIndex, feedErrChan chan error, validAddr *common.Address) (*BroadcastClient, error) {
port := listenerAddress.(*net.TCPAddr).Port
func newTestBroadcastClient(config Config, listenerAddress net.Addr, chainId uint64, currentMessageCount arbutil.MessageIndex, txStreamer TransactionStreamerInterface, confirmedSequenceNumberListener chan arbutil.MessageIndex, feedErrChan chan error, validAddr *common.Address, t *testing.T) (*BroadcastClient, error) {
t.Helper()
port := testhelpers.AddrTCPPort(listenerAddress, t)
var av contracts.AddressVerifierInterface
if validAddr != nil {
config.Verify.AcceptSequencer = true
Expand All @@ -225,6 +231,7 @@ func startMakeBroadcastClient(ctx context.Context, t *testing.T, clientConfig Co
nil,
feedErrChan,
sequencerAddr,
t,
)
Require(t, err)
broadcastClient.Start(ctx)
Expand Down Expand Up @@ -313,6 +320,7 @@ func TestServerClientDisconnect(t *testing.T) {
nil,
feedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
broadcastClient.Start(ctx)
Expand Down Expand Up @@ -384,6 +392,7 @@ func TestBroadcastClientConfirmedMessage(t *testing.T) {
confirmedSequenceNumberListener,
feedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
broadcastClient.Start(ctx)
Expand Down Expand Up @@ -456,6 +465,7 @@ func TestServerIncorrectChainId(t *testing.T) {
nil,
badFeedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
badBroadcastClient.Start(ctx)
Expand Down Expand Up @@ -515,6 +525,7 @@ func TestServerMissingChainId(t *testing.T) {
nil,
badFeedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
badBroadcastClient.Start(ctx)
Expand Down Expand Up @@ -572,6 +583,7 @@ func TestServerIncorrectFeedServerVersion(t *testing.T) {
nil,
badFeedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
badBroadcastClient.Start(ctx)
Expand Down Expand Up @@ -631,6 +643,7 @@ func TestServerMissingFeedServerVersion(t *testing.T) {
nil,
badFeedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
badBroadcastClient.Start(ctx)
Expand Down Expand Up @@ -682,6 +695,7 @@ func TestBroadcastClientReconnectsOnServerDisconnect(t *testing.T) {
nil,
feedErrChan,
&sequencerAddr,
t,
)
Require(t, err)
broadcastClient.Start(ctx)
Expand Down Expand Up @@ -794,6 +808,7 @@ func connectAndGetCachedMessages(ctx context.Context, addr net.Addr, chainId uin
nil,
feedErrChan,
sequencerAddr,
t,
)
Require(t, err)
broadcastClient.Start(ctx)
Expand Down
8 changes: 7 additions & 1 deletion broadcaster/backlog/backlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,13 @@ func newBacklogSegment() *backlogSegment {
func IsBacklogSegmentNil(segment BacklogSegment) bool {
if segment == nil {
return true
} else if segment.(*backlogSegment) == nil {
}
bs, ok := segment.(*backlogSegment)
if !ok {
log.Error("error in backlogSegment type assertion: clearing backlog")
return false
}
if bs == nil {
return true
}
return false
Expand Down
6 changes: 5 additions & 1 deletion cmd/genericconf/filehandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ func readLogMessagesFromJSONFile(t *testing.T, path string) ([]string, error) {
if !ok {
testhelpers.FailImpl(t, "Incorrect record, msg key is missing", "record", record)
}
messages = append(messages, msg.(string))
msgString, ok := msg.(string)
if !ok {
testhelpers.FailImpl(t, "Incorrect record, msg is not a string", "record", record)
}
messages = append(messages, msgString)
}
if errors.Is(err, io.EOF) {
return messages, nil
Expand Down
6 changes: 4 additions & 2 deletions das/reader_aggregator_strategies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ func TestDAS_SimpleExploreExploit(t *testing.T) {
}

for i := 0; i < len(was) && doMatch; i++ {
if expected[i].(*dummyReader).int != was[i].(*dummyReader).int {
Fail(t, fmt.Sprintf("expected %d, was %d", expected[i].(*dummyReader).int, was[i].(*dummyReader).int))
expR, expOK := expected[i].(*dummyReader)
wasR, wasOK := was[i].(*dummyReader)
if !expOK || !wasOK || expR.int != wasR.int {
Fail(t, fmt.Sprintf("expected %d, was %d", expected[i], was[i]))
}
}
}
Expand Down
12 changes: 10 additions & 2 deletions execution/nodeInterface/NodeInterface.go
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,11 @@ func (n NodeInterface) GasEstimateL1Component(
if err := args.CallDefaults(randomGas, evm.Context.BaseFee, evm.ChainConfig().ChainID); err != nil {
return 0, nil, nil, err
}
msg := args.ToMessage(evm.Context.BaseFee, randomGas, n.header, evm.StateDB.(*state.StateDB), core.MessageEthcallMode)
sdb, ok := evm.StateDB.(*state.StateDB)
if !ok {
return 0, nil, nil, errors.New("failed to cast to stateDB")
}
msg := args.ToMessage(evm.Context.BaseFee, randomGas, n.header, sdb, core.MessageEthcallMode)

pricing := c.State.L1PricingState()
l1BaseFeeEstimate, err := pricing.PricePerUnit()
Expand Down Expand Up @@ -581,7 +585,11 @@ func (n NodeInterface) GasEstimateComponents(
if err := args.CallDefaults(gasCap, evm.Context.BaseFee, evm.ChainConfig().ChainID); err != nil {
return 0, 0, nil, nil, err
}
msg := args.ToMessage(evm.Context.BaseFee, gasCap, n.header, evm.StateDB.(*state.StateDB), core.MessageGasEstimationMode)
sdb, ok := evm.StateDB.(*state.StateDB)
if !ok {
return 0, 0, nil, nil, errors.New("failed to cast to stateDB")
}
msg := args.ToMessage(evm.Context.BaseFee, gasCap, n.header, sdb, core.MessageGasEstimationMode)
brotliCompressionLevel, err := c.State.BrotliCompressionLevel()
if err != nil {
return 0, 0, nil, nil, fmt.Errorf("failed to get brotli compression level: %w", err)
Expand Down
6 changes: 5 additions & 1 deletion linters/koanf/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,11 @@ func checkFlagDefs(pass *analysis.Pass, f *ast.FuncDecl, cnt map[string]int) Res
if !ok {
continue
}
handleSelector(pass, callE.Args[1].(*ast.SelectorExpr), -1, cnt)
sel, ok := callE.Args[1].(*ast.SelectorExpr)
if !ok {
continue
}
handleSelector(pass, sel, -1, cnt)
if normSL := normalizeTag(sl); !strings.EqualFold(normSL, s) {
res.Errors = append(res.Errors, koanfError{
Pos: f.Pos(),
Expand Down
13 changes: 10 additions & 3 deletions system_tests/seq_coordinator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"math/big"
"net"
"testing"
"time"

Expand Down Expand Up @@ -153,7 +152,15 @@ func TestRedisSeqCoordinatorPriorities(t *testing.T) {

nodeForwardTarget := func(nodeNum int) int {
execNode := testNodes[nodeNum].ExecNode
fwTarget := execNode.TxPublisher.(*gethexec.TxPreChecker).TransactionPublisher.(*gethexec.Sequencer).ForwardTarget()
preChecker, ok := execNode.TxPublisher.(*gethexec.TxPreChecker)
if !ok {
return -1
}
sequencer, ok := preChecker.TransactionPublisher.(*gethexec.Sequencer)
if !ok {
return -1
}
fwTarget := sequencer.ForwardTarget()
if fwTarget == "" {
return -1
}
Expand Down Expand Up @@ -323,7 +330,7 @@ func testCoordinatorMessageSync(t *testing.T, successCase bool) {
// nodeB doesn't sequence transactions, but adds messages related to them to its output feed.
// nodeBOutputFeedReader reads those messages from this feed and processes them.
// nodeBOutputFeedReader doesn't read messages from L1 since none of the nodes posts to L1.
nodeBPort := testClientB.ConsensusNode.BroadcastServer.ListenerAddr().(*net.TCPAddr).Port
nodeBPort := testhelpers.AddrTCPPort(testClientB.ConsensusNode.BroadcastServer.ListenerAddr(), t)
nodeConfigNodeBOutputFeedReader := arbnode.ConfigDefaultL1NonSequencerTest()
nodeConfigNodeBOutputFeedReader.Feed.Input = *newBroadcastClientConfigTest(nodeBPort)
testClientNodeBOutputFeedReader, cleanupNodeBOutputFeedReader := builder.Build2ndNode(t, &SecondNodeParams{nodeConfig: nodeConfigNodeBOutputFeedReader})
Expand Down
4 changes: 2 additions & 2 deletions system_tests/seq_reject_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"context"
"fmt"
"math/big"
"net"
"strings"
"sync"
"sync/atomic"
Expand All @@ -20,6 +19,7 @@ import (
"github.com/offchainlabs/nitro/solgen/go/mocksgen"
"github.com/offchainlabs/nitro/util/arbmath"
"github.com/offchainlabs/nitro/util/colors"
"github.com/offchainlabs/nitro/util/testhelpers"
)

func TestSequencerRejection(t *testing.T) {
Expand All @@ -35,7 +35,7 @@ func TestSequencerRejection(t *testing.T) {

builder := NewNodeBuilder(ctx).DefaultConfig(t, false)
builder.takeOwnership = false
port := builderSeq.L2.ConsensusNode.BroadcastServer.ListenerAddr().(*net.TCPAddr).Port
port := testhelpers.AddrTCPPort(builderSeq.L2.ConsensusNode.BroadcastServer.ListenerAddr(), t)
builder.nodeConfig.Feed.Input = *newBroadcastClientConfigTest(port)
cleanup := builder.Build(t)
defer cleanup()
Expand Down
13 changes: 6 additions & 7 deletions system_tests/seqfeed_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"context"
"fmt"
"math/big"
"net"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -61,7 +60,7 @@ func TestSequencerFeed(t *testing.T) {
defer cleanupSeq()
seqInfo, seqNode, seqClient := builderSeq.L2Info, builderSeq.L2.ConsensusNode, builderSeq.L2.Client

port := seqNode.BroadcastServer.ListenerAddr().(*net.TCPAddr).Port
port := testhelpers.AddrTCPPort(seqNode.BroadcastServer.ListenerAddr(), t)
builder := NewNodeBuilder(ctx).DefaultConfig(t, false)
builder.nodeConfig.Feed.Input = *newBroadcastClientConfigTest(port)
builder.takeOwnership = false
Expand Down Expand Up @@ -107,7 +106,7 @@ func TestRelayedSequencerFeed(t *testing.T) {
Require(t, err)

config := relay.ConfigDefault
port := seqNode.BroadcastServer.ListenerAddr().(*net.TCPAddr).Port
port := testhelpers.AddrTCPPort(seqNode.BroadcastServer.ListenerAddr(), t)
config.Node.Feed.Input = *newBroadcastClientConfigTest(port)
config.Node.Feed.Output = *newBroadcasterConfigTest()
config.Chain.ID = bigChainId.Uint64()
Expand All @@ -119,7 +118,7 @@ func TestRelayedSequencerFeed(t *testing.T) {
Require(t, err)
defer currentRelay.StopAndWait()

port = currentRelay.GetListenerAddr().(*net.TCPAddr).Port
port = testhelpers.AddrTCPPort(currentRelay.GetListenerAddr(), t)
builder := NewNodeBuilder(ctx).DefaultConfig(t, false)
builder.nodeConfig.Feed.Input = *newBroadcastClientConfigTest(port)
builder.takeOwnership = false
Expand Down Expand Up @@ -219,7 +218,7 @@ func testLyingSequencer(t *testing.T, dasModeStr string) {
defer cleanupC()
l2clientC, nodeC := testClientC.Client, testClientC.ConsensusNode

port := nodeC.BroadcastServer.ListenerAddr().(*net.TCPAddr).Port
port := testhelpers.AddrTCPPort(nodeC.BroadcastServer.ListenerAddr(), t)

// The client node, connects to lying sequencer's feed
nodeConfigB := arbnode.ConfigDefaultL1NonSequencerTest()
Expand Down Expand Up @@ -361,7 +360,7 @@ func testBlockHashComparison(t *testing.T, blockHash *common.Hash, mustMismatch
}
defer wsBroadcastServer.StopAndWait()

port := wsBroadcastServer.ListenerAddr().(*net.TCPAddr).Port
port := testhelpers.AddrTCPPort(wsBroadcastServer.ListenerAddr(), t)

builder := NewNodeBuilder(ctx).DefaultConfig(t, true)
builder.nodeConfig.Feed.Input = *newBroadcastClientConfigTest(port)
Expand Down Expand Up @@ -468,7 +467,7 @@ func TestPopulateFeedBacklog(t *testing.T) {

// Creates a sink node that will read from the output feed of the previous node.
nodeConfigSink := builder.nodeConfig
port := builder.L2.ConsensusNode.BroadcastServer.ListenerAddr().(*net.TCPAddr).Port
port := testhelpers.AddrTCPPort(builder.L2.ConsensusNode.BroadcastServer.ListenerAddr(), t)
nodeConfigSink.Feed.Input = *newBroadcastClientConfigTest(port)
testClientSink, cleanupSink := builder.Build2ndNode(t, &SecondNodeParams{nodeConfig: nodeConfigSink})
defer cleanupSink()
Expand Down
17 changes: 14 additions & 3 deletions util/containers/syncmap.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package containers

import "sync"
import (
"fmt"
"sync"
)

type SyncMap[K any, V any] struct {
internal sync.Map
Expand All @@ -12,7 +15,11 @@ func (m *SyncMap[K, V]) Load(key K) (V, bool) {
var empty V
return empty, false
}
return val.(V), true
vVal, ok := val.(V)
if !ok {
panic(fmt.Sprintf("type assertion failed on %s", val))
}
return vVal, true
}

func (m *SyncMap[K, V]) Store(key K, val V) {
Expand All @@ -27,7 +34,11 @@ func (m *SyncMap[K, V]) Delete(key K) {
func (m *SyncMap[K, V]) Keys() []K {
s := make([]K, 0)
m.internal.Range(func(k, v interface{}) bool {
s = append(s, k.(K))
kKey, ok := k.(K)
if !ok {
panic(fmt.Sprintf("type assertion failed on %s", k))
}
s = append(s, kKey)
return true
})
return s
Expand Down
11 changes: 11 additions & 0 deletions util/testhelpers/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package testhelpers

import (
"net"
"testing"
)

// FreeTCPPortListener returns a listener listening on an unused local port.
Expand All @@ -15,3 +16,13 @@ func FreeTCPPortListener() (net.Listener, error) {
}
return l, nil
}

// Func AddrTCPPort returns the port of a net.Addr.
func AddrTCPPort(n net.Addr, t *testing.T) int {
t.Helper()
tcpAddr, ok := n.(*net.TCPAddr)
if !ok {
t.Fatal("Could not get TCP address net.Addr")
}
return tcpAddr.Port
}
Loading

0 comments on commit 9ad3707

Please sign in to comment.