Skip to content

[chain] Apply exported lint rule #2018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 11 commits into from
43 changes: 42 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
@@ -166,6 +166,44 @@ linters:
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#useless-break
- name: useless-break
disabled: false
# https://github.com/mgechev/revive/blob/HEAD/RULES_DESCRIPTIONS.md#exported
- name: exported
disabled: false
arguments:
- "checkPublicInterface"
- "sayRepetitiveInsteadOfStutters"
exclude:
- "**/abi/**/*.go"
- "**/api/**/*.go"
- "**/auth/**/*.go"
- "**/chainindexer/**/*.go"
- "**/cli/**/*.go"
- "**/cmd/**/*.go"
- "**/codec/**/*.go"
- "**/consts/**/*.go"
- "**/context/**/*.go"
- "**/crypto/**/*.go"
- "**/event/**/*.go"
- "**/examples/**/*.go"
- "**/extension/**/*.go"
- "**/fees/**/*.go"
- "**/genesis/**/*.go"
- "**/internal/**/*.go"
- "**/keys/**/*.go"
- "**/load/**/*.go"
- "**/proto/**/*.go"
- "**/pubsub/**/*.go"
- "**/requester/**/*.go"
- "**/snow/**/*.go"
- "**/state/**/*.go"
- "**/statesync/**/*.go"
- "**/storage/**/*.go"
- "**/tests/**/*.go"
- "**/throughput/**/*.go"
- "**/utils/**/*.go"
- "**/vm/**/*.go"
- "**/x/**/*.go"
- "TEST"
spancheck:
checks:
- end
@@ -193,10 +231,13 @@ linters:
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
- path-except: ^chain/
text: "(ST1000|ST1020|ST1021|ST1022)"

issues:
# Maximum issues count per one linter.
# Set to 0 to disable.
4 changes: 2 additions & 2 deletions chain/accepter.go
Original file line number Diff line number Diff line change
@@ -9,16 +9,16 @@
"github.com/ava-labs/avalanchego/trace"
)

type Accepter struct {

Check failure on line 12 in chain/accepter.go

GitHub Actions / hypersdk-lint

exported: exported type Accepter should have comment or be unexported (revive)
tracer trace.Tracer
validityWindow ValidityWindow
metrics *ChainMetrics
metrics *Metrics
}

func NewAccepter(

Check failure on line 18 in chain/accepter.go

GitHub Actions / hypersdk-lint

exported: exported function NewAccepter should have comment or be unexported (revive)
tracer trace.Tracer,
validityWindow ValidityWindow,
metrics *ChainMetrics,
metrics *Metrics,
) *Accepter {
return &Accepter{
tracer: tracer,
@@ -27,7 +27,7 @@
}
}

func (a *Accepter) AcceptBlock(ctx context.Context, blk *OutputBlock) error {

Check failure on line 30 in chain/accepter.go

GitHub Actions / hypersdk-lint

exported: exported method Accepter.AcceptBlock should have comment or be unexported (revive)
_, span := a.tracer.Start(ctx, "Chain.AcceptBlock")
defer span.End()

2 changes: 2 additions & 0 deletions chain/auth_batch.go
Original file line number Diff line number Diff line change
@@ -13,11 +13,13 @@

const authWorkerBacklog = 16_384

type AuthEngines interface {

Check failure on line 16 in chain/auth_batch.go

GitHub Actions / hypersdk-lint

exported: exported type AuthEngines should have comment or be unexported (revive)
// GetAuthBatchVerifier returns a verifier for verifying signatures in
// batches for a specific auth type.
GetAuthBatchVerifier(authTypeID uint8, cores int, count int) (AuthBatchVerifier, bool)
}

// Adding a signature to a verification batch

Check failure on line 22 in chain/auth_batch.go

GitHub Actions / hypersdk-lint

exported: comment on exported type AuthBatch should be of the form "AuthBatch ..." (with optional leading article) (revive)
// may perform complex cryptographic operations. We should
// not block the caller when this happens and we should
// not require each batch package to re-implement this logic.
@@ -28,7 +30,7 @@
bvs map[uint8]*authBatchWorker
}

func NewAuthBatch(logger logging.Logger, engines AuthEngines, job workers.Job, authTypes map[uint8]int) *AuthBatch {

Check failure on line 33 in chain/auth_batch.go

GitHub Actions / hypersdk-lint

exported: exported function NewAuthBatch should have comment or be unexported (revive)
bvs := map[uint8]*authBatchWorker{}
for t, count := range authTypes {
bv, ok := engines.GetAuthBatchVerifier(t, job.Workers(), count)
@@ -49,7 +51,7 @@
return &AuthBatch{logger, engines, job, bvs}
}

func (a *AuthBatch) Add(digest []byte, auth Auth) {

Check failure on line 54 in chain/auth_batch.go

GitHub Actions / hypersdk-lint

exported: exported method AuthBatch.Add should have comment or be unexported (revive)
// If batch doesn't exist for auth, just add verify right to job and start
// processing.
bv, ok := a.bvs[auth.GetTypeID()]
@@ -60,7 +62,7 @@
bv.items <- &authBatchObject{digest, auth}
}

func (a *AuthBatch) Done(f func()) {

Check failure on line 65 in chain/auth_batch.go

GitHub Actions / hypersdk-lint

exported: exported method AuthBatch.Done should have comment or be unexported (revive)
for _, bw := range a.bvs {
close(bw.items)
<-bw.done
4 changes: 2 additions & 2 deletions chain/builder.go
Original file line number Diff line number Diff line change
@@ -45,7 +45,7 @@ type Builder struct {
balanceHandler BalanceHandler
mempool Mempool
validityWindow ValidityWindow
metrics *ChainMetrics
metrics *Metrics
config Config
}

@@ -57,7 +57,7 @@ func NewBuilder(
balanceHandler BalanceHandler,
mempool Mempool,
validityWindow ValidityWindow,
metrics *ChainMetrics,
metrics *Metrics,
config Config,
) *Builder {
return &Builder{
72 changes: 61 additions & 11 deletions chain/dependencies.go
Original file line number Diff line number Diff line change
@@ -17,43 +17,65 @@ import (
)

type Parser interface {
// ParseAction parses a marshaled action
ParseAction([]byte) (Action, error)
// ParseAuth parses a marshaled auth
ParseAuth([]byte) (Auth, error)
}

type Mempool interface {
Len(context.Context) int // items
Size(context.Context) int // bytes
// Len returns the number of items in the mempool
Len(context.Context) int
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Linter doesn't seem to apply exported rule correctly.

The Go documentation guidelines specify that documentation comments for exported identifiers should start with the name being declared. This helps with generated documentation, maintains a consistent style, and makes it clear what's being described, especially when multiple declarations are being documented in sequence.

// This lacks a comment
func HandleRequest(w http.ResponseWriter, r *http.Request) {
    // ...
}

// Processes incoming HTTP requests
func HandleRequest(w http.ResponseWriter, r *http.Request) {
    // ...
}

Both of these functions should be targeted.
GoLand IDE is reporting invalid comment pattern as well.

Screenshot 2025-04-09 at 6 27 37 PM

// Size of mempool in bytes
Size(context.Context) int
// Add a list of txs to the mempool
Add(context.Context, []*Transaction)

// StartStreaming signals to the mempool to prepare a new stream of txs
StartStreaming(context.Context)
PrepareStream(context.Context, int)
// PrepareStream signals to the mempool to prepare a new stream of count txs
PrepareStream(ctx context.Context, count int)
// Stream returns a list of txs from the mempool
Stream(context.Context, int) []*Transaction
FinishStreaming(context.Context, []*Transaction) int
// FinishStreaming signals to the mempool that stream is finished and
// restores txs to the mempool
FinishStreaming(ctx context.Context, txs []*Transaction) int
}

type Genesis interface {
// InitializeState sets the initial state diff of the chain
InitializeState(ctx context.Context, tracer trace.Tracer, mu state.Mutable, balanceHandler BalanceHandler) error
}

// TODO: add fixed rules as a subset of this interface
type Rules interface {
// GetNetworkID returns the network ID of the chain
//
// Should almost always be constant (unless there is a fork of
// a live network)
GetNetworkID() uint32
// GetChainID returns the chain ID
GetChainID() ids.ID

GetMinBlockGap() int64 // in milliseconds
GetMinEmptyBlockGap() int64 // in milliseconds
GetValidityWindow() int64 // in milliseconds
// GetMinBlockGap returns the minimum gap between non-empty blocks (in milliseconds)
GetMinBlockGap() int64
// GetMinEmptyBlockGap returns the minimum gap between empty blocks (in milliseconds)
GetMinEmptyBlockGap() int64
// GetValidityWindow returns the validity window for txs (in milliseconds)
GetValidityWindow() int64

// GetMaxActionsPerTx returns the maximum number of actions per tx
GetMaxActionsPerTx() uint8

// GetMinUnitPrice returns the minimum unit price
GetMinUnitPrice() fees.Dimensions
// GetUnitPriceChangeDenominator returns the denominator for unit price changes
GetUnitPriceChangeDenominator() fees.Dimensions
// GetWindowTargetUnits returns the target units for the window
GetWindowTargetUnits() fees.Dimensions
// GetMaxBlockUnits returns the maximum amount of units that a block can consume
GetMaxBlockUnits() fees.Dimensions

// GetBaseComputeUnits returns the minimum amount of compute
GetBaseComputeUnits() uint64

// Invariants:
@@ -62,24 +84,41 @@ type Rules interface {
// * Creating a new key involves first allocating and then writing
// * Keys are only charged once per transaction (even if used multiple times), it is
// up to the controller to ensure multiple usage has some compute cost

// GetSponsorStateKeysMaxChunks returns the maximum number of chunks that
// can be associated with the sponsor account
GetSponsorStateKeysMaxChunks() []uint16
// GetStorageKeyReadUnits returns the fixed cost of reading a kv-pair
GetStorageKeyReadUnits() uint64
GetStorageValueReadUnits() uint64 // per chunk
// GetStorageValueReadUnits returns the variable cost of reading a kv-pair (per chunk)
GetStorageValueReadUnits() uint64
// GetStorageKeyAllocateUnits returns the fixed cost of allocating a kv-pair
GetStorageKeyAllocateUnits() uint64
GetStorageValueAllocateUnits() uint64 // per chunk
// GetStorageValueAllocateUnits returns the variable cost of allocating a kv-pair (per chunk)
GetStorageValueAllocateUnits() uint64
// GetStorageKeyWriteUnits returns the fixed cost of writing a kv-pair
GetStorageKeyWriteUnits() uint64
GetStorageValueWriteUnits() uint64 // per chunk
// GetStorageValueWriteUnits returns the variable cost of writing a kv-pair (per chunk)
GetStorageValueWriteUnits() uint64

// FetchCustom returns a custom rule
// This is used to fetch rules that are not part of the standard rule interface
// The first return value is the value of the rule, and the second return
// value indicates whether the rule exists.
FetchCustom(string) (any, bool)
}

type RuleFactory interface {
// GetRules returns the rules at timestamp t
GetRules(t int64) Rules
}

type MetadataManager interface {
// HeightPrefix returns the prefix key for storing block height
HeightPrefix() []byte
// TimestampPrefix returns the prefix key for storing block timestamp
TimestampPrefix() []byte
// FeePrefix returns the prefix key for storing fees
FeePrefix() []byte
}

@@ -107,6 +146,7 @@ type BalanceHandler interface {
}

type Action interface {
// GetTypeID returns the unique identifier for this action.
GetTypeID() uint8
// ValidRange is the timestamp range (in ms) that this [Action] is considered valid.
//
@@ -208,23 +248,33 @@ type Auth interface {
}

type AuthBatchVerifier interface {
// Add a signature to batch verification.
// If there are enough signatures for a full batch, Add will return a
// function which, when called, verifies the batch
Add([]byte, Auth) func() error
// Done returns a function that verifies the current batch
Done() []func() error
}

type AuthFactory interface {
// Sign is used by helpers, auth object should store internally to be ready for marshaling
Sign(msg []byte) (Auth, error)
// MaxUnits returns the bandwidth and compute units that this factory consumes
MaxUnits() (bandwidth uint64, compute uint64)
// Address of the factory
Address() codec.Address
}

type ValidityWindow interface {
// VerifyExpiryReplayProtection is used to verify that there are no repeats
// within blk and within the validity window
VerifyExpiryReplayProtection(
ctx context.Context,
blk validitywindow.ExecutionBlock[*Transaction],
) error
// Accept blk as most recent
Accept(blk validitywindow.ExecutionBlock[*Transaction])
// IsRepeat checks if the txs are repeats within the validity window
IsRepeat(
ctx context.Context,
parentBlk validitywindow.ExecutionBlock[*Transaction],
7 changes: 7 additions & 0 deletions chain/errors.go
Original file line number Diff line number Diff line change
@@ -7,13 +7,16 @@ import "errors"

var (
// Parsing

ErrInvalidObject = errors.New("invalid object")

// Genesis Correctness

ErrInvalidChainID = errors.New("invalid chain ID")
ErrInvalidBlockRate = errors.New("invalid block rate")

// Block Correctness

ErrTimestampTooEarly = errors.New("timestamp too early")
ErrTimestampTooEarlyEmptyBlock = errors.New("timestamp too early for empty block")
ErrTimestampTooLate = errors.New("timestamp too late")
@@ -31,6 +34,7 @@ var (
ErrInvalidBlockHeight = errors.New("invalid block height")

// Tx Correctness

ErrInvalidSignature = errors.New("invalid signature")
ErrDuplicateTx = errors.New("duplicate transaction")
ErrInsufficientPrice = errors.New("insufficient price")
@@ -53,17 +57,20 @@ var (
ErrTooManyActions = errors.New("too many actions")

// Execution Correctness

ErrBlockTooBig = errors.New("block too big")
ErrKeyNotSpecified = errors.New("key not specified")

// State Correctness

ErrFailedToFetchParentHeight = errors.New("failed to fetch height from state")
ErrFailedToFetchParentTimestamp = errors.New("failed to fetch timestamp from state")
ErrFailedToFetchParentFee = errors.New("failed to fetch fee manager from state")
ErrFailedToParseParentHeight = errors.New("failed to parse height")
ErrFailedToParseParentTimestamp = errors.New("failed to parse timestamp")

// Misc

ErrNotImplemented = errors.New("not implemented")
ErrBlockNotProcessed = errors.New("block is not processed")
ErrInvalidKeyValue = errors.New("invalid key or value")
6 changes: 3 additions & 3 deletions chain/metrics.go
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ import (

const namespace = "chain"

type ChainMetrics struct {
type Metrics struct {
txsBuilt prometheus.Counter
txsVerified prometheus.Counter
txsAccepted prometheus.Counter
@@ -53,8 +53,8 @@ func (em *executorMetrics) RecordExecutable() {
em.executable.Inc()
}

func NewMetrics(reg *prometheus.Registry) (*ChainMetrics, error) {
m := &ChainMetrics{
func NewMetrics(reg *prometheus.Registry) (*Metrics, error) {
m := &Metrics{
txsBuilt: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "txs_built",
4 changes: 2 additions & 2 deletions chain/processor.go
Original file line number Diff line number Diff line change
@@ -83,7 +83,7 @@ type Processor struct {
metadataManager MetadataManager
balanceHandler BalanceHandler
validityWindow ValidityWindow
metrics *ChainMetrics
metrics *Metrics
config Config
}

@@ -96,7 +96,7 @@ func NewProcessor(
metadataManager MetadataManager,
balanceHandler BalanceHandler,
validityWindow ValidityWindow,
metrics *ChainMetrics,
metrics *Metrics,
config Config,
) *Processor {
return &Processor{
2 changes: 1 addition & 1 deletion load/dependencies.go
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ type Issuer[T comparable] interface {
// If a transaction is issued after Stop has been called, the issuer should error.
Stop()

// Issue sends a tx to the network, and informs the tracker that its sent
// IssueTx sends a tx to the network, and informs the tracker that its sent
// said transaction.
IssueTx(ctx context.Context, tx T) error
}
Loading