Skip to content

Commit

Permalink
golangci-lint: update rules to match core (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmank88 authored May 15, 2024
1 parent a5a1065 commit 7eae9cf
Show file tree
Hide file tree
Showing 14 changed files with 169 additions and 130 deletions.
47 changes: 42 additions & 5 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ linters:
- misspell
- rowserrcheck
- errorlint
- unconvert
- sqlclosecheck
- noctx
- whitespace
- depguard
linters-settings:
exhaustive:
default-signifies-exhaustive: true
Expand All @@ -26,7 +31,7 @@ linters-settings:
# - G404
govet:
# report about shadowed variables
check-shadowing: false
check-shadowing: true
errorlint:
# Allow formatting of errors without %w
errorf: false
Expand All @@ -40,9 +45,10 @@ linters-settings:
- name: error-return
- name: error-strings
- name: error-naming
- name: exported
- name: if-return
- name: increment-decrement
# - name: var-naming
- name: var-naming
- name: var-declaration
- name: package-comments
- name: range
Expand All @@ -61,23 +67,54 @@ linters-settings:
- name: struct-tag
# - name: string-format
- name: string-of-int
# - name: range-val-address
- name: range-val-address
- name: range-val-in-closure
- name: modifies-value-receiver
- name: modifies-parameter
- name: identical-branches
- name: get-return
# - name: flag-parameter
# - name: early-return
- name: early-return
- name: defer
- name: constant-logical-expr
# - name: confusing-naming
# - name: confusing-results
- name: bool-literal-in-expr
- name: atomic
depguard:
rules:
main:
list-mode: lax
deny:
- pkg: "cosmossdk.io/errors"
desc: Use the standard library instead
- pkg: "github.com/ethereum/go-ethereum"
desc: This is a chain-agnostic repo
- pkg: "github.com/go-gorm/gorm"
desc: Use github.com/jmoiron/sqlx directly instead
- pkg: "github.com/gofrs/uuid"
desc: Use github.com/google/uuid instead
- pkg: "github.com/pkg/errors"
desc: Use the standard library instead, for example https://pkg.go.dev/errors#Join
- pkg: "github.com/satori/go.uuid"
desc: Use github.com/google/uuid instead
- pkg: "github.com/test-go/testify/assert"
desc: Use github.com/stretchr/testify/assert instead
- pkg: "github.com/test-go/testify/mock"
desc: Use github.com/stretchr/testify/mock instead
- pkg: "github.com/test-go/testify/require"
desc: Use github.com/stretchr/testify/require instead
- pkg: "go.uber.org/multierr"
desc: Use the standard library instead, for example https://pkg.go.dev/errors#Join
- pkg: "gopkg.in/guregu/null.v1"
desc: Use gopkg.in/guregu/null.v4 instead
- pkg: "gopkg.in/guregu/null.v2"
desc: Use gopkg.in/guregu/null.v4 instead
- pkg: "gopkg.in/guregu/null.v3"
desc: Use gopkg.in/guregu/null.v4 instead
issues:
exclude-rules:
- path: test
text: "^G404:"
linters:
- gosec
- gosec
58 changes: 29 additions & 29 deletions llo/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ import (

// Additional limits so we can more effectively bound the size of observations
const (
MAX_OBSERVATION_REMOVE_CHANNEL_IDS_LENGTH = 5
MAX_OBSERVATION_ADD_CHANNEL_DEFINITIONS_LENGTH = 5
MAX_OBSERVATION_STREAM_VALUES_LENGTH = 1_000
MaxObservationRemoveChannelIDsLength = 5
MaxObservationAddChannelDefinitionsLength = 5
MaxObservationStreamValuesLength = 1_000
)

const MAX_OUTCOME_CHANNEL_DEFINITIONS_LENGTH = 500
const MaxOutcomeChannelDefinitionsLength = 500

// Values for a set of streams, e.g. "eth-usd", "link-usd", and "eur-chf"
// TODO: generalize from *big.Int to anything
Expand Down Expand Up @@ -185,7 +185,7 @@ func (f *PluginFactory) NewReportingPlugin(cfg ocr3types.ReportingPluginConfig)
return nil, ocr3types.ReportingPluginInfo{}, fmt.Errorf("NewReportingPlugin failed to decode offchain config; got: 0x%x (len: %d); %w", cfg.OffchainConfig, len(cfg.OffchainConfig), err)
}

return &LLOPlugin{
return &Plugin{
offchainCfg.PredecessorConfigDigest,
cfg.ConfigDigest,
f.PredecessorRetirementReportCache,
Expand All @@ -207,15 +207,15 @@ func (f *PluginFactory) NewReportingPlugin(cfg ocr3types.ReportingPluginConfig)
}, nil
}

var _ ocr3types.ReportingPlugin[llotypes.ReportInfo] = &LLOPlugin{}
var _ ocr3types.ReportingPlugin[llotypes.ReportInfo] = &Plugin{}

type ReportCodec interface {
Encode(Report) ([]byte, error)
Decode([]byte) (Report, error)
// TODO: max length check? https://smartcontract-it.atlassian.net/browse/MERC-3524
}

type LLOPlugin struct {
type Plugin struct {
PredecessorConfigDigest *types.ConfigDigest
ConfigDigest types.ConfigDigest
PredecessorRetirementReportCache PredecessorRetirementReportCache
Expand All @@ -240,7 +240,7 @@ type LLOPlugin struct {
// *not* strictly) across the lifetime of a protocol instance and that
// outctx.previousOutcome contains the consensus outcome with sequence
// number (outctx.SeqNr-1).
func (p *LLOPlugin) Query(ctx context.Context, outctx ocr3types.OutcomeContext) (types.Query, error) {
func (p *Plugin) Query(ctx context.Context, outctx ocr3types.OutcomeContext) (types.Query, error) {
return nil, nil
}

Expand All @@ -256,7 +256,7 @@ type Observation struct {
RemoveChannelIDs map[llotypes.ChannelID]struct{}
AddChannelDefinitions llotypes.ChannelDefinitions
// Observed (numeric) stream values. Subject to
// MAX_OBSERVATION_STREAM_VALUES_LENGTH limit
// MaxObservationStreamValuesLength limit
StreamValues StreamValues
}

Expand All @@ -269,7 +269,7 @@ type Observation struct {
// number (outctx.SeqNr-1).
//
// Should return a serialized Observation struct.
func (p *LLOPlugin) Observation(ctx context.Context, outctx ocr3types.OutcomeContext, query types.Query) (types.Observation, error) {
func (p *Plugin) Observation(ctx context.Context, outctx ocr3types.OutcomeContext, query types.Query) (types.Observation, error) {
// send empty observation in initial round
// NOTE: First sequence number is always 1
if outctx.SeqNr < 1 {
Expand Down Expand Up @@ -313,21 +313,21 @@ func (p *LLOPlugin) Observation(ctx context.Context, outctx ocr3types.OutcomeCon
{
expectedChannelDefs := p.ChannelDefinitionCache.Definitions()

removeChannelDefinitions := subtractChannelDefinitions(previousOutcome.ChannelDefinitions, expectedChannelDefs, MAX_OBSERVATION_REMOVE_CHANNEL_IDS_LENGTH)
removeChannelDefinitions := subtractChannelDefinitions(previousOutcome.ChannelDefinitions, expectedChannelDefs, MaxObservationRemoveChannelIDsLength)
for channelID := range removeChannelDefinitions {
removeChannelIDs[channelID] = struct{}{}
}

for channelID := range previousOutcome.ValidAfterSeconds {
if len(removeChannelIDs) >= MAX_OBSERVATION_REMOVE_CHANNEL_IDS_LENGTH {
if len(removeChannelIDs) >= MaxObservationRemoveChannelIDsLength {
break
}
if _, ok := expectedChannelDefs[channelID]; !ok {
removeChannelIDs[channelID] = struct{}{}
}
}

addChannelDefinitions = subtractChannelDefinitions(expectedChannelDefs, previousOutcome.ChannelDefinitions, MAX_OBSERVATION_ADD_CHANNEL_DEFINITIONS_LENGTH)
addChannelDefinitions = subtractChannelDefinitions(expectedChannelDefs, previousOutcome.ChannelDefinitions, MaxObservationAddChannelDefinitionsLength)
}

var streamValues StreamValues
Expand Down Expand Up @@ -374,7 +374,7 @@ func (p *LLOPlugin) Observation(ctx context.Context, outctx ocr3types.OutcomeCon
// *not* strictly) across the lifetime of a protocol instance and that
// outctx.previousOutcome contains the consensus outcome with sequence
// number (outctx.SeqNr-1).
func (p *LLOPlugin) ValidateObservation(outctx ocr3types.OutcomeContext, query types.Query, ao types.AttributedObservation) error {
func (p *Plugin) ValidateObservation(outctx ocr3types.OutcomeContext, query types.Query, ao types.AttributedObservation) error {
if outctx.SeqNr <= 1 {
if len(ao.Observation) != 0 {
return fmt.Errorf("Observation is not empty")
Expand All @@ -394,16 +394,16 @@ func (p *LLOPlugin) ValidateObservation(outctx ocr3types.OutcomeContext, query t
return fmt.Errorf("AttestedPredecessorRetirement is not empty even though this instance has no predecessor")
}

if len(observation.AddChannelDefinitions) > MAX_OBSERVATION_ADD_CHANNEL_DEFINITIONS_LENGTH {
return fmt.Errorf("AddChannelDefinitions is too long: %v vs %v", len(observation.AddChannelDefinitions), MAX_OBSERVATION_ADD_CHANNEL_DEFINITIONS_LENGTH)
if len(observation.AddChannelDefinitions) > MaxObservationAddChannelDefinitionsLength {
return fmt.Errorf("AddChannelDefinitions is too long: %v vs %v", len(observation.AddChannelDefinitions), MaxObservationAddChannelDefinitionsLength)
}

if len(observation.RemoveChannelIDs) > MAX_OBSERVATION_REMOVE_CHANNEL_IDS_LENGTH {
return fmt.Errorf("RemoveChannelIDs is too long: %v vs %v", len(observation.RemoveChannelIDs), MAX_OBSERVATION_REMOVE_CHANNEL_IDS_LENGTH)
if len(observation.RemoveChannelIDs) > MaxObservationRemoveChannelIDsLength {
return fmt.Errorf("RemoveChannelIDs is too long: %v vs %v", len(observation.RemoveChannelIDs), MaxObservationRemoveChannelIDsLength)
}

if len(observation.StreamValues) > MAX_OBSERVATION_STREAM_VALUES_LENGTH {
return fmt.Errorf("StreamValues is too long: %v vs %v", len(observation.StreamValues), MAX_OBSERVATION_STREAM_VALUES_LENGTH)
if len(observation.StreamValues) > MaxObservationStreamValuesLength {
return fmt.Errorf("StreamValues is too long: %v vs %v", len(observation.StreamValues), MaxObservationStreamValuesLength)
}

for streamID, obsResult := range observation.StreamValues {
Expand Down Expand Up @@ -515,7 +515,7 @@ func (out *Outcome) ReportableChannels() []llotypes.ChannelID {
//
// libocr guarantees that this will always be called with at least 2f+1
// AttributedObservations
func (p *LLOPlugin) Outcome(outctx ocr3types.OutcomeContext, query types.Query, aos []types.AttributedObservation) (ocr3types.Outcome, error) {
func (p *Plugin) Outcome(outctx ocr3types.OutcomeContext, query types.Query, aos []types.AttributedObservation) (ocr3types.Outcome, error) {
if len(aos) < 2*p.F+1 {
return nil, fmt.Errorf("invariant violation: expected at least 2f+1 attributed observations, got %d (f: %d)", len(aos), p.F)
}
Expand Down Expand Up @@ -673,9 +673,9 @@ func (p *LLOPlugin) Outcome(outctx ocr3types.OutcomeContext, query types.Query,
)
continue
}
if len(outcome.ChannelDefinitions) > MAX_OUTCOME_CHANNEL_DEFINITIONS_LENGTH {
if len(outcome.ChannelDefinitions) > MaxOutcomeChannelDefinitionsLength {
p.Logger.Warn("Cannot add channel, outcome already contains maximum number of channels",
"maxOutcomeChannelDefinitionsLength", MAX_OUTCOME_CHANNEL_DEFINITIONS_LENGTH,
"maxOutcomeChannelDefinitionsLength", MaxOutcomeChannelDefinitionsLength,
"addChannelDefinition", defWithID,
)
continue
Expand Down Expand Up @@ -776,7 +776,7 @@ type Report struct {
Specimen bool
}

func (p *LLOPlugin) encodeReport(r Report, format llotypes.ReportFormat) (types.Report, error) {
func (p *Plugin) encodeReport(r Report, format llotypes.ReportFormat) (types.Report, error) {
codec, exists := p.Codecs[format]
if !exists {
return nil, fmt.Errorf("codec missing for ReportFormat=%d", format)
Expand All @@ -797,7 +797,7 @@ func (p *LLOPlugin) encodeReport(r Report, format llotypes.ReportFormat) (types.
// *not* strictly) across the lifetime of a protocol instance and that
// outctx.previousOutcome contains the consensus outcome with sequence
// number (outctx.SeqNr-1).
func (p *LLOPlugin) Reports(seqNr uint64, rawOutcome ocr3types.Outcome) ([]ocr3types.ReportWithInfo[llotypes.ReportInfo], error) {
func (p *Plugin) Reports(seqNr uint64, rawOutcome ocr3types.Outcome) ([]ocr3types.ReportWithInfo[llotypes.ReportInfo], error) {
if seqNr <= 1 {
// no reports for initial round
return nil, nil
Expand Down Expand Up @@ -870,12 +870,12 @@ func (p *LLOPlugin) Reports(seqNr uint64, rawOutcome ocr3types.Outcome) ([]ocr3t
return rwis, nil
}

func (p *LLOPlugin) ShouldAcceptAttestedReport(context.Context, uint64, ocr3types.ReportWithInfo[llotypes.ReportInfo]) (bool, error) {
func (p *Plugin) ShouldAcceptAttestedReport(context.Context, uint64, ocr3types.ReportWithInfo[llotypes.ReportInfo]) (bool, error) {
// Transmit it all to the Mercury server
return true, nil
}

func (p *LLOPlugin) ShouldTransmitAcceptedReport(context.Context, uint64, ocr3types.ReportWithInfo[llotypes.ReportInfo]) (bool, error) {
func (p *Plugin) ShouldTransmitAcceptedReport(context.Context, uint64, ocr3types.ReportWithInfo[llotypes.ReportInfo]) (bool, error) {
// Transmit it all to the Mercury server
return true, nil
}
Expand All @@ -888,11 +888,11 @@ func (p *LLOPlugin) ShouldTransmitAcceptedReport(context.Context, uint64, ocr3ty
// This is an advanced feature. The "default" approach (what OCR1 & OCR2
// did) is to have an empty ValidateObservation function and return
// QuorumTwoFPlusOne from this function.
func (p *LLOPlugin) ObservationQuorum(outctx ocr3types.OutcomeContext, query types.Query) (ocr3types.Quorum, error) {
func (p *Plugin) ObservationQuorum(outctx ocr3types.OutcomeContext, query types.Query) (ocr3types.Quorum, error) {
return ocr3types.QuorumTwoFPlusOne, nil
}

func (p *LLOPlugin) Close() error {
func (p *Plugin) Close() error {
return nil
}

Expand Down
8 changes: 4 additions & 4 deletions mercury/fees.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import (

// PriceScalingFactor indicates the multiplier applied to token prices that we expect from data source
// e.g. for a 1e8 multiplier, a LINK/USD value of 7.42 will be derived from a data source value of 742000000
var PRICE_SCALING_FACTOR = decimal.NewFromInt(1e18) //nolint:revive
var PriceScalingFactor = decimal.NewFromInt(1e18) //nolint:revive

// FeeScalingFactor indicates the multiplier applied to fees.
// e.g. for a 1e18 multiplier, a LINK fee of 7.42 will be represented as 7.42e18
// This is what will be baked into the report for use on-chain.
var FEE_SCALING_FACTOR = decimal.NewFromInt(1e18)
var FeeScalingFactor = decimal.NewFromInt(1e18)

// CalculateFee outputs a fee in wei according to the formula: baseUSDFee * scaleFactor / tokenPriceInUSD
func CalculateFee(tokenPriceInUSD *big.Int, baseUSDFee decimal.Decimal) *big.Int {
Expand All @@ -23,15 +23,15 @@ func CalculateFee(tokenPriceInUSD *big.Int, baseUSDFee decimal.Decimal) *big.Int
}

// scale baseFee in USD
baseFeeScaled := baseUSDFee.Mul(PRICE_SCALING_FACTOR)
baseFeeScaled := baseUSDFee.Mul(PriceScalingFactor)

tokenPrice := decimal.NewFromBigInt(tokenPriceInUSD, 0)

// fee denominated in token
fee := baseFeeScaled.Div(tokenPrice)

// scale fee to the expected format
fee = fee.Mul(FEE_SCALING_FACTOR)
fee = fee.Mul(FeeScalingFactor)

// convert to big.Int
return fee.BigInt()
Expand Down
9 changes: 4 additions & 5 deletions mercury/onchain_config.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package mercury

import (
"fmt"
"math/big"

pkgerrors "github.com/pkg/errors"

"github.com/smartcontractkit/libocr/bigbigendian"

"github.com/smartcontractkit/chainlink-common/pkg/types/mercury"
Expand All @@ -29,15 +28,15 @@ type StandardOnchainConfigCodec struct{}

func (StandardOnchainConfigCodec) Decode(b []byte) (mercury.OnchainConfig, error) {
if len(b) != onchainConfigEncodedLength {
return mercury.OnchainConfig{}, pkgerrors.Errorf("unexpected length of OnchainConfig, expected %v, got %v", onchainConfigEncodedLength, len(b))
return mercury.OnchainConfig{}, fmt.Errorf("unexpected length of OnchainConfig, expected %v, got %v", onchainConfigEncodedLength, len(b))
}

v, err := bigbigendian.DeserializeSigned(32, b[:32])
if err != nil {
return mercury.OnchainConfig{}, err
}
if v.Cmp(onchainConfigVersionBig) != 0 {
return mercury.OnchainConfig{}, pkgerrors.Errorf("unexpected version of OnchainConfig, expected %v, got %v", onchainConfigVersion, v)
return mercury.OnchainConfig{}, fmt.Errorf("unexpected version of OnchainConfig, expected %v, got %v", onchainConfigVersion, v)
}

min, err := bigbigendian.DeserializeSigned(32, b[32:64])
Expand All @@ -50,7 +49,7 @@ func (StandardOnchainConfigCodec) Decode(b []byte) (mercury.OnchainConfig, error
}

if !(min.Cmp(max) <= 0) {
return mercury.OnchainConfig{}, pkgerrors.Errorf("OnchainConfig min (%v) should not be greater than max(%v)", min, max)
return mercury.OnchainConfig{}, fmt.Errorf("OnchainConfig min (%v) should not be greater than max(%v)", min, max)
}

return mercury.OnchainConfig{Min: min, Max: max}, nil
Expand Down
2 changes: 1 addition & 1 deletion mercury/onchain_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func FuzzDecodeOnchainConfig(f *testing.F) {
}

f.Add([]byte{})
f.Add([]byte(valid))
f.Add(valid)
f.Fuzz(func(t *testing.T, encoded []byte) {
decoded, err := StandardOnchainConfigCodec{}.Decode(encoded)
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion mercury/v1/aggregate_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ func GetConsensusLatestBlock(paos []PAO, f int) (hash []byte, num int64, ts uint
})

return usableBlocks[0].HashBytes(), usableBlocks[0].Num, usableBlocks[0].Ts, nil

}
// this grouping does not have any identical blocks with at least f+1 in agreement, try next block number down
}
Expand Down
Loading

0 comments on commit 7eae9cf

Please sign in to comment.