Skip to content
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

Ban usage of require.Error #1346

Merged
merged 94 commits into from
Apr 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
94 commits
Select commit Hold shift + click to select a range
d03b96d
Ban usage of require.Error
StephenButtolph Apr 14, 2023
bfe48dd
lint apis + chains
StephenButtolph Apr 14, 2023
50b03d1
lint history_test.go
StephenButtolph Apr 14, 2023
4b00093
continuing cleanup
StephenButtolph Apr 14, 2023
4b7e77c
more cleanup
StephenButtolph Apr 14, 2023
2b08634
revert grpc test failure
StephenButtolph Apr 14, 2023
29a2d0a
Add some nolints + improve error interface
StephenButtolph Apr 15, 2023
fcffb84
use errorIs where previously intended
StephenButtolph Apr 15, 2023
3e1174f
wip
StephenButtolph Apr 15, 2023
a543942
wip
StephenButtolph Apr 15, 2023
3c0217c
wip
StephenButtolph Apr 15, 2023
c47dad4
Fix bad addValidatorTx tests
StephenButtolph Apr 15, 2023
f384184
merged
StephenButtolph Apr 17, 2023
3a21dd8
wip
StephenButtolph Apr 17, 2023
1be6077
fix proposal tests
StephenButtolph Apr 17, 2023
fa05f02
Merge branch 'dev' into ban-require-error
StephenButtolph Apr 18, 2023
5e419d2
nit
StephenButtolph Apr 19, 2023
530d076
fix keystore user
StephenButtolph Apr 19, 2023
90ba1ab
nit
StephenButtolph Apr 19, 2023
7d0d353
cleanup test
StephenButtolph Apr 19, 2023
53bca50
cleanup
StephenButtolph Apr 19, 2023
b445380
cleanup
StephenButtolph Apr 19, 2023
6309a37
cleanup aliases
StephenButtolph Apr 19, 2023
dcb3c91
cleanup
StephenButtolph Apr 19, 2023
7ae3c49
cleanup vertex builder tests
StephenButtolph Apr 19, 2023
a0c6820
nit
StephenButtolph Apr 19, 2023
9687dde
more cleanup
StephenButtolph Apr 19, 2023
aaf70b1
cleanup index tests
StephenButtolph Apr 19, 2023
2aba09a
check error
StephenButtolph Apr 19, 2023
c466b86
mor ecleanup
StephenButtolph Apr 19, 2023
0a16f37
cleanup
StephenButtolph Apr 19, 2023
4e18013
nit
StephenButtolph Apr 19, 2023
bc5bfc3
cleanup
StephenButtolph Apr 19, 2023
a6628fa
nit
StephenButtolph Apr 19, 2023
4cb24cf
merged
StephenButtolph Apr 19, 2023
948b115
add nolints
StephenButtolph Apr 19, 2023
a03c3e3
cleanup more tests
StephenButtolph Apr 19, 2023
e94ea5b
cleanup
StephenButtolph Apr 19, 2023
fc885dc
more cleanup
StephenButtolph Apr 19, 2023
e35ed2f
cleanup
StephenButtolph Apr 19, 2023
6ef1ef0
nit
StephenButtolph Apr 19, 2023
55e0773
fix error
StephenButtolph Apr 19, 2023
72412b6
nit
StephenButtolph Apr 19, 2023
0ac8449
nit
StephenButtolph Apr 19, 2023
5631d35
state fixes
StephenButtolph Apr 19, 2023
fb69515
use bls errors
StephenButtolph Apr 19, 2023
a870fc9
cleanup
StephenButtolph Apr 19, 2023
ca7277d
fix delegator tests
StephenButtolph Apr 19, 2023
61e8d4e
fix verifier test
StephenButtolph Apr 19, 2023
5ab4510
cleanup
StephenButtolph Apr 19, 2023
51e800a
fix indexer tests
StephenButtolph Apr 19, 2023
65e3ce1
fix avm service tests
StephenButtolph Apr 19, 2023
b20ddc7
fix platformvm service tests
StephenButtolph Apr 19, 2023
bd00c1b
fix add validator tests
StephenButtolph Apr 19, 2023
1c0e276
fix add subnet validator tests
StephenButtolph Apr 19, 2023
4881b8c
fix add permissionless delegator tx tests
StephenButtolph Apr 19, 2023
9960baa
fix platformvm block acceptor tests
StephenButtolph Apr 19, 2023
2c7d173
fix platformvm regression tests
StephenButtolph Apr 19, 2023
8422653
fix platformvm vm tests
StephenButtolph Apr 19, 2023
9857a15
fix platformvm static service tests
StephenButtolph Apr 19, 2023
65778b0
fix proposal block tests
StephenButtolph Apr 20, 2023
a665afd
remove rng from tests
StephenButtolph Apr 20, 2023
296e757
fix genesis tests
StephenButtolph Apr 20, 2023
06d30c4
fix standard block tests
StephenButtolph Apr 20, 2023
5618975
simple
StephenButtolph Apr 20, 2023
6e7ce81
Merge branch 'dev' into ban-require-error
StephenButtolph Apr 20, 2023
e37782b
fix various proposal tx executor tests
StephenButtolph Apr 20, 2023
a6a395a
nit
StephenButtolph Apr 20, 2023
0ae53f8
fix error
StephenButtolph Apr 20, 2023
67d2cc3
fixed proposal tx executor
StephenButtolph Apr 20, 2023
f9e34d4
fix db manager tests
StephenButtolph Apr 20, 2023
e372eb2
nit
StephenButtolph Apr 20, 2023
3dbd072
Fix standard tx executor
StephenButtolph Apr 20, 2023
f60207e
Fix config tests
StephenButtolph Apr 20, 2023
8926e2f
Remove require.ErrorContains
StephenButtolph Apr 20, 2023
4e4fa41
Merge branch 'dev' into ban-require-error
StephenButtolph Apr 21, 2023
4de7649
Merge branch 'dev' into ban-require-error
StephenButtolph Apr 21, 2023
ab7c2bc
Improve codec/ error handling
StephenButtolph Apr 21, 2023
60adcd9
Merge branch 'codec-error-handling' into ban-require-error
StephenButtolph Apr 21, 2023
46f3ab3
Merge branch 'dev' into ban-require-error
StephenButtolph Apr 21, 2023
de719ad
Improve utils/ error handling
StephenButtolph Apr 21, 2023
7d57fa2
Merge branch 'dev' into codec-error-handling
StephenButtolph Apr 21, 2023
8d95775
Merge branch 'codec-error-handling' into ban-require-error
StephenButtolph Apr 21, 2023
1d4161e
merged
StephenButtolph Apr 21, 2023
bec6bd3
Merge branch 'dev' into utils-error-handling
StephenButtolph Apr 21, 2023
eb04f06
Merge branch 'utils-error-handling' into ban-require-error
StephenButtolph Apr 21, 2023
b49ca6f
Improve consensus error handling
StephenButtolph Apr 21, 2023
9dc2547
Merge branch 'consensus-error-handling' into ban-require-error
StephenButtolph Apr 21, 2023
eb8bf7d
Improve secp256k1fx error handling + merkledb error handling
StephenButtolph Apr 21, 2023
dbfb684
Merge branch 'not-platformvm-error-handling' into ban-require-error
StephenButtolph Apr 21, 2023
630b915
Merge branch 'dev' into not-platformvm-error-handling
StephenButtolph Apr 21, 2023
850b9d0
Merge branch 'not-platformvm-error-handling' into ban-require-error
StephenButtolph Apr 21, 2023
24a937e
Merge branch 'dev' into ban-require-error
StephenButtolph Apr 22, 2023
892943e
ok
StephenButtolph Apr 22, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ linters:
- depguard
- errcheck
- exportloopref
- forbidigo
- goconst
- gocritic
- gofmt
Expand Down Expand Up @@ -49,11 +50,28 @@ linters:
# - lll

linters-settings:
depguard:
list-type: blacklist
packages-with-error-message:
- io/ioutil: 'io/ioutil is deprecated. Use package io or os instead.'
- github.com/stretchr/testify/assert: 'github.com/stretchr/testify/require should be used instead.'
include-go-root: true
errorlint:
# Check for plain type assertions and type switches.
asserts: false
# Check for plain error comparisons.
comparison: false
# https://golangci-lint.run/usage/linters/#forbidigo
forbidigo:
# Forbid the following identifiers (list of regexp).
forbid:
- 'require\.Error$(# ErrorIs should be used instead)?'
- 'require\.ErrorContains$(# ErrorIs should be used instead)?'
exclude_godoc_examples: false
# https://golangci-lint.run/usage/linters#gosec
gosec:
excludes:
- G107 # https://securego.io/docs/rules/g107.html
revive:
rules:
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bool-literal-in-expr
Expand Down Expand Up @@ -103,13 +121,3 @@ linters-settings:
- "all"
- "-SA6002" # argument should be pointer-like to avoid allocation, for sync.Pool
- "-SA1019" # deprecated packages e.g., golang.org/x/crypto/ripemd160
# https://golangci-lint.run/usage/linters#gosec
gosec:
excludes:
- G107 # https://securego.io/docs/rules/g107.html
depguard:
list-type: blacklist
packages-with-error-message:
- io/ioutil: 'io/ioutil is deprecated. Use package io or os instead.'
- github.com/stretchr/testify/assert: 'github.com/stretchr/testify/require should be used instead.'
include-go-root: true
13 changes: 10 additions & 3 deletions chains/atomic/test_shared_memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ func TestSharedMemoryLargeIndexed(t *testing.T, chainID0, chainID1 ids.ID, sm0,

func TestSharedMemoryCantDuplicatePut(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, _ database.Database) {
require := require.New(t)

err := sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{
{
Key: []byte{0},
Expand All @@ -203,26 +204,32 @@ func TestSharedMemoryCantDuplicatePut(t *testing.T, _, chainID1 ids.ID, sm0, _ S
Value: []byte{2},
},
}}})
require.Error(err, "shouldn't be able to write duplicated keys")
// TODO: require error to be errDuplicatedOperation
require.Error(err) //nolint:forbidigo // currently returns grpc errors too

err = sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{
Key: []byte{0},
Value: []byte{1},
}}}})
require.NoError(err)

err = sm0.Apply(map[ids.ID]*Requests{chainID1: {PutRequests: []*Element{{
Key: []byte{0},
Value: []byte{1},
}}}})
require.Error(err, "shouldn't be able to write duplicated keys")
// TODO: require error to be errDuplicatedOperation
require.Error(err) //nolint:forbidigo // currently returns grpc errors too
}

func TestSharedMemoryCantDuplicateRemove(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, _ database.Database) {
require := require.New(t)

err := sm0.Apply(map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{0}}}})
require.NoError(err)

err = sm0.Apply(map[ids.ID]*Requests{chainID1: {RemoveRequests: [][]byte{{0}}}})
require.Error(err, "shouldn't be able to remove duplicated keys")
// TODO: require error to be errDuplicatedOperation
require.Error(err) //nolint:forbidigo // currently returns grpc errors too
}

func TestSharedMemoryCommitOnPut(t *testing.T, _, chainID1 ids.ID, sm0, _ SharedMemory, db database.Database) {
Expand Down
34 changes: 23 additions & 11 deletions ids/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,36 @@
package ids

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

var (
errNoIDWithAlias = errors.New("there is no ID with alias")
errNoAliasForID = errors.New("there is no alias for ID")
errAliasAlreadyMapped = errors.New("alias already mapped to an ID")
)

// AliaserReader allows one to lookup the aliases given to an ID.
type AliaserReader interface {
// Lookup returns the ID associated with alias
Lookup(alias string) (ID, error)

// PrimaryAlias returns the first alias of [id]
PrimaryAlias(id ID) (string, error)

// Aliases returns the aliases of an ID
Aliases(id ID) ([]string, error)
}

// Aliaser allows one to give an ID aliases. An ID can have arbitrarily many
// aliases; two IDs may not have the same alias.
// AliaserWriter allows one to give an ID aliases. An ID can have arbitrarily
// many aliases; two IDs may not have the same alias.
type AliaserWriter interface {
// Alias gives [id] the alias [alias]
Alias(id ID, alias string) error

// RemoveAliases of the provided ID
RemoveAliases(id ID)
}

Expand All @@ -27,6 +42,9 @@ type AliaserWriter interface {
type Aliaser interface {
AliaserReader
AliaserWriter

// PrimaryAliasOrDefault returns the first alias of [id], or ID string as a
// default if no alias exists
PrimaryAliasOrDefault(id ID) string
}

Expand All @@ -43,30 +61,27 @@ func NewAliaser() Aliaser {
}
}

// Lookup returns the ID associated with alias
func (a *aliaser) Lookup(alias string) (ID, error) {
a.lock.RLock()
defer a.lock.RUnlock()

if id, ok := a.dealias[alias]; ok {
return id, nil
}
return ID{}, fmt.Errorf("there is no ID with alias %s", alias)
return ID{}, fmt.Errorf("%w: %s", errNoIDWithAlias, alias)
}

// PrimaryAlias returns the first alias of [id]
func (a *aliaser) PrimaryAlias(id ID) (string, error) {
a.lock.RLock()
defer a.lock.RUnlock()

aliases := a.aliases[id]
if len(aliases) == 0 {
return "", fmt.Errorf("there is no alias for ID %s", id)
return "", fmt.Errorf("%w: %s", errNoAliasForID, id)
}
return aliases[0], nil
}

// PrimaryAliasOrDefault returns the first alias of [id], or ID string as default
func (a *aliaser) PrimaryAliasOrDefault(id ID) string {
alias, err := a.PrimaryAlias(id)
if err != nil {
Expand All @@ -75,29 +90,26 @@ func (a *aliaser) PrimaryAliasOrDefault(id ID) string {
return alias
}

// Aliases returns the aliases of an ID
func (a *aliaser) Aliases(id ID) ([]string, error) {
a.lock.RLock()
defer a.lock.RUnlock()

return a.aliases[id], nil
}

// Alias gives [id] the alias [alias]
func (a *aliaser) Alias(id ID, alias string) error {
a.lock.Lock()
defer a.lock.Unlock()

if _, exists := a.dealias[alias]; exists {
return fmt.Errorf("%s is already used as an alias for an ID", alias)
return fmt.Errorf("%w: %s", errAliasAlreadyMapped, alias)
}

a.dealias[alias] = id
a.aliases[id] = append(a.aliases[id], alias)
return nil
}

// RemoveAliases of the provided ID
func (a *aliaser) RemoveAliases(id ID) {
a.lock.Lock()
defer a.lock.Unlock()
Expand Down
12 changes: 8 additions & 4 deletions ids/test_aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ var AliasTests = []func(require *require.Assertions, r AliaserReader, w AliaserW

func AliaserLookupErrorTest(require *require.Assertions, r AliaserReader, _ AliaserWriter) {
_, err := r.Lookup("Batman")
require.Error(err, "expected an error due to missing alias")
// TODO: require error to be errNoIDWithAlias
require.Error(err) //nolint:forbidigo // currently returns grpc errors too
}

func AliaserLookupTest(require *require.Assertions, r AliaserReader, w AliaserWriter) {
Expand Down Expand Up @@ -63,7 +64,8 @@ func AliaserPrimaryAliasTest(require *require.Assertions, r AliaserReader, w Ali
require.NoError(err)

_, err = r.PrimaryAlias(id1)
require.Error(err)
// TODO: require error to be errNoAliasForID
require.Error(err) //nolint:forbidigo // currently returns grpc errors too

expected := "Batman"
res, err := r.PrimaryAlias(id2)
Expand All @@ -78,7 +80,8 @@ func AliaserAliasClashTest(require *require.Assertions, _ AliaserReader, w Alias
require.NoError(err)

err = w.Alias(id2, "Batman")
require.Error(err)
// TODO: require error to be errAliasAlreadyMapped
require.Error(err) //nolint:forbidigo // currently returns grpc errors too
}

func AliaserRemoveAliasTest(require *require.Assertions, r AliaserReader, w AliaserWriter) {
Expand All @@ -93,7 +96,8 @@ func AliaserRemoveAliasTest(require *require.Assertions, r AliaserReader, w Alia
w.RemoveAliases(id1)

_, err = r.PrimaryAlias(id1)
require.Error(err)
// TODO: require error to be errNoAliasForID
require.Error(err) //nolint:forbidigo // currently returns grpc errors too

err = w.Alias(id2, "Batman")
require.NoError(err)
Expand Down
11 changes: 6 additions & 5 deletions vms/platformvm/api/static_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ import (
// state of the network.

var (
errUTXOHasNoValue = errors.New("genesis UTXO has no value")
errValidatorAddsNoValue = errors.New("validator would have already unstaked")
errStakeOverflow = errors.New("validator stake exceeds limit")
errUTXOHasNoValue = errors.New("genesis UTXO has no value")
errValidatorHasNoWeight = errors.New("validator has not weight")
errValidatorAlreadyExited = errors.New("validator would have already unstaked")
errStakeOverflow = errors.New("validator stake exceeds limit")

_ utils.Sortable[UTXO] = UTXO{}
)
Expand Down Expand Up @@ -278,10 +279,10 @@ func (*StaticService) BuildGenesis(_ *http.Request, args *BuildGenesisArgs, repl
}

if weight == 0 {
return errValidatorAddsNoValue
return errValidatorHasNoWeight
}
if uint64(vdr.EndTime) <= uint64(args.Time) {
return errValidatorAddsNoValue
return errValidatorAlreadyExited
}

owner := &secp256k1fx.OutputOwners{
Expand Down
25 changes: 11 additions & 14 deletions vms/platformvm/api/static_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@ import (
"github.com/ava-labs/avalanchego/vms/platformvm/genesis"
)

const testNetworkID = 10 // To be used in tests

func TestBuildGenesisInvalidUTXOBalance(t *testing.T) {
require := require.New(t)
nodeID := ids.NodeID{1, 2, 3}
hrp := constants.NetworkIDToHRP[testNetworkID]
addr, err := address.FormatBech32(hrp, nodeID.Bytes())
addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes())
require.NoError(err)

utxo := UTXO{
Expand Down Expand Up @@ -59,14 +56,14 @@ func TestBuildGenesisInvalidUTXOBalance(t *testing.T) {
reply := BuildGenesisReply{}

ss := StaticService{}
require.Error(ss.BuildGenesis(nil, &args, &reply), "should have errored due to an invalid balance")
err = ss.BuildGenesis(nil, &args, &reply)
require.ErrorIs(err, errUTXOHasNoValue)
}

func TestBuildGenesisInvalidAmount(t *testing.T) {
func TestBuildGenesisInvalidStakeWeight(t *testing.T) {
require := require.New(t)
nodeID := ids.NodeID{1, 2, 3}
hrp := constants.NetworkIDToHRP[testNetworkID]
addr, err := address.FormatBech32(hrp, nodeID.Bytes())
addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes())
require.NoError(err)

utxo := UTXO{
Expand Down Expand Up @@ -103,14 +100,14 @@ func TestBuildGenesisInvalidAmount(t *testing.T) {
reply := BuildGenesisReply{}

ss := StaticService{}
require.Error(ss.BuildGenesis(nil, &args, &reply), "should have errored due to an invalid amount")
err = ss.BuildGenesis(nil, &args, &reply)
require.ErrorIs(err, errValidatorHasNoWeight)
}

func TestBuildGenesisInvalidEndtime(t *testing.T) {
require := require.New(t)
nodeID := ids.NodeID{1, 2, 3}
hrp := constants.NetworkIDToHRP[testNetworkID]
addr, err := address.FormatBech32(hrp, nodeID.Bytes())
addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes())
require.NoError(err)

utxo := UTXO{
Expand Down Expand Up @@ -148,14 +145,14 @@ func TestBuildGenesisInvalidEndtime(t *testing.T) {
reply := BuildGenesisReply{}

ss := StaticService{}
require.Error(ss.BuildGenesis(nil, &args, &reply), "should have errored due to an invalid end time")
err = ss.BuildGenesis(nil, &args, &reply)
require.ErrorIs(err, errValidatorAlreadyExited)
}

func TestBuildGenesisReturnsSortedValidators(t *testing.T) {
require := require.New(t)
nodeID := ids.NodeID{1}
hrp := constants.NetworkIDToHRP[testNetworkID]
addr, err := address.FormatBech32(hrp, nodeID.Bytes())
addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes())
require.NoError(err)

utxo := UTXO{
Expand Down
12 changes: 6 additions & 6 deletions vms/platformvm/blocks/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ const targetBlockSize = 128 * units.KiB
var (
_ Builder = (*builder)(nil)

errEndOfTime = errors.New("program time is suspiciously far in the future")
errNoPendingBlocks = errors.New("no pending blocks")
errChainNotSynced = errors.New("chain not synced")
ErrEndOfTime = errors.New("program time is suspiciously far in the future")
ErrNoPendingBlocks = errors.New("no pending blocks")
ErrChainNotSynced = errors.New("chain not synced")
)

type Builder interface {
Expand Down Expand Up @@ -126,7 +126,7 @@ func (b *builder) Preferred() (snowman.Block, error) {
// AddUnverifiedTx verifies a transaction and attempts to add it to the mempool
func (b *builder) AddUnverifiedTx(tx *txs.Tx) error {
if !b.txExecutorBackend.Bootstrapped.Get() {
return errChainNotSynced
return ErrChainNotSynced
}

txID := tx.ID()
Expand Down Expand Up @@ -369,7 +369,7 @@ func buildBlock(
// If there is no reason to build a block, don't.
if !builder.Mempool.HasTxs() && !forceAdvanceTime {
builder.txExecutorBackend.Ctx.Log.Debug("no pending txs to issue into a block")
return nil, errNoPendingBlocks
return nil, ErrNoPendingBlocks
}

// Issue a block with as many transactions as possible.
Expand All @@ -394,7 +394,7 @@ func getNextStakerToReward(
preferredState state.Chain,
) (ids.ID, bool, error) {
if !chainTimestamp.Before(mockable.MaxTime) {
return ids.Empty, false, errEndOfTime
return ids.Empty, false, ErrEndOfTime
}

currentStakerIterator, err := preferredState.GetCurrentStakerIterator()
Expand Down
Loading