From 03670eb4cab7e3412eb3a064ef45e5ec0aa28d94 Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Wed, 28 Feb 2024 14:28:59 +0100 Subject: [PATCH 1/2] chore: update go to 1.21 + update CI pipeline Signed-off-by: Minh Huy Tran --- .github/workflows/ci.yml | 24 +- .golangci.yml | 5 +- apps/payment/app_internal_test.go | 7 +- apps/payment/randomizer_internal_test.go | 3 +- apps/payment/resolver_internal_test.go | 6 +- backend/sim/channel/backend.go | 5 +- backend/sim/wallet/address.go | 16 +- backend/sim/wallet/address_internal_test.go | 5 +- backend/sim/wallet/wallet_internal_test.go | 15 +- backend/sim/wallet/wallet_test.go | 6 +- backend/sim/wire/account.go | 2 +- backend/sim/wire/address.go | 4 +- channel/adjudicator.go | 12 +- channel/allocation.go | 24 +- channel/allocation_test.go | 57 ++-- channel/app.go | 19 +- channel/app_test.go | 14 +- channel/appregistry_internal_test.go | 5 +- channel/backend.go | 4 +- channel/funder.go | 2 +- channel/funder_internal_test.go | 9 +- channel/machine.go | 10 +- channel/mock_app.go | 10 +- channel/mock_app_internal_test.go | 27 +- channel/persistence/keyvalue/cache.go | 1 + channel/persistence/keyvalue/persister.go | 4 +- .../keyvalue/persistrestorer_internal_test.go | 4 +- channel/persistence/keyvalue/restorer.go | 6 +- channel/persistence/persistence.go | 16 +- channel/persistence/statemachine.go | 4 +- channel/persistence/test/channel.go | 6 +- channel/persistence/test/peerchans.go | 2 +- .../persistence/test/persistrestorertest.go | 2 + channel/statemachine.go | 7 +- channel/test/app_randomizer.go | 4 +- channel/test/app_randomizer_internal_test.go | 4 +- channel/test/backend.go | 18 +- channel/test/randomizer.go | 43 +-- channel/test/randomopts.go | 12 +- client/adjudicate.go | 61 +++-- client/chanregistry.go | 9 +- client/client.go | 4 +- client/client_persistence_test.go | 8 +- client/client_test.go | 2 +- client/clientconn.go | 4 +- client/failing_funding_test.go | 2 +- client/proposal.go | 38 +-- client/proposalmsgs.go | 31 ++- client/proposalmsgs_test.go | 4 +- client/restore_internal_test.go | 10 +- client/serialize.go | 47 ++-- client/sync.go | 8 +- client/test/backend.go | 8 +- client/test/bob.go | 2 +- client/test/carol.go | 2 +- client/test/fund.go | 4 +- client/test/handler.go | 6 +- client/test/multiledger_dispute.go | 6 +- client/test/multiledger_happy.go | 4 +- client/test/progression.go | 4 +- client/test/proposalmsgs.go | 5 +- client/test/role.go | 27 +- client/test/subchannel.go | 4 +- client/test/updatemsgs.go | 6 +- client/test/virtualchannel.go | 19 +- client/update.go | 26 +- client/updatemsgs.go | 33 ++- client/virtual_channel.go | 14 +- client/virtual_channel_settlement.go | 4 +- client/virtual_channel_util.go | 11 +- go.mod | 2 +- go.sum | 3 - log/log.go | 40 +-- log/logrus/logrus.go | 2 +- log/logrus/logrus_internal_test.go | 20 +- log/none.go | 2 +- wallet/address.go | 15 +- wallet/backend.go | 2 +- wallet/sig.go | 10 +- wallet/test/address.go | 6 +- wallet/test/randomizer.go | 4 +- wallet/test/wallet.go | 14 +- wallet/wallet.go | 6 +- watcher/local/adjudicatorpubsub.go | 18 +- watcher/local/statespubsub.go | 20 +- watcher/local/watcher.go | 2 +- watcher/local/watcher_test.go | 3 +- watcher/watcher.go | 6 +- wire/account.go | 3 +- wire/address.go | 4 +- wire/cache.go | 4 +- wire/cache_internal_test.go | 2 +- wire/consumer.go | 2 +- wire/hybridbus_test.go | 8 +- wire/localbus_test.go | 2 +- wire/net/bus.go | 5 +- wire/net/conn.go | 2 +- wire/net/endpoint.go | 2 +- wire/net/endpoint_internal_test.go | 29 +- wire/net/endpoint_registry.go | 20 +- wire/net/endpoint_registry_external_test.go | 8 +- wire/net/endpoint_registry_internal_test.go | 36 +-- wire/net/exchange_addr.go | 8 +- wire/net/exchange_addr_internal_test.go | 11 +- wire/net/simple/address.go | 3 +- wire/net/simple/dialer_internal_test.go | 28 +- wire/net/simple/listener_internal_test.go | 14 +- wire/net/simple/simple_exchange_addr_test.go | 13 +- wire/net/test/connhub.go | 6 +- wire/net/test/connhub_internal_test.go | 24 +- wire/net/test/dialer_internal_test.go | 9 +- wire/net/test/dialerlist_internal_test.go | 12 +- wire/net/test/listener_internal_test.go | 13 +- wire/net/test/listenermap_internal_test.go | 13 +- wire/net/test/pipeconn.go | 14 +- wire/perunio/bigint_external_test.go | 11 +- wire/perunio/byteslice_external_test.go | 7 +- wire/perunio/serialize.go | 6 +- wire/perunio/serializer.go | 4 +- wire/perunio/serializer/serializer.go | 5 +- wire/perunio/string_internal_test.go | 12 +- wire/perunio/test/msgtest.go | 3 +- wire/perunio/wire_internal_test.go | 6 +- wire/protobuf/controlmsgs.go | 45 +-- wire/protobuf/proposalmsgs.go | 256 ++++++++++-------- wire/protobuf/serializer.go | 13 +- wire/protobuf/syncmsgs.go | 22 +- wire/protobuf/updatemsgs.go | 147 +++++----- wire/pubsub.go | 4 +- wire/receiver_internal_test.go | 15 +- wire/relay_internal_test.go | 26 +- wire/relay_test.go | 3 +- wire/test/address.go | 8 +- wire/test/bustest.go | 12 +- wire/test/serializinglocalbus.go | 8 +- 135 files changed, 1040 insertions(+), 880 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e62105574..7e7ded08b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ on: release: env: - go-version: 1.17 + go-version: 1.21 jobs: check-copyright: @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4.1.1 with: fetch-depth: 0 - name: Authors @@ -26,23 +26,23 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4.1.1 - name: Check vanity import run: .scripts/check-vanity-imports.sh $GITHUB_WORKSPACE - name: Setup Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v4 with: go-version: ${{ env.go-version }} - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.43 + version: v1.55 - name: Lint proto files - uses: plexsystems/protolint-action@v0.6.0 + uses: plexsystems/protolint-action@v0.7.0 with: configDirectory: . @@ -51,14 +51,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Setup Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v4 with: go-version: ${{ env.go-version }} - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4.1.1 - - uses: actions/cache@v2 + - uses: actions/cache@v4.0.0 with: path: | ~/.cache/go-build @@ -75,14 +75,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Setup Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v4 with: go-version: ${{ env.go-version }} - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4.1.1 - - uses: actions/cache@v2 + - uses: actions/cache@v4.0.0 with: path: | ~/.cache/go-build diff --git a/.golangci.yml b/.golangci.yml index b25ce4581..1221be651 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -26,6 +26,9 @@ linters: - gci # We have our own import order. - goerr113 # We do not strictly require static errors. - promlinter # Disabled because unstable. + - nosnakecase # We use snake case. + - depguard # We use go modules. + - exhaustruct # We often have uninitialized fields of structs. # These could be enabled in the future: - ifshort # we often don't use `if err := …` for readability. @@ -77,4 +80,4 @@ issues: # therefore disable the "context must be the first argument" check in tests. - path: test linters: [revive] - text: "context-as-argument" + text: "context-as-argument" \ No newline at end of file diff --git a/apps/payment/app_internal_test.go b/apps/payment/app_internal_test.go index 7834afc65..4cebc2283 100644 --- a/apps/payment/app_internal_test.go +++ b/apps/payment/app_internal_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/channel" "perun.network/go-perun/channel/test" @@ -42,7 +43,7 @@ func TestApp_ValidInit(t *testing.T) { assert.Panics(func() { app.ValidInit(nil, wrongdata) }) //nolint:errcheck data := &channel.State{Data: Data()} - assert.Nil(app.ValidInit(nil, data)) + require.NoError(t, app.ValidInit(nil, data)) } func TestApp_ValidTransition(t *testing.T) { @@ -95,7 +96,7 @@ func TestApp_ValidTransition(t *testing.T) { numParticipants := len(tt.from[0]) for i := 0; i < numParticipants; i++ { // valid self-transition - assert.NoError(app.ValidTransition(nil, from, from, channel.Index(i))) + require.NoError(t, app.ValidTransition(nil, from, from, channel.Index(i))) } for _, tto := range tt.tos { @@ -107,7 +108,7 @@ func TestApp_ValidTransition(t *testing.T) { for i := 0; i < numParticipants; i++ { err := app.ValidTransition(nil, from, to, channel.Index(i)) if i == tto.valid { - assert.NoError(err) + require.NoError(t, err) } else { assert.Error(err) } diff --git a/apps/payment/randomizer_internal_test.go b/apps/payment/randomizer_internal_test.go index 9a9dea688..10012ae3e 100644 --- a/apps/payment/randomizer_internal_test.go +++ b/apps/payment/randomizer_internal_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" _ "perun.network/go-perun/backend/sim" // backend init "perun.network/go-perun/channel" @@ -31,7 +32,7 @@ func TestRandomizer(t *testing.T) { app := r.NewRandomApp(rng) channel.RegisterApp(app) regApp, err := channel.Resolve(app.Def()) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, app.Def().Equal(regApp.Def())) assert.True(t, IsData(r.NewRandomData(rng))) } diff --git a/apps/payment/resolver_internal_test.go b/apps/payment/resolver_internal_test.go index 6c7de90b3..2e6e93309 100644 --- a/apps/payment/resolver_internal_test.go +++ b/apps/payment/resolver_internal_test.go @@ -36,7 +36,7 @@ func TestResolver(t *testing.T) { channel.RegisterAppResolver(def.Equal, &Resolver{}) app, err := channel.Resolve(def) - assert.NoError(err) + require.NoError(err) require.NotNil(app) assert.True(def.Equal(app.Def())) } @@ -47,13 +47,13 @@ func TestData(t *testing.T) { assert.NotPanics(func() { data := Data() _, err := data.MarshalBinary() - assert.Nil(err) + require.NoError(t, err) }) assert.NotPanics(func() { app := new(App) data := app.NewData() - assert.NoError(data.UnmarshalBinary(nil)) + require.NoError(t, data.UnmarshalBinary(nil)) assert.NotNil(data) assert.True(IsData(data)) }) diff --git a/backend/sim/channel/backend.go b/backend/sim/channel/backend.go index 57e53ad7b..86817ba29 100644 --- a/backend/sim/channel/backend.go +++ b/backend/sim/channel/backend.go @@ -33,7 +33,8 @@ type backend struct{} var _ channel.Backend = new(backend) // CalcID calculates a channel's ID by hashing all fields of its parameters. -func (*backend) CalcID(p *channel.Params) (id channel.ID) { +func (*backend) CalcID(p *channel.Params) channel.ID { + var id channel.ID w := sha256.New() // Write Parts @@ -51,7 +52,7 @@ func (*backend) CalcID(p *channel.Params) (id channel.ID) { if copy(id[:], w.Sum(nil)) != channel.IDLen { log.Panic("Could not copy id") } - return + return id } // Sign signs `state`. diff --git a/backend/sim/wallet/address.go b/backend/sim/wallet/address.go index 6b4d4a49f..09cdf6343 100644 --- a/backend/sim/wallet/address.go +++ b/backend/sim/wallet/address.go @@ -62,7 +62,8 @@ func (a *Address) Bytes() []byte { // byteArray converts an address into a 64-byte array. The returned array // consists of two 32-byte chunks representing the public key's X and Y values. -func (a *Address) byteArray() (data [addrLen]byte) { +func (a *Address) byteArray() [addrLen]byte { + var data [addrLen]byte xb := a.X.Bytes() yb := a.Y.Bytes() @@ -89,12 +90,15 @@ func (a *Address) Equal(addr wallet.Address) bool { return (a.X.Cmp(b.X) == 0) && (a.Y.Cmp(b.Y) == 0) } -// Cmp checks the ordering of two addresses according to following definition: -// -1 if (a.X < addr.X) || ((a.X == addr.X) && (a.Y < addr.Y)) -// 0 if (a.X == addr.X) && (a.Y == addr.Y) -// +1 if (a.X > addr.X) || ((a.X == addr.X) && (a.Y > addr.Y)) +// Cmp checks the ordering of two addresses according to the following definition: +// +// -1 if (a.X < addr.X) || ((a.X == addr.X) && (a.Y < addr.Y)) +// 0 if (a.X == addr.X) && (a.Y == addr.Y) +// +1 if (a.X > addr.X) || ((a.X == addr.X) && (a.Y > addr.Y)) +// // So the X coordinate is weighted higher. -// Pancis if the passed address is of the wrong type. +// +// It panics if the passed address is of the wrong type. func (a *Address) Cmp(addr wallet.Address) int { b, ok := addr.(*Address) if !ok { diff --git a/backend/sim/wallet/address_internal_test.go b/backend/sim/wallet/address_internal_test.go index c3f5e703f..46bd5a444 100644 --- a/backend/sim/wallet/address_internal_test.go +++ b/backend/sim/wallet/address_internal_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" pkgtest "polycry.pt/poly-go/test" "perun.network/go-perun/wire/test" @@ -43,7 +44,7 @@ func TestAddressMarshalling(t *testing.T) { Y: new(big.Int).SetBytes(dest[elemLen:]), } result, err := addr.MarshalBinary() - assert.NoError(t, err, "marshaling address should not error") + require.NoError(t, err, "marshaling address should not error") assert.Equal(t, result, dest[:]) }) @@ -59,7 +60,7 @@ func TestAddressMarshalling(t *testing.T) { Y: new(big.Int).SetBytes(dest[elemLen:]), } result, err := addr.MarshalBinary() - assert.NoError(t, err, "marshaling address should not error") + require.NoError(t, err, "marshaling address should not error") assert.Equal(t, result, dest[:]) }) } diff --git a/backend/sim/wallet/wallet_internal_test.go b/backend/sim/wallet/wallet_internal_test.go index b6f6a4d7f..25b3ec727 100644 --- a/backend/sim/wallet/wallet_internal_test.go +++ b/backend/sim/wallet/wallet_internal_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wallet/test" pkgtest "polycry.pt/poly-go/test" @@ -45,11 +46,11 @@ func TestSignatureSerialize(t *testing.T) { s := new(big.Int).SetBytes(sBytes) sig, err1 := serializeSignature(r, s) - a.Nil(err1, "Serialization should not fail") - a.Equal(curve.Params().BitSize/4, len(sig), "Signature has wrong size") + require.NoError(t, err1, "Serialization should not fail") + a.Len(sig, curve.Params().BitSize/4, "Signature has wrong size") R, S, err2 := deserializeSignature(sig) - a.Nil(err2, "Deserialization should not fail") + require.NoError(t, err2, "Deserialization should not fail") a.Equal(r, R, "Serialized and deserialized r values should be equal") a.Equal(s, S, "Serialized and deserialized s values should be equal") } @@ -80,10 +81,10 @@ func TestGenericTests(t *testing.T) { addrStrLen := addrLen*2 + 2 // hex encoded and prefixed with 0x str0 := addr0.String() str1 := addr1.String() - assert.Equal( - t, addrStrLen, len(str0), "First address '%v' has wrong length", str0) - assert.Equal( - t, addrStrLen, len(str1), "Second address '%v' has wrong length", str1) + assert.Len( + t, str0, addrStrLen, "First address '%v' has wrong length", str0) + assert.Len( + t, str1, addrStrLen, "Second address '%v' has wrong length", str1) assert.NotEqual( t, str0, str1, "Printed addresses are unlikely to be identical") } diff --git a/backend/sim/wallet/wallet_test.go b/backend/sim/wallet/wallet_test.go index 1f1989b00..910e886a6 100644 --- a/backend/sim/wallet/wallet_test.go +++ b/backend/sim/wallet/wallet_test.go @@ -30,9 +30,9 @@ func TestWallet_AddAccount(t *testing.T) { acc := wallet.NewRandomAccount(rng) assert.False(t, w.HasAccount(acc)) - assert.NoError(t, w.AddAccount(acc)) + require.NoError(t, w.AddAccount(acc)) assert.True(t, w.HasAccount(acc)) - assert.Error(t, w.AddAccount(acc)) + require.Error(t, w.AddAccount(acc)) } func TestWallet_Unlock(t *testing.T) { @@ -76,7 +76,7 @@ func TestWallet_Unlock(t *testing.T) { t.Run("unknown unlock", func(t *testing.T) { acc, err := w.Unlock(wallet.NewRandomAddress(rng)) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, acc) }) } diff --git a/backend/sim/wire/account.go b/backend/sim/wire/account.go index 191cbcd17..7dfe3a1c3 100644 --- a/backend/sim/wire/account.go +++ b/backend/sim/wire/account.go @@ -31,7 +31,7 @@ func (acc *Account) Address() wire.Address { } // Sign signs the given message with the account's private key. -func (acc *Account) Sign(msg []byte) ([]byte, error) { +func (acc *Account) Sign(_ []byte) ([]byte, error) { return []byte("Authenticate"), nil } diff --git a/backend/sim/wire/address.go b/backend/sim/wire/address.go index 4c241dc5c..2187ae94b 100644 --- a/backend/sim/wire/address.go +++ b/backend/sim/wire/address.go @@ -34,7 +34,7 @@ func NewAddress() *Address { } // MarshalBinary marshals the address to binary. -func (a Address) MarshalBinary() (data []byte, err error) { +func (a Address) MarshalBinary() ([]byte, error) { return a[:], nil } @@ -64,7 +64,7 @@ func (a Address) Cmp(b wire.Address) int { } // Verify verifies a signature. -func (a Address) Verify(msg, sig []byte) error { +func (a Address) Verify(_, sig []byte) error { if !bytes.Equal(sig, []byte("Authenticate")) { return errors.New("invalid signature") } diff --git a/channel/adjudicator.go b/channel/adjudicator.go index ddfd1a7b0..0b9072339 100644 --- a/channel/adjudicator.go +++ b/channel/adjudicator.go @@ -65,7 +65,7 @@ type ( // If the channel has locked funds into sub-channels, the corresponding // signed sub-channel states must be provided. Registerer interface { - Register(context.Context, AdjudicatorReq, []SignedState) error + Register(ctx context.Context, adjReq AdjudicatorReq, signedStates []SignedState) error } // Withdrawer is the interface that wraps the Withdraw method. @@ -77,7 +77,7 @@ type ( // If the channel has locked funds in sub-channels, the states of the // corresponding sub-channels need to be supplied additionally. Withdrawer interface { - Withdraw(context.Context, AdjudicatorReq, StateMap) error + Withdraw(ctx context.Context, adjReq AdjudicatorReq, stateMap StateMap) error } // Progresser is the interface that wraps the Progress method. @@ -87,7 +87,7 @@ type ( // contain the state, the signatures can be nil, since the old state is // already registered on the adjudicator. Progresser interface { - Progress(context.Context, ProgressReq) error + Progress(ctx context.Context, progReq ProgressReq) error } // EventSubscriber is the interface that wraps the Subscribe method. @@ -98,7 +98,7 @@ type ( // subscription should be closed by calling Close on the subscription after // the channel is closed. EventSubscriber interface { - Subscribe(context.Context, ID) (AdjudicatorSubscription, error) + Subscribe(ctx context.Context, ID ID) (AdjudicatorSubscription, error) } // An AdjudicatorReq collects all necessary information to make calls to the @@ -196,11 +196,11 @@ type ( Timeout interface { // IsElapsed should return whether the timeout has elapsed at the time of // the call of this method. - IsElapsed(context.Context) bool + IsElapsed(ctx context.Context) bool // Wait waits for the timeout to elapse. If the context is canceled, Wait // should return immediately with the context's error. - Wait(context.Context) error + Wait(ctx context.Context) error } // StateMap represents a channel state tree. diff --git a/channel/allocation.go b/channel/allocation.go index d0f04038e..6c7673fca 100644 --- a/channel/allocation.go +++ b/channel/allocation.go @@ -97,7 +97,7 @@ type ( // from binary format (a byte array). encoding.BinaryUnmarshaler // Equal returns true iff this asset is equal to the given asset. - Equal(Asset) bool + Equal(asset Asset) bool } ) @@ -184,12 +184,11 @@ func (a *Allocation) NumParts() int { // Clone returns a deep copy of the Allocation object. // If it is nil, it returns nil. -func (a Allocation) Clone() (clone Allocation) { +func (a Allocation) Clone() Allocation { + var clone Allocation if a.Assets != nil { clone.Assets = make([]Asset, len(a.Assets)) - for i, asset := range a.Assets { - clone.Assets[i] = asset - } + copy(clone.Assets, a.Assets) } clone.Balances = a.Balances.Clone() @@ -445,14 +444,14 @@ func CloneBals(orig []Bal) []Bal { } // CloneIndexMap creates a deep copy of an index map. -func CloneIndexMap(orig []Index) (clone []Index) { +func CloneIndexMap(orig []Index) []Index { if orig == nil { return nil } - clone = make([]Index, len(orig)) + clone := make([]Index, len(orig)) copy(clone, orig) - return + return clone } // Valid checks that the asset-dimensions match and slices are not nil. @@ -542,15 +541,18 @@ func NewSubAlloc(id ID, bals []Bal, indexMap []Index) *SubAlloc { // SubAlloc tries to return the sub-allocation for the given subchannel. // The second return value indicates success. -func (a Allocation) SubAlloc(subchannel ID) (subAlloc SubAlloc, ok bool) { +func (a Allocation) SubAlloc(subchannel ID) (SubAlloc, bool) { + var subAlloc SubAlloc + var ok bool + for _, subAlloc = range a.Locked { if subAlloc.ID == subchannel { ok = true - return + return subAlloc, ok } } ok = false - return + return subAlloc, ok } // AddSubAlloc adds the given sub-allocation. diff --git a/channel/allocation_test.go b/channel/allocation_test.go index 0751fbe5f..7cc57af85 100644 --- a/channel/allocation_test.go +++ b/channel/allocation_test.go @@ -64,7 +64,7 @@ func TestAllocationNumParts(t *testing.T) { } } -func randomBalancesWithMismatchingNumAssets(rng *rand.Rand, rngBase int) (b1, b2 channel.Balances) { +func randomBalancesWithMismatchingNumAssets(rng *rand.Rand, rngBase int) (channel.Balances, channel.Balances) { numParts := 2 + rng.Intn(rngBase) randomNumAssets := func() int { @@ -76,13 +76,13 @@ func randomBalancesWithMismatchingNumAssets(rng *rand.Rand, rngBase int) (b1, b2 numAssets2 = randomNumAssets() } - b1 = test.NewRandomBalances(rng, test.WithNumAssets(numAssets1), test.WithNumParts(numParts)) - b2 = test.NewRandomBalances(rng, test.WithNumAssets(numAssets2), test.WithNumParts(numParts)) + b1 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets1), test.WithNumParts(numParts)) + b2 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets2), test.WithNumParts(numParts)) - return + return b1, b2 } -func randomBalancesWithMismatchingNumParts(rng *rand.Rand, rngBase int) (b1, b2 channel.Balances) { +func randomBalancesWithMismatchingNumParts(rng *rand.Rand, rngBase int) (channel.Balances, channel.Balances) { numAssets := 1 + rng.Intn(rngBase) randomNumParts := func() int { @@ -94,10 +94,10 @@ func randomBalancesWithMismatchingNumParts(rng *rand.Rand, rngBase int) (b1, b2 numParts2 = randomNumParts() } - b1 = test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts1)) - b2 = test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts2)) + b1 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts1)) + b2 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts2)) - return + return b1, b2 } func TestBalancesEqualAndAssertEqual(t *testing.T) { @@ -105,19 +105,19 @@ func TestBalancesEqualAndAssertEqual(t *testing.T) { rng := pkgtest.Prng(t) const rngBase = 10 - t.Run("fails with mismatching number of assets", func(t *testing.T) { + t.Run("fails with mismatching number of assets", func(_ *testing.T) { b1, b2 := randomBalancesWithMismatchingNumAssets(rng, rngBase) assert.False(b1.Equal(b2)) - assert.Error(b1.AssertEqual(b2)) + require.Error(t, b1.AssertEqual(b2)) }) - t.Run("fails with mismatching number of parts", func(t *testing.T) { + t.Run("fails with mismatching number of parts", func(_ *testing.T) { b1, b2 := randomBalancesWithMismatchingNumParts(rng, rngBase) assert.False(b1.Equal(b2)) - assert.Error(b1.AssertEqual(b2)) + require.Error(t, b1.AssertEqual(b2)) }) - t.Run("compares correctly", func(t *testing.T) { + t.Run("compares correctly", func(_ *testing.T) { numAssets := 1 + rng.Intn(rngBase) numParts := 2 + rng.Intn(rngBase) @@ -125,37 +125,36 @@ func TestBalancesEqualAndAssertEqual(t *testing.T) { b2 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts), test.WithBalancesInRange(big.NewInt(rngBase), big.NewInt(2*rngBase))) assert.False(b1.Equal(b2)) - assert.Error(b1.AssertEqual(b2)) + require.Error(t, b1.AssertEqual(b2)) assert.True(b1.Equal(b1)) //nolint:gocritic - assert.NoError(b1.AssertEqual(b1)) + require.NoError(t, b1.AssertEqual(b1)) }) } func TestBalancesGreaterOrEqual(t *testing.T) { - assert := assert.New(t) rng := pkgtest.Prng(t) const rngBase = 10 - t.Run("fails with mismatching number of assets", func(t *testing.T) { + t.Run("fails with mismatching number of assets", func(_ *testing.T) { b1, b2 := randomBalancesWithMismatchingNumAssets(rng, rngBase) - assert.Error(b1.AssertGreaterOrEqual(b2)) + require.Error(t, b1.AssertGreaterOrEqual(b2)) }) - t.Run("fails with mismatching number of parts", func(t *testing.T) { + t.Run("fails with mismatching number of parts", func(_ *testing.T) { b1, b2 := randomBalancesWithMismatchingNumParts(rng, rngBase) - assert.Error(b1.AssertGreaterOrEqual(b2)) + require.Error(t, b1.AssertGreaterOrEqual(b2)) }) - t.Run("compares correctly", func(t *testing.T) { + t.Run("compares correctly", func(_ *testing.T) { numAssets := 1 + rng.Intn(rngBase) numParts := 2 + rng.Intn(rngBase) b1 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts), test.WithBalancesInRange(big.NewInt(0), big.NewInt(rngBase))) b2 := test.NewRandomBalances(rng, test.WithNumAssets(numAssets), test.WithNumParts(numParts), test.WithBalancesInRange(big.NewInt(rngBase), big.NewInt(2*rngBase))) - assert.Error(b1.AssertGreaterOrEqual(b2)) - assert.NoError(b2.AssertGreaterOrEqual(b1)) + require.Error(t, b1.AssertGreaterOrEqual(b2)) + require.NoError(t, b2.AssertGreaterOrEqual(b1)) }) } @@ -200,17 +199,17 @@ func testBalancesOperation(t *testing.T, op func(channel.Balances, channel.Balan rng := pkgtest.Prng(t) const rngBase = 10 - t.Run("fails with mismatching number of assets", func(t *testing.T) { + t.Run("fails with mismatching number of assets", func(_ *testing.T) { b1, b2 := randomBalancesWithMismatchingNumAssets(rng, rngBase) assert.Panics(func() { op(b1, b2) }) }) - t.Run("fails with mismatching number of parts", func(t *testing.T) { + t.Run("fails with mismatching number of parts", func(_ *testing.T) { b1, b2 := randomBalancesWithMismatchingNumParts(rng, rngBase) assert.Panics(func() { op(b1, b2) }) }) - t.Run("calculates correctly", func(t *testing.T) { + t.Run("calculates correctly", func(_ *testing.T) { numAssets := 1 + rng.Intn(rngBase) numParts := 2 + rng.Intn(rngBase) @@ -301,7 +300,7 @@ func TestAllocationValidLimits(t *testing.T) { } } - assert.Errorf(t, allocation.Valid(), "[%d] expected error for parameters %v", ti, x) + require.Errorf(t, allocation.Valid(), "[%d] expected error for parameters %v", ti, x) } } @@ -576,10 +575,10 @@ func TestRemoveSubAlloc(t *testing.T) { require.NoError(t, alloc.RemoveSubAlloc(subAlloc), "removing contained element should not fail") - assert.Equal(lenBefore-1, len(alloc.Locked), "length should decrease by 1") + assert.Len(alloc.Locked, lenBefore-1, "length should decrease by 1") _, ok := alloc.SubAlloc(subAlloc.ID) assert.False(ok, "element should not be found after removal") // this could potentially fail because duplicates are currently not removed - assert.Error(alloc.RemoveSubAlloc(subAlloc), "removing not-contained element should fail") + require.Error(t, alloc.RemoveSubAlloc(subAlloc), "removing not-contained element should fail") } diff --git a/channel/app.go b/channel/app.go index 417bd41f1..5b0bae896 100644 --- a/channel/app.go +++ b/channel/app.go @@ -28,7 +28,7 @@ type ( AppID interface { encoding.BinaryMarshaler encoding.BinaryUnmarshaler - Equal(AppID) bool + Equal(appID AppID) bool // Key returns the object key which can be used as a map key. Key() AppIDKey @@ -72,7 +72,7 @@ type ( // ValidInit should perform app-specific checks for a valid initial state. // The framework guarantees to only pass initial states with version == 0, // correct channel ID and valid initial allocation. - ValidInit(*Params, *State) error + ValidInit(params *Params, state *State) error } // An ActionApp is advanced by first collecting actions from the participants @@ -87,7 +87,7 @@ type ( // of the action. It should return a normal error (with attached stacktrace // from pkg/errors) if there was any other runtime error, not related to the // invalidity of the action itself. - ValidAction(*Params, *State, Index, Action) error + ValidAction(params *Params, state *State, idx Index, action Action) error // ApplyAction applies the given actions to the provided channel state and // returns the resulting new state. @@ -96,13 +96,13 @@ type ( // of the action. It should return a normal error (with attached stacktrace // from pkg/errors) if there was any other runtime error, not related to the // invalidity of the action itself. - ApplyActions(*Params, *State, []Action) (*State, error) + ApplyActions(params *Params, state *State, actions []Action) (*State, error) // InitState creates the initial state from the given actions. The actual // State will be created by the machine and only the initial allocation of // funds and app data can be set, as the channel id is specified by the // parameters and version must be 0. - InitState(*Params, []Action) (Allocation, Data, error) + InitState(Params *Params, actions []Action) (Allocation, Data, error) // NewAction returns an instance of action specific to this // application. This has to be defined on an application-level because @@ -130,7 +130,7 @@ type ( // multiple apps are in use, which is why creation happens over a central // Resolve function. This function is intended to resolve app definitions // coming in on the wire. - Resolve(AppID) (App, error) + Resolve(appID AppID) (App, error) } ) @@ -165,7 +165,8 @@ type OptAppDec struct { } // Decode decodes an optional App value. -func (d OptAppDec) Decode(r io.Reader) (err error) { +func (d OptAppDec) Decode(r io.Reader) error { + var err error var hasApp bool if err = perunio.Decode(r, &hasApp); err != nil { return err @@ -201,8 +202,8 @@ type OptAppAndDataDec struct { } // Decode decodes an optional pair of App definition and Data. -func (o OptAppAndDataDec) Decode(r io.Reader) (err error) { - if err = perunio.Decode(r, OptAppDec{App: o.App}); err != nil { +func (o OptAppAndDataDec) Decode(r io.Reader) error { + if err := perunio.Decode(r, OptAppDec{App: o.App}); err != nil { return err } diff --git a/channel/app_test.go b/channel/app_test.go index 65c593263..5d4a03bec 100644 --- a/channel/app_test.go +++ b/channel/app_test.go @@ -17,7 +17,7 @@ package channel_test import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/channel" "perun.network/go-perun/channel/test" pkgtest "polycry.pt/poly-go/test" @@ -29,10 +29,10 @@ func TestAppShouldEqual(t *testing.T) { app2 := test.NewRandomApp(rng) napp := channel.NoApp() - assert.EqualError(t, channel.AppShouldEqual(app1, app2), "different App definitions") - assert.EqualError(t, channel.AppShouldEqual(app2, app1), "different App definitions") - assert.NoError(t, channel.AppShouldEqual(app1, app1)) - assert.EqualError(t, channel.AppShouldEqual(app1, napp), "(non-)nil App definitions") - assert.EqualError(t, channel.AppShouldEqual(napp, app1), "(non-)nil App definitions") - assert.NoError(t, channel.AppShouldEqual(napp, napp)) + require.EqualError(t, channel.AppShouldEqual(app1, app2), "different App definitions") + require.EqualError(t, channel.AppShouldEqual(app2, app1), "different App definitions") + require.NoError(t, channel.AppShouldEqual(app1, app1)) + require.EqualError(t, channel.AppShouldEqual(app1, napp), "(non-)nil App definitions") + require.EqualError(t, channel.AppShouldEqual(napp, app1), "(non-)nil App definitions") + require.NoError(t, channel.AppShouldEqual(napp, napp)) } diff --git a/channel/appregistry_internal_test.go b/channel/appregistry_internal_test.go index 08e74606e..20995e097 100644 --- a/channel/appregistry_internal_test.go +++ b/channel/appregistry_internal_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "polycry.pt/poly-go/test" ) @@ -97,7 +98,7 @@ func testAppRegistryIdentity(t *testing.T, rng *rand.Rand) { func assertIdentity(t *testing.T, expected App) { t.Helper() actual, err := Resolve(expected.Def()) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual.Def().Equal(expected.Def())) } @@ -123,7 +124,7 @@ const appIDLength = 32 type appID [appIDLength]byte -func (id appID) MarshalBinary() (data []byte, err error) { +func (id appID) MarshalBinary() ([]byte, error) { return id[:], nil } diff --git a/channel/backend.go b/channel/backend.go index be57819de..8adbb61a7 100644 --- a/channel/backend.go +++ b/channel/backend.go @@ -30,11 +30,11 @@ type Backend interface { // In order to guarantee non-malleability of States, any parameters omitted // from the CalcID digest need to be signed together with the State in // Sign(). - CalcID(*Params) ID + CalcID(params *Params) ID // Sign signs a channel's State with the given Account. // Returns the signature or an error. - Sign(wallet.Account, *State) (wallet.Sig, error) + Sign(acc wallet.Account, state *State) (wallet.Sig, error) // Verify verifies that the provided signature on the state belongs to the // provided address. diff --git a/channel/funder.go b/channel/funder.go index 1d6775a7f..5cfc41718 100644 --- a/channel/funder.go +++ b/channel/funder.go @@ -34,7 +34,7 @@ type ( // funds from the partially funded channel. In this case, it should // return a FundingTimeoutError containing the index of the peer who // did not fund in time. - Fund(context.Context, FundingReq) error + Fund(ctx context.Context, fundReq FundingReq) error } // A FundingReq bundles all data needed to fund a channel. diff --git a/channel/funder_internal_test.go b/channel/funder_internal_test.go index ee362113d..353e1590e 100644 --- a/channel/funder_internal_test.go +++ b/channel/funder_internal_test.go @@ -34,8 +34,8 @@ func TestAssetFundingError(t *testing.T) { assert.Equal(Index(2), perr.TimedOutPeers[1]) assert.Equal(Index(3), perr.TimedOutPeers[2]) assert.Equal(Index(4), perr.TimedOutPeers[3]) - assert.Equal(4, len(perr.TimedOutPeers)) - assert.Equal(perr.Error(), "Funding Error on asset [42] peers: [1], [2], [3], [4], did not fund channel in time") + assert.Len(perr.TimedOutPeers, 4) + assert.Equal("Funding Error on asset [42] peers: [1], [2], [3], [4], did not fund channel in time", perr.Error()) assert.False(IsAssetFundingError(errors.New("not a asset funding error"))) } @@ -60,8 +60,9 @@ func TestFundingTimeoutError(t *testing.T) { assert.Equal(Index(7531), perr.Errors[2].Asset) assert.Equal(Index(1), perr.Errors[2].TimedOutPeers[0]) assert.Equal(Index(3), perr.Errors[2].TimedOutPeers[1]) - assert.Equal(3, len(perr.Errors)) - assert.Equal(perr.Error(), "Funding Error on asset [42] peers: [1], [2], did not fund channel in time; Funding Error on asset [1337] peers: [0], [2], did not fund channel in time; Funding Error on asset [7531] peers: [1], [3], did not fund channel in time; ") + assert.Len(perr.Errors, 3) + assert.Equal("Funding Error on asset [42] peers: [1], [2], did not fund channel in time; Funding Error on asset [1337] peers: [0], [2], did not fund channel in time; Funding Error on asset [7531] peers: [1], [3], did not fund channel in time; ", + perr.Error()) // test no funding timeout error assert.False(IsFundingTimeoutError(errors.New("no FundingTimeoutError"))) // nil input should not return error diff --git a/channel/machine.go b/channel/machine.go index 0175a2067..c47739c5a 100644 --- a/channel/machine.go +++ b/channel/machine.go @@ -218,21 +218,23 @@ func inPhase(phase Phase, phases []Phase) bool { // The signature is calculated and saved to the staging TX's signature slice // if it was not calculated before. // A call to Sig only makes sense in a signing phase. -func (m *machine) Sig() (sig wallet.Sig, err error) { +func (m *machine) Sig() (wallet.Sig, error) { if !inPhase(m.phase, signingPhases) { return nil, m.phaseErrorf(m.selfTransition(), "can only create own signature in a signing phase") } + var sig wallet.Sig + var err error if m.stagingTX.Sigs[m.idx] == nil { sig, err = Sign(m.acc, m.stagingTX.State) if err != nil { - return + return nil, err } m.stagingTX.Sigs[m.idx] = sig } else { sig = m.stagingTX.Sigs[m.idx] } - return + return sig, err } // State returns the current state. @@ -241,7 +243,7 @@ func (m *machine) State() *State { return m.currentTX.State } -// CurrentTX returns the current current transaction. +// CurrentTX returns the current transaction. func (m *machine) CurrentTX() Transaction { return m.currentTX } diff --git a/channel/mock_app.go b/channel/mock_app.go index b8dc4f6be..770f83347 100644 --- a/channel/mock_app.go +++ b/channel/mock_app.go @@ -113,7 +113,7 @@ func (a MockApp) NewData() Data { } // ValidTransition checks the transition for validity. -func (a MockApp) ValidTransition(params *Params, from, to *State, actor Index) error { +func (a MockApp) ValidTransition(_ *Params, from, _ *State, _ Index) error { op, ok := from.Data.(*MockOp) if !ok { return fmt.Errorf("wrong data type: expected *MockOp, got %T", from.Data) @@ -122,7 +122,7 @@ func (a MockApp) ValidTransition(params *Params, from, to *State, actor Index) e } // ValidInit checks the initial state for validity. -func (a MockApp) ValidInit(params *Params, state *State) error { +func (a MockApp) ValidInit(_ *Params, state *State) error { op, ok := state.Data.(*MockOp) if !ok { return fmt.Errorf("wrong data type: expected *MockOp, got %T", state.Data) @@ -131,7 +131,7 @@ func (a MockApp) ValidInit(params *Params, state *State) error { } // ValidAction checks the action for validity. -func (a MockApp) ValidAction(params *Params, state *State, part Index, act Action) error { +func (a MockApp) ValidAction(_ *Params, _ *State, _ Index, act Action) error { op, ok := act.(*MockOp) if !ok { return fmt.Errorf("wrong data type: expected *MockOp, got %T", act) @@ -140,7 +140,7 @@ func (a MockApp) ValidAction(params *Params, state *State, part Index, act Actio } // ApplyActions applies the actions unto a copy of state and returns the result or an error. -func (a MockApp) ApplyActions(params *Params, state *State, acts []Action) (*State, error) { +func (a MockApp) ApplyActions(_ *Params, state *State, acts []Action) (*State, error) { ret := state.Clone() ret.Version++ @@ -153,7 +153,7 @@ func (a MockApp) ApplyActions(params *Params, state *State, acts []Action) (*Sta } // InitState Checks for the validity of the passed arguments as initial state. -func (a MockApp) InitState(params *Params, rawActs []Action) (Allocation, Data, error) { +func (a MockApp) InitState(_ *Params, rawActs []Action) (Allocation, Data, error) { op, ok := rawActs[0].(*MockOp) if !ok { return Allocation{}, nil, fmt.Errorf("wrong data type: expected *MockOp, got %T", rawActs[0]) diff --git a/channel/mock_app_internal_test.go b/channel/mock_app_internal_test.go index c0f4b1c00..f3bcc81eb 100644 --- a/channel/mock_app_internal_test.go +++ b/channel/mock_app_internal_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" wiretest "perun.network/go-perun/wire/test" pkgtest "polycry.pt/poly-go/test" @@ -54,8 +55,6 @@ func TestMockApp(t *testing.T) { t.Run("CloneTest", func(t *testing.T) { op := NewMockOp(OpValid) op2 := op.Clone() - // Dont use Equal here since it compares the values and not addresses - assert.False(t, op == op2, "Clone should return a different address") assert.Equal(t, op, op2, "Clone should return the same value") }) } @@ -70,19 +69,19 @@ func MockStateAppTest(t *testing.T, app MockApp) { t.Run("ValidTransition", func(t *testing.T) { // ValidTransition only checks the first state. - assert.NoError(t, app.ValidTransition(nil, stateValid, nil, 0)) - assert.Error(t, app.ValidTransition(nil, stateErr, nil, 0)) + require.NoError(t, app.ValidTransition(nil, stateValid, nil, 0)) + require.Error(t, app.ValidTransition(nil, stateErr, nil, 0)) assert.True(t, IsStateTransitionError(app.ValidTransition(nil, stateTransErr, nil, 0))) assert.True(t, IsActionError(app.ValidTransition(nil, stateActErr, nil, 0))) - assert.Panics(t, func() { assert.NoError(t, app.ValidTransition(nil, statePanic, nil, 0)) }) + assert.Panics(t, func() { require.NoError(t, app.ValidTransition(nil, statePanic, nil, 0)) }) }) t.Run("ValidInit", func(t *testing.T) { - assert.NoError(t, app.ValidInit(nil, stateValid)) - assert.Error(t, app.ValidInit(nil, stateErr)) + require.NoError(t, app.ValidInit(nil, stateValid)) + require.Error(t, app.ValidInit(nil, stateErr)) assert.True(t, IsStateTransitionError(app.ValidInit(nil, stateTransErr))) assert.True(t, IsActionError(app.ValidInit(nil, stateActErr))) - assert.Panics(t, func() { assert.NoError(t, app.ValidInit(nil, statePanic)) }) + assert.Panics(t, func() { require.NoError(t, app.ValidInit(nil, statePanic)) }) }) } @@ -99,10 +98,10 @@ func MockActionAppTest(t *testing.T, app MockApp) { t.Run("InitState", func(t *testing.T) { _, _, err := app.InitState(nil, []Action{actValid}) // Sadly we can not check Allocation.valid() here, since it is private. - assert.NoError(t, err) + require.NoError(t, err) _, _, err = app.InitState(nil, []Action{actErr}) - assert.Error(t, err) + require.Error(t, err) _, _, err = app.InitState(nil, []Action{actTransErr}) assert.True(t, IsStateTransitionError(err)) @@ -114,8 +113,8 @@ func MockActionAppTest(t *testing.T, app MockApp) { }) t.Run("ValidAction", func(t *testing.T) { - assert.NoError(t, app.ValidAction(nil, nil, 0, actValid)) - assert.Error(t, app.ValidAction(nil, nil, 0, actErr)) + require.NoError(t, app.ValidAction(nil, nil, 0, actValid)) + require.Error(t, app.ValidAction(nil, nil, 0, actErr)) assert.True(t, IsStateTransitionError(app.ValidAction(nil, nil, 0, actTransErr))) assert.True(t, IsActionError(app.ValidAction(nil, nil, 0, actActErr))) assert.Panics(t, func() { app.ValidAction(nil, nil, 0, actPanic) }) //nolint:errcheck @@ -125,10 +124,10 @@ func MockActionAppTest(t *testing.T, app MockApp) { // ApplyActions increments the Version counter, so we cant pass nil as state. retState, err := app.ApplyActions(nil, state, []Action{actValid}) assert.Equal(t, retState.Version, state.Version+1) - assert.NoError(t, err) + require.NoError(t, err) _, err = app.ApplyActions(nil, state, []Action{actErr}) - assert.Error(t, err) + require.Error(t, err) _, err = app.ApplyActions(nil, state, []Action{actTransErr}) assert.True(t, IsStateTransitionError(err)) diff --git a/channel/persistence/keyvalue/cache.go b/channel/persistence/keyvalue/cache.go index af667f4a4..6fbb875d1 100644 --- a/channel/persistence/keyvalue/cache.go +++ b/channel/persistence/keyvalue/cache.go @@ -31,6 +31,7 @@ func newChannelCache() *channelCache { } // channelCache contains all channels. +// //nolint:unused type channelCache struct { mutex stdsync.RWMutex diff --git a/channel/persistence/keyvalue/persister.go b/channel/persistence/keyvalue/persister.go index 6f606cce6..29885f9b7 100644 --- a/channel/persistence/keyvalue/persister.go +++ b/channel/persistence/keyvalue/persister.go @@ -77,7 +77,7 @@ func sigKey(idx, numParts int) string { } // ChannelRemoved deletes a channel from the database. -func (pr *PersistRestorer) ChannelRemoved(ctx context.Context, id channel.ID) error { +func (pr *PersistRestorer) ChannelRemoved(_ context.Context, id channel.ID) error { db := pr.channelDB(id).NewBatch() peerdb := sortedkv.NewTable(pr.db, prefix.PeerDB).NewBatch() // All keys a channel has. @@ -118,7 +118,7 @@ func (pr *PersistRestorer) ChannelRemoved(ctx context.Context, id channel.ID) er // the db. func (pr *PersistRestorer) paramsForChan(id channel.ID) (channel.Params, error) { params := channel.Params{} - b, err := pr.channelDB(id).GetBytes("params") + b, err := pr.channelDB(id).GetBytes("params") //nolint:forbidigo if err != nil { return params, errors.WithMessage(err, "unable to retrieve params from db") } diff --git a/channel/persistence/keyvalue/persistrestorer_internal_test.go b/channel/persistence/keyvalue/persistrestorer_internal_test.go index bafd808c0..3fcf9c878 100644 --- a/channel/persistence/keyvalue/persistrestorer_internal_test.go +++ b/channel/persistence/keyvalue/persistrestorer_internal_test.go @@ -16,7 +16,7 @@ package keyvalue import ( "context" - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/assert" @@ -31,7 +31,7 @@ import ( ) func TestPersistRestorer_Generic(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "perun-test-kvpersistrestorer-db-*") + tmpdir, err := os.MkdirTemp("", "perun-test-kvpersistrestorer-db-*") require.NoError(t, err) lvldb, err := leveldb.LoadDatabase(tmpdir) require.NoError(t, err) diff --git a/channel/persistence/keyvalue/restorer.go b/channel/persistence/keyvalue/restorer.go index 6dfea22cd..6bed2c360 100644 --- a/channel/persistence/keyvalue/restorer.go +++ b/channel/persistence/keyvalue/restorer.go @@ -41,7 +41,7 @@ type ChannelIterator struct { } // ActivePeers returns a list of all peers with which a channel is persisted. -func (pr *PersistRestorer) ActivePeers(ctx context.Context) ([]wire.Address, error) { +func (pr *PersistRestorer) ActivePeers(_ context.Context) ([]wire.Address, error) { it := sortedkv.NewTable(pr.db, prefix.PeerDB).NewIterator() peermap := make(map[wire.AddrKey]wire.Address) @@ -63,13 +63,15 @@ func (pr *PersistRestorer) ActivePeers(ctx context.Context) ([]wire.Address, err // channelPeers returns a slice of peer addresses for a given channel id from // the db of PersistRestorer. +// +//nolint:forbidigo func (pr *PersistRestorer) channelPeers(id channel.ID) ([]wire.Address, error) { var ps wire.AddressesWithLen peers, err := pr.channelDB(id).Get(prefix.Peers) if err != nil { return nil, errors.WithMessage(err, "unable to get peerlist from db") } - return []wire.Address(ps), errors.WithMessage(perunio.Decode(bytes.NewBuffer([]byte(peers)), &ps), + return []wire.Address(ps), errors.WithMessage(perunio.Decode(bytes.NewReader([]byte(peers)), &ps), "decoding peerlist") } diff --git a/channel/persistence/persistence.go b/channel/persistence/persistence.go index 30705dfe2..f79e0a8e3 100644 --- a/channel/persistence/persistence.go +++ b/channel/persistence/persistence.go @@ -46,20 +46,20 @@ type ( // state. It may already contain one valid signature, either by a remote // peer or us locally. Hence, this only needs to persist a channel's staged // state, all its currently known signatures and the phase. - Staged(context.Context, channel.Source) error + Staged(ctx context.Context, source channel.Source) error // SigAdded is called when a new signature is added to the current staging // state. Only the signature for the given index needs to be persisted. - SigAdded(context.Context, channel.Source, channel.Index) error + SigAdded(ctx context.Context, source channel.Source, idx channel.Index) error // Enabled is called when the current state is updated to the staging state. // The old current state may be discarded. The current state and phase // should be persisted. - Enabled(context.Context, channel.Source) error + Enabled(ctx context.Context, source channel.Source) error // PhaseChanged is called when a phase change occurred that did not change // the current or staging transaction. Only the phase needs to be persisted. - PhaseChanged(context.Context, channel.Source) error + PhaseChanged(ctx context.Context, source channel.Source) error // Close is called by the client when it shuts down. No more persistence // requests will be made after this call and the Persister should free up @@ -72,14 +72,14 @@ type ( Restorer interface { // ActivePeers should return a list of all peers with which any channel is // persisted. - ActivePeers(context.Context) ([]wire.Address, error) + ActivePeers(ctx context.Context) ([]wire.Address, error) // RestorePeer should return an iterator over all persisted channels which // the given peer is a part of. - RestorePeer(wire.Address) (ChannelIterator, error) + RestorePeer(wireAddr wire.Address) (ChannelIterator, error) // RestoreChannel should return the channel with the requested ID. - RestoreChannel(context.Context, channel.ID) (*Channel, error) + RestoreChannel(ctx context.Context, channelID channel.ID) (*Channel, error) } // PersistRestorer is a Persister and Restorer on the same data source and @@ -95,7 +95,7 @@ type ( ChannelIterator interface { // Next should restore the next persisted channel. If no channel was found, // or the context times out, it should return false. - Next(context.Context) bool + Next(ctx context.Context) bool // Channel should return the latest channel data that was restored via Next. // It is guaranteed by the framework to only be called after Next returned diff --git a/channel/persistence/statemachine.go b/channel/persistence/statemachine.go index 148e9140b..b9530c2dd 100644 --- a/channel/persistence/statemachine.go +++ b/channel/persistence/statemachine.go @@ -139,8 +139,8 @@ func (m StateMachine) ForceUpdate( // Sig calls Sig on the channel.StateMachine and then persists the added // signature. -func (m StateMachine) Sig(ctx context.Context) (sig wallet.Sig, err error) { - sig, err = m.StateMachine.Sig() +func (m StateMachine) Sig(ctx context.Context) (wallet.Sig, error) { + sig, err := m.StateMachine.Sig() if err != nil { return sig, err } diff --git a/channel/persistence/test/channel.go b/channel/persistence/test/channel.go index 9cd8857dd..cc3c2734b 100644 --- a/channel/persistence/test/channel.go +++ b/channel/persistence/test/channel.go @@ -51,11 +51,11 @@ func NewRandomChannel( ctx context.Context, t require.TestingT, pr persistence.PersistRestorer, - user channel.Index, + _ channel.Index, peers []wire.Address, parent *Channel, rng *rand.Rand, -) (c *Channel) { +) *Channel { accs, parts := wtest.NewRandomAccounts(rng, len(peers)) params := ctest.NewRandomParams(rng, ctest.WithParts(parts...)) csm, err := channel.NewStateMachine(accs[0], *params) @@ -68,7 +68,7 @@ func NewRandomChannel( } sm := persistence.FromStateMachine(csm, pr) - c = &Channel{ + c := &Channel{ accounts: accs, peers: peers, StateMachine: &sm, diff --git a/channel/persistence/test/peerchans.go b/channel/persistence/test/peerchans.go index 5861340ff..90ed45b1c 100644 --- a/channel/persistence/test/peerchans.go +++ b/channel/persistence/test/peerchans.go @@ -85,7 +85,7 @@ func peerKey(a wire.Address) string { func peerFromKey(s string) wire.Address { p := wire.NewAddress() - err := perunio.Decode(bytes.NewBuffer([]byte(s)), p) + err := perunio.Decode(bytes.NewReader([]byte(s)), p) if err != nil { panic("error decoding peer key: " + err.Error()) } diff --git a/channel/persistence/test/persistrestorertest.go b/channel/persistence/test/persistrestorertest.go index bc5552930..65c24631d 100644 --- a/channel/persistence/test/persistrestorertest.go +++ b/channel/persistence/test/persistrestorertest.go @@ -76,6 +76,8 @@ func (c *Client) NewChannel(t require.TestingT, p wire.Address, parent *Channel) // fresh and not contain any previous channels. The parameter numChans controls // the channels created per wire. numPeers is the number of separate peers to // generate. +// +//nolint:testifylint func GenericPersistRestorerTest( ctx context.Context, t *testing.T, diff --git a/channel/statemachine.go b/channel/statemachine.go index 80a94c605..22fcf240d 100644 --- a/channel/statemachine.go +++ b/channel/statemachine.go @@ -100,7 +100,7 @@ func (m *StateMachine) Update(stagingState *State, actor Index) error { } // ForceUpdate makes the provided state the staging state. -func (m *StateMachine) ForceUpdate(stagingState *State, actor Index) error { +func (m *StateMachine) ForceUpdate(stagingState *State, _ Index) error { m.setStaging(Signing, stagingState) return nil } @@ -130,11 +130,12 @@ func (m *StateMachine) CheckUpdate( // every action is checked as being a valid action by the application definition // and the resulting state by applying all actions to the old state is by // definition a valid new state. -func (m *StateMachine) validTransition(to *State, actor Index) (err error) { +func (m *StateMachine) validTransition(to *State, actor Index) error { + var err error if actor >= m.N() { return errors.New("actor index is out of range") } - if err := m.machine.ValidTransition(to); err != nil { + if err = m.machine.ValidTransition(to); err != nil { return err } diff --git a/channel/test/app_randomizer.go b/channel/test/app_randomizer.go index ae7442b20..44aafd1ff 100644 --- a/channel/test/app_randomizer.go +++ b/channel/test/app_randomizer.go @@ -23,8 +23,8 @@ import ( // The AppRandomizer interface provides functionality for creating random // data and apps which is useful for testing. type AppRandomizer interface { - NewRandomApp(*rand.Rand) channel.App - NewRandomData(*rand.Rand) channel.Data + NewRandomApp(rng *rand.Rand) channel.App + NewRandomData(rng *rand.Rand) channel.Data } var appRandomizer AppRandomizer = NewMockAppRandomizer() diff --git a/channel/test/app_randomizer_internal_test.go b/channel/test/app_randomizer_internal_test.go index 3416841a2..67e28d253 100644 --- a/channel/test/app_randomizer_internal_test.go +++ b/channel/test/app_randomizer_internal_test.go @@ -32,11 +32,11 @@ func TestAppRandomizerSet(t *testing.T) { assert.NotPanics(t, func() { SetAppRandomizer(NewMockAppRandomizer()) }, "first SetAppRandomizer() should work") assert.True(t, isAppRandomizerSet, "isAppRandomizerSet should be true") assert.NotNil(t, appRandomizer, "appRandomizer should not be nil") - assert.False(t, old == appRandomizer, "appRandomizer should have changed") + assert.NotEqual(t, old, appRandomizer, "appRandomizer should have changed") old = appRandomizer assert.Panics(t, func() { SetAppRandomizer(NewMockAppRandomizer()) }, "second SetAppRandomizer() should panic") assert.True(t, isAppRandomizerSet, "isAppRandomizerSet should be true") assert.NotNil(t, appRandomizer, "appRandomizer should not be nil") - assert.True(t, old == appRandomizer, "appRandomizer should not have changed") + assert.Equal(t, old, appRandomizer, "appRandomizer should not have changed") } diff --git a/channel/test/backend.go b/channel/test/backend.go index e109df926..662c03e09 100644 --- a/channel/test/backend.go +++ b/channel/test/backend.go @@ -108,7 +108,7 @@ func genericChannelIDTest(t *testing.T, s *Setup) { func genericSignTest(t *testing.T, s *Setup) { t.Helper() _, err := channel.Sign(s.Account, s.State) - assert.NoError(t, err, "Sign should not return an error") + require.NoError(t, err, "Sign should not return an error") } func genericVerifyTest(t *testing.T, s *Setup, opts ...GenericTestOption) { @@ -119,27 +119,28 @@ func genericVerifyTest(t *testing.T, s *Setup, opts ...GenericTestOption) { require.NoError(t, err, "Sign should not return an error") ok, err := channel.Verify(addr, s.State, sig) - assert.NoError(t, err, "Verify should not return an error") + require.NoError(t, err, "Verify should not return an error") assert.True(t, ok, "Verify should return true") for i, _modState := range buildModifiedStates(s.State, s.State2, append(opts, IgnoreApp)...) { modState := _modState ok, err = channel.Verify(addr, &modState, sig) assert.Falsef(t, ok, "Verify should return false: index %d", i) - assert.NoError(t, err, "Verify should not return an error") + require.NoError(t, err, "Verify should not return an error") } // Different address and same state and params for i := 0; i < 10; i++ { ok, err := channel.Verify(s.RandomAddress(), s.State, sig) - assert.NoError(t, err, "Verify should not return an error") + require.NoError(t, err, "Verify should not return an error") assert.False(t, ok, "Verify should return false") } } // buildModifiedParams returns a slice of Params that are different from `p1` assuming that `p2` differs in // every member from `p1`. -func buildModifiedParams(p1, p2 *channel.Params, s *Setup) (ret []channel.Params) { +func buildModifiedParams(p1, p2 *channel.Params, s *Setup) []channel.Params { + var ret []channel.Params // Modify params { // Modify complete Params @@ -197,7 +198,8 @@ func appendModParams(a []channel.Params, modParams channel.Params) []channel.Par // every member from `s1`. // `modifyApp` indicates whether the app should also be changed or not. In some cases (signature) it is desirable // not to modify it. -func buildModifiedStates(s1, s2 *channel.State, _opts ...GenericTestOption) (ret []channel.State) { +func buildModifiedStates(s1, s2 *channel.State, _opts ...GenericTestOption) []channel.State { + var ret []channel.State opts := mergeTestOpts(_opts...) // Modify state { @@ -361,8 +363,8 @@ func ensureBalanceVectorLength(bals []channel.Bal, l int) []channel.Bal { // GenericStateEqualTest tests the State.Equal function. func GenericStateEqualTest(t *testing.T, s1, s2 *channel.State, opts ...GenericTestOption) { t.Helper() - assert.NoError(t, s1.Equal(s1)) //nolint:gocritic - assert.NoError(t, s2.Equal(s2)) //nolint:gocritic + require.NoError(t, s1.Equal(s1)) //nolint:gocritic + require.NoError(t, s2.Equal(s2)) //nolint:gocritic for _, differentState := range buildModifiedStates(s1, s2, opts...) { assert.Error(t, differentState.Equal(s1)) diff --git a/channel/test/randomizer.go b/channel/test/randomizer.go index f1303f23e..0db92fa86 100644 --- a/channel/test/randomizer.go +++ b/channel/test/randomizer.go @@ -30,7 +30,7 @@ import ( // The Randomizer interface provides the ability to create random assets. // This is useful for testing. type Randomizer interface { - NewRandomAsset(*rand.Rand) channel.Asset + NewRandomAsset(rng *rand.Rand) channel.Asset } var randomizer Randomizer @@ -115,8 +115,8 @@ func NewRandomLockedIDs(rng *rand.Rand, opts ...RandomOpt) []channel.ID { return ids } - numLockedIds := opt.NumLocked(rng) - ids := make([]channel.ID, numLockedIds) + numLockedIDs := opt.NumLocked(rng) + ids := make([]channel.ID, numLockedIDs) for i := range ids { rng.Read(ids[i][:]) } @@ -139,13 +139,13 @@ func NewRandomSubAlloc(rng *rand.Rand, opts ...RandomOpt) *channel.SubAlloc { // NewRandomParamsAndState generates a new random `channel.Params` and `channel.State`. // Options: all from `NewRandomParams` and `NewRandomState`. -func NewRandomParamsAndState(rng *rand.Rand, opts ...RandomOpt) (params *channel.Params, state *channel.State) { +func NewRandomParamsAndState(rng *rand.Rand, opts ...RandomOpt) (*channel.Params, *channel.State) { opt := mergeRandomOpts(opts...) - params = NewRandomParams(rng, opt) - state = NewRandomState(rng, WithParams(params), opt) + params := NewRandomParams(rng, opt) + state := NewRandomState(rng, WithParams(params), opt) - return + return params, state } // NewRandomParams generates a new random `channel.Params`. @@ -182,7 +182,7 @@ func NewRandomParams(rng *rand.Rand, opts ...RandomOpt) *channel.Params { // NewRandomState generates a new random `channel.State`. // Options: `WithState`, `WithVersion`, `WithIsFinal` // and all from `NewRandomChannelID`, `NewRandomApp`, `NewRandomAllocation` and `NewRandomData`. -func NewRandomState(rng *rand.Rand, opts ...RandomOpt) (state *channel.State) { +func NewRandomState(rng *rand.Rand, opts ...RandomOpt) *channel.State { opt := mergeRandomOpts(opts...) if state := opt.State(); state != nil { return state @@ -195,7 +195,7 @@ func NewRandomState(rng *rand.Rand, opts ...RandomOpt) (state *channel.State) { data := NewRandomData(rng, opt) isFinal := opt.IsFinal(rng) - state = &channel.State{ + state := &channel.State{ ID: id, Version: version, App: app, @@ -204,13 +204,14 @@ func NewRandomState(rng *rand.Rand, opts ...RandomOpt) (state *channel.State) { IsFinal: isFinal, } updateOpts(opts, WithState(state)) - return + return state } // NewRandomChannelID generates a new random `channel.ID`. // Options: `WithID`. -func NewRandomChannelID(rng *rand.Rand, opts ...RandomOpt) (id channel.ID) { +func NewRandomChannelID(rng *rand.Rand, opts ...RandomOpt) channel.ID { opt := mergeRandomOpts(opts...) + var id channel.ID if id, valid := opt.ID(); valid { return id @@ -219,34 +220,34 @@ func NewRandomChannelID(rng *rand.Rand, opts ...RandomOpt) (id channel.ID) { if _, err := rng.Read(id[:]); err != nil { log.Panic("could not read from rng") } - return + return id } // NewRandomChannelIDs generates a list of random channel IDs. -func NewRandomChannelIDs(rng *rand.Rand, n int) (ids []channel.ID) { - ids = make([]channel.ID, n) +func NewRandomChannelIDs(rng *rand.Rand, n int) []channel.ID { + ids := make([]channel.ID, n) for i := range ids { ids[i] = NewRandomChannelID(rng) } - return + return ids } // NewRandomIndexMap generates a random index map. -func NewRandomIndexMap(rng *rand.Rand, numParts int, numPartsParent int) (m []channel.Index) { - m = make([]channel.Index, numParts) +func NewRandomIndexMap(rng *rand.Rand, numParts int, numPartsParent int) []channel.Index { + m := make([]channel.Index, numParts) for i := range m { m[i] = channel.Index(rng.Intn(numPartsParent)) } - return + return m } // NewRandomIndexMaps generates a list of random index maps. -func NewRandomIndexMaps(rng *rand.Rand, numParts int, numPartsParent int) (maps [][]channel.Index) { - maps = make([][]channel.Index, numParts) +func NewRandomIndexMaps(rng *rand.Rand, numParts int, numPartsParent int) [][]channel.Index { + maps := make([][]channel.Index, numParts) for i := range maps { maps[i] = NewRandomIndexMap(rng, numParts, numPartsParent) } - return + return maps } // NewRandomBal generates a new random `channel.Bal`. diff --git a/channel/test/randomopts.go b/channel/test/randomopts.go index ba4d348e3..dfe01a0d9 100644 --- a/channel/test/randomopts.go +++ b/channel/test/randomopts.go @@ -300,9 +300,9 @@ func (o RandomOpt) Balances() channel.Balances { return o["balances"].([][]channel.Bal) } -// BalancesRange returns the `BalancesRange` value of the `RandomOpt`. +// BalancesRange returns the `BalancesRange` (min, max) value of the `RandomOpt`. // If not present, returns nil,nil. -func (o RandomOpt) BalancesRange() (min, max channel.Bal) { +func (o RandomOpt) BalancesRange() (channel.Bal, channel.Bal) { if _, ok := o["balanceRange"]; !ok { return nil, nil } @@ -321,7 +321,7 @@ func (o RandomOpt) ChallengeDuration(rng *rand.Rand) uint64 { // ID returns the `ID` value of the `RandomOpt`. // If not present, returns `false` as second argument. -func (o RandomOpt) ID() (id channel.ID, valid bool) { +func (o RandomOpt) ID() (channel.ID, bool) { if _, ok := o["id"]; !ok { return channel.ID{}, false } @@ -348,7 +348,7 @@ func (o RandomOpt) IsFinal(rng *rand.Rand) bool { // Locked returns the `Locked` value of the `RandomOpt`. // If not present, returns `false` as second argument. -func (o RandomOpt) Locked() (locked []channel.SubAlloc, valid bool) { +func (o RandomOpt) Locked() ([]channel.SubAlloc, bool) { if _, ok := o["locked"]; !ok { return nil, false } @@ -375,7 +375,7 @@ func (o RandomOpt) LockedID(rng *rand.Rand) channel.ID { // LockedIDs returns the `LockedIDs` value of the `RandomOpt`. // If not present, returns nil. -func (o RandomOpt) LockedIDs(rng *rand.Rand) (ids []channel.ID) { +func (o RandomOpt) LockedIDs(_ *rand.Rand) []channel.ID { if _, ok := o["lockedIds"]; !ok { return nil } @@ -434,7 +434,7 @@ func (o RandomOpt) NumAssets(rng *rand.Rand) int { // NumLocked returns the `NumLocked` value of the `RandomOpt`. // If not present, returns 0. -func (o RandomOpt) NumLocked(rng *rand.Rand) int { +func (o RandomOpt) NumLocked(_ *rand.Rand) int { if _, ok := o["numLocked"]; !ok { // We return 0 here because when no `WithLocked` or `WithNumLocked` // are given, 0 is assumed. diff --git a/client/adjudicate.go b/client/adjudicate.go index 362a8f294..7adf2368f 100644 --- a/client/adjudicate.go +++ b/client/adjudicate.go @@ -28,7 +28,7 @@ import ( // AdjudicatorEventHandler represents an interface for handling adjudicator events. type AdjudicatorEventHandler interface { - HandleAdjudicatorEvent(channel.AdjudicatorEvent) + HandleAdjudicatorEvent(adjEvent channel.AdjudicatorEvent) } // Watch registers the channel with the watcher, which watches for channel @@ -114,7 +114,8 @@ func (c *Channel) handleEvents(eventsSub watcher.AdjudicatorSub, h AdjudicatorEv } } -func (c *Channel) setMachinePhase(ctx context.Context, e channel.AdjudicatorEvent) (err error) { +func (c *Channel) setMachinePhase(ctx context.Context, e channel.AdjudicatorEvent) error { + var err error // Lock machine if !c.machMtx.TryLockCtx(ctx) { return errors.WithMessage(ctx.Err(), "locking machine") @@ -132,7 +133,7 @@ func (c *Channel) setMachinePhase(ctx context.Context, e channel.AdjudicatorEven c.Log().Panic("unsupported event type") } - return + return err } // registerDispute registers a dispute for the channel and all its relatives. @@ -242,7 +243,7 @@ func (c *Channel) ForceUpdate(ctx context.Context, updater func(*channel.State)) // to be mined. // Returns ChainNotReachableError if the connection to the blockchain network // fails when sending a transaction to / reading from the blockchain. -func (c *Channel) Settle(ctx context.Context, secondary bool) (err error) { +func (c *Channel) Settle(ctx context.Context, secondary bool) error { if !c.State().IsFinal { err := c.ensureRegistered(ctx) if err != nil { @@ -285,16 +286,16 @@ func (c *Channel) Settle(ctx context.Context, secondary bool) (err error) { } // Decrement account usage. - if err = c.applyRecursive(func(c *Channel) (err error) { + if err = c.applyRecursive(func(c *Channel) error { // Skip if we are not a participant, e.g., if this is a virtual channel and we are the hub. if c.IsVirtualChannel() { ourID := c.parent.Peers()[c.parent.Idx()] if !c.hasParticipant(ourID) { - return + return nil } } c.wallet.DecrementUsage(c.machine.Account().Address()) - return + return nil }); err != nil { return errors.WithMessage(err, "decrementing account usage") } @@ -358,53 +359,53 @@ func (a mutexList) Unlock() { // tryLockRecursive tries to lock the channel and all of its sub-channels. // It returns a list of all the mutexes that have been locked. -func (c *Channel) tryLockRecursive(ctx context.Context) (l mutexList, err error) { - err = c.applyRecursive(func(c *Channel) error { +func (c *Channel) tryLockRecursive(ctx context.Context) (mutexList, error) { + var l mutexList + err := c.applyRecursive(func(c *Channel) error { if !c.machMtx.TryLockCtx(ctx) { return errors.Errorf("locking machine mutex in time: %v", ctx.Err()) } l = append(l, &c.machMtx) return nil }) - return + return l, err } // applyToSubChannelsRecursive applies the function to all sub-channels recursively. -func (c *Channel) applyToSubChannelsRecursive(f func(*Channel) error) (err error) { +func (c *Channel) applyToSubChannelsRecursive(f func(*Channel) error) error { for _, subAlloc := range c.state().Locked { subID := subAlloc.ID var subCh *Channel - subCh, err = c.client.Channel(subID) + subCh, err := c.client.Channel(subID) if err != nil { - err = errors.WithMessagef(err, "getting sub-channel: %v", subID) - return + return errors.WithMessagef(err, "getting sub-channel: %v", subID) } err = f(subCh) if err != nil { - return + return err } err = subCh.applyToSubChannelsRecursive(f) if err != nil { - return + return err } } - return + return nil } // applyRecursive applies the function to the channel and its sub-channels recursively. -func (c *Channel) applyRecursive(f func(*Channel) error) (err error) { - err = f(c) +func (c *Channel) applyRecursive(f func(*Channel) error) error { + err := f(c) if err != nil { return err } err = c.applyToSubChannelsRecursive(f) - return + return err } // setRegisteringRecursive sets the machine phase of the channel and all of its sub-channels to `Registering`. // Assumes that the channel machine has been locked. -func (c *Channel) setRegisteringRecursive(ctx context.Context) (err error) { +func (c *Channel) setRegisteringRecursive(ctx context.Context) error { return c.applyRecursive(func(c *Channel) error { return c.machine.SetRegistering(ctx) }) @@ -412,7 +413,7 @@ func (c *Channel) setRegisteringRecursive(ctx context.Context) (err error) { // setRegisteredRecursive sets the machine phase of the channel and all of its sub-channels to `Registered`. // Assumes that the channel machine has been locked. -func (c *Channel) setRegisteredRecursive(ctx context.Context) (err error) { +func (c *Channel) setRegisteredRecursive(ctx context.Context) error { return c.applyRecursive(func(c *Channel) error { return c.machine.SetRegistered(ctx) }) @@ -420,9 +421,9 @@ func (c *Channel) setRegisteredRecursive(ctx context.Context) (err error) { // gatherSubChannelStates gathers the state of all sub-channels recursively. // Assumes sub-channels are locked. -func (c *Channel) gatherSubChannelStates() (states []channel.SignedState, err error) { - states = []channel.SignedState{} - err = c.applyToSubChannelsRecursive(func(c *Channel) error { +func (c *Channel) gatherSubChannelStates() ([]channel.SignedState, error) { + states := []channel.SignedState{} + err := c.applyToSubChannelsRecursive(func(c *Channel) error { states = append(states, channel.SignedState{ Params: c.Params(), State: c.machine.CurrentTX().State, @@ -430,18 +431,18 @@ func (c *Channel) gatherSubChannelStates() (states []channel.SignedState, err er }) return nil }) - return + return states, err } // subChannelStateMap gathers the state of all sub-channels recursively. // Assumes sub-channels are locked. -func (c *Channel) subChannelStateMap() (states channel.StateMap, err error) { - states = channel.MakeStateMap() - err = c.applyToSubChannelsRecursive(func(c *Channel) error { +func (c *Channel) subChannelStateMap() (channel.StateMap, error) { + states := channel.MakeStateMap() + err := c.applyToSubChannelsRecursive(func(c *Channel) error { states[c.ID()] = c.state() return nil }) - return + return states, err } // ensureRegistered ensures that the channel is registered. diff --git a/client/chanregistry.go b/client/chanregistry.go index 8ffa4d985..5437a9873 100644 --- a/client/chanregistry.go +++ b/client/chanregistry.go @@ -90,17 +90,18 @@ func (r *chanRegistry) Channel(id channel.ID) (*Channel, bool) { // Delete deletes a channel from the registry. // If the channel did not exist, does nothing. Returns whether the channel // existed. -func (r *chanRegistry) Delete(id channel.ID) (deleted bool) { +func (r *chanRegistry) Delete(id channel.ID) bool { r.mutex.Lock() defer r.mutex.Unlock() - + var deleted bool if _, deleted = r.values[id]; deleted { delete(r.values, id) } - return + return deleted } -func (r *chanRegistry) CloseAll() (err error) { +func (r *chanRegistry) CloseAll() error { + var err error r.mutex.Lock() values := r.values r.values = make(map[channel.ID]*Channel) diff --git a/client/client.go b/client/client.go index 0fc28ee82..7ea13bf20 100644 --- a/client/client.go +++ b/client/client.go @@ -74,7 +74,7 @@ func New( adjudicator channel.Adjudicator, wallet wallet.Wallet, watcher watcher.Watcher, -) (c *Client, err error) { +) (*Client, error) { if address == nil { log.Panic("address must not be nil") } @@ -97,7 +97,7 @@ func New( return nil, errors.WithMessage(err, "setting up client connection") } - c = &Client{ + c := &Client{ address: address, conn: conn, channels: makeChanRegistry(), diff --git a/client/client_persistence_test.go b/client/client_persistence_test.go index d04bc373b..813f69fce 100644 --- a/client/client_persistence_test.go +++ b/client/client_persistence_test.go @@ -27,13 +27,13 @@ func TestPersistencePetraRobert(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), twoPartyTestTimeout) defer cancel() - runAliceBobTest(ctx, t, func(rng *rand.Rand) (setups []ctest.RoleSetup, roles [2]ctest.Executer) { - setups = NewSetupsPersistence(t, rng, []string{"Petra", "Robert"}) - roles = [2]ctest.Executer{ + runAliceBobTest(ctx, t, func(rng *rand.Rand) ([]ctest.RoleSetup, [2]ctest.Executer) { + setups := NewSetupsPersistence(t, rng, []string{"Petra", "Robert"}) + roles := [2]ctest.Executer{ ctest.NewPetra(t, setups[0]), ctest.NewRobert(t, setups[1]), } - return + return setups, roles }) } diff --git a/client/client_test.go b/client/client_test.go index 1e89d0153..b203f9dcf 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -84,7 +84,7 @@ func TestClient_New(t *testing.T) { require.NoError(t, err, "initializing the watcher should not error") c, err := client.New(wiretest.NewRandomAddress(rng), &DummyBus{t}, &ctest.MockFunder{}, &ctest.MockAdjudicator{}, wtest.RandomWallet(), watcher) - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, c) } diff --git a/client/clientconn.go b/client/clientconn.go index 660320e14..fc0335662 100644 --- a/client/clientconn.go +++ b/client/clientconn.go @@ -32,7 +32,9 @@ type clientConn struct { log.Embedding } -func makeClientConn(address wire.Address, bus wire.Bus) (c clientConn, err error) { +func makeClientConn(address wire.Address, bus wire.Bus) (clientConn, error) { + var c clientConn + var err error c.Embedding = log.MakeEmbedding(log.WithField("id", address)) c.sender = address c.bus = bus diff --git a/client/failing_funding_test.go b/client/failing_funding_test.go index 543cfd094..faf135d7c 100644 --- a/client/failing_funding_test.go +++ b/client/failing_funding_test.go @@ -41,7 +41,7 @@ func TestFailingFunding(t *testing.T) { FredInitBal: big.NewInt(50), BalanceDelta: big.NewInt(0), }, - func(r *rand.Rand) ([2]ctest.RoleSetup, channel.Asset) { + func(_ *rand.Rand) ([2]ctest.RoleSetup, channel.Asset) { roles := NewSetups(rng, []string{"Frida", "Fred"}) asset := chtest.NewRandomAsset(rng) return [2]ctest.RoleSetup{roles[0], roles[1]}, asset diff --git a/client/proposal.go b/client/proposal.go index 6b7455a39..c3019a8a5 100644 --- a/client/proposal.go +++ b/client/proposal.go @@ -48,13 +48,13 @@ type ( // HandleProposal is the user callback called by the Client on an incoming channel // proposal. // The response on the proposal responder must be called within the same go routine. - HandleProposal(ChannelProposal, *ProposalResponder) + HandleProposal(proposal ChannelProposal, responder *ProposalResponder) } // ProposalHandlerFunc is an adapter type to allow the use of functions as // proposal handlers. ProposalHandlerFunc(f) is a ProposalHandler that calls // f when HandleProposal is called. - ProposalHandlerFunc func(ChannelProposal, *ProposalResponder) + ProposalHandlerFunc func(proposal ChannelProposal, responser *ProposalResponder) // ProposalResponder lets the user respond to a channel proposal. If the user // wants to accept the proposal, they should call Accept(), otherwise Reject(). @@ -205,17 +205,17 @@ func (c *Client) ProposeChannel(ctx context.Context, prop ChannelProposal) (*Cha return ch, nil } -func (c *Client) prepareChannelOpening(ctx context.Context, prop ChannelProposal, ourIdx channel.Index) (err error) { +func (c *Client) prepareChannelOpening(ctx context.Context, prop ChannelProposal, ourIdx channel.Index) error { _, parentCh, err := c.proposalParent(prop, ourIdx) if err != nil { - return + return err } if parentCh != nil { if !parentCh.machMtx.TryLockCtx(ctx) { return ctx.Err() } } - return + return nil } func (c *Client) cleanupChannelOpening(prop ChannelProposal, ourIdx channel.Index) { @@ -259,8 +259,10 @@ func (c *Client) handleChannelProposal(handler ProposalHandler, p wire.Address, func (c *Client) handleChannelProposalAcc( ctx context.Context, p wire.Address, prop ChannelProposal, acc ChannelProposalAccept, -) (ch *Channel, err error) { - if err := c.validChannelProposalAcc(prop, acc); err != nil { +) (*Channel, error) { + var ch *Channel + var err error + if err = c.validChannelProposalAcc(prop, acc); err != nil { return ch, errors.WithMessage(err, "validating channel proposal acceptance") } @@ -608,7 +610,10 @@ func (c *Client) completeCPP( return ch, nil } -func (c *Client) proposalParent(prop ChannelProposal, partIdx channel.Index) (parentChannelID *channel.ID, parent *Channel, err error) { +func (c *Client) proposalParent(prop ChannelProposal, partIdx channel.Index) (*channel.ID, *Channel, error) { + var parentChannelID *channel.ID + var parent *Channel + var err error switch prop := prop.(type) { case *SubChannelProposalMsg: parentChannelID = &prop.Parent @@ -620,17 +625,18 @@ func (c *Client) proposalParent(prop ChannelProposal, partIdx channel.Index) (pa var ok bool if parent, ok = c.channels.Channel(*parentChannelID); !ok { err = errors.New("referenced parent channel not found") - return + return parentChannelID, parent, err } } - return + return parentChannelID, parent, err } // mpcppParts returns a proposed channel's participant addresses. func (c *Client) mpcppParts( prop ChannelProposal, acc ChannelProposalAccept, -) (parts []wallet.Address) { +) []wallet.Address { + var parts []wallet.Address switch p := prop.(type) { case *LedgerChannelProposalMsg: ledgerAcc, ok := acc.(*LedgerChannelProposalAccMsg) @@ -653,7 +659,7 @@ func (c *Client) mpcppParts( default: c.log.Panicf("unhandled %T", p) } - return + return parts } func (c *Client) fundChannel(ctx context.Context, ch *Channel, prop ChannelProposal) error { @@ -684,8 +690,8 @@ func (c *Client) completeFunding(ctx context.Context, ch *Channel) error { return nil } -func (c *Client) fundLedgerChannel(ctx context.Context, ch *Channel, agreement channel.Balances) (err error) { - if err = c.funder.Fund(ctx, +func (c *Client) fundLedgerChannel(ctx context.Context, ch *Channel, agreement channel.Balances) error { + if err := c.funder.Fund(ctx, *channel.NewFundingReq( ch.Params(), ch.machine.State(), // initial state @@ -701,7 +707,7 @@ func (c *Client) fundLedgerChannel(ctx context.Context, ch *Channel, agreement c return c.completeFunding(ctx, ch) } -func (c *Client) fundSubchannel(ctx context.Context, prop *SubChannelProposalMsg, subChannel *Channel) (err error) { +func (c *Client) fundSubchannel(ctx context.Context, prop *SubChannelProposalMsg, subChannel *Channel) error { parentChannel, ok := c.channels.Channel(prop.Parent) if !ok { return errors.New("referenced parent channel not found") @@ -751,7 +757,7 @@ func (c *Client) releaseVer1Cache() { c.version1Cache.enabled-- for _, u := range c.version1Cache.cache { - go c.handleChannelUpdate(u.uh, u.p, u.m) //nolint:contextcheck + go c.handleChannelUpdate(u.uh, u.p, u.m) } c.version1Cache.cache = nil } diff --git a/client/proposalmsgs.go b/client/proposalmsgs.go index 6115587ce..db9fce2cc 100644 --- a/client/proposalmsgs.go +++ b/client/proposalmsgs.go @@ -90,7 +90,7 @@ type ( // Matches checks whether an accept message is of the correct type. This // does not check any contents of the accept message, only its type. - Matches(ChannelProposalAccept) bool + Matches(propAccept ChannelProposalAccept) bool // Valid checks whether a channel proposal is valid. Valid() error @@ -127,7 +127,8 @@ type ( // proposalPeers returns the wire addresses of a proposed channel's // participants. -func (c *Client) proposalPeers(p ChannelProposal) (peers []wire.Address) { +func (c *Client) proposalPeers(p ChannelProposal) []wire.Address { + var peers []wire.Address switch prop := p.(type) { case *LedgerChannelProposalMsg: peers = prop.Peers @@ -142,7 +143,7 @@ func (c *Client) proposalPeers(p ChannelProposal) (peers []wire.Address) { default: c.log.Panicf("ProposalPeers: unhandled proposal type %T") } - return + return peers } // makeBaseChannelProposal creates a BaseChannelProposal and applies the supplied @@ -198,7 +199,7 @@ func (p BaseChannelProposal) Encode(w io.Writer) error { } // Decode decodes a BaseChannelProposal from an io.Reader. -func (p *BaseChannelProposal) Decode(r io.Reader) (err error) { +func (p *BaseChannelProposal) Decode(r io.Reader) error { if p.InitBals == nil { p.InitBals = new(channel.Allocation) } @@ -263,8 +264,9 @@ func NewLedgerChannelProposal( initBals *channel.Allocation, peers []wire.Address, opts ...ProposalOpts, -) (prop *LedgerChannelProposalMsg, err error) { - prop = &LedgerChannelProposalMsg{ +) (*LedgerChannelProposalMsg, error) { + var err error + prop := &LedgerChannelProposalMsg{ Participant: participant, Peers: peers, } @@ -272,7 +274,7 @@ func NewLedgerChannelProposal( challengeDuration, initBals, opts...) - return + return prop, err } // Type returns wire.LedgerChannelProposal. @@ -330,16 +332,17 @@ func NewSubChannelProposal( challengeDuration uint64, initBals *channel.Allocation, opts ...ProposalOpts, -) (prop *SubChannelProposalMsg, err error) { +) (*SubChannelProposalMsg, error) { + var err error if union(opts...).isFundingAgreement() { return nil, errors.New("Sub-Channels currently do not support funding agreements") } - prop = &SubChannelProposalMsg{Parent: parent} + prop := &SubChannelProposalMsg{Parent: parent} prop.BaseChannelProposal, err = makeBaseChannelProposal( challengeDuration, initBals, opts...) - return + return prop, err } // Encode encodes the SubChannelProposal into an io.Writer. @@ -540,23 +543,23 @@ func NewVirtualChannelProposal( parents []channel.ID, indexMaps [][]channel.Index, opts ...ProposalOpts, -) (prop *VirtualChannelProposalMsg, err error) { +) (*VirtualChannelProposalMsg, error) { base, err := makeBaseChannelProposal( challengeDuration, initBals, opts..., ) if err != nil { - return + return nil, err } - prop = &VirtualChannelProposalMsg{ + prop := &VirtualChannelProposalMsg{ BaseChannelProposal: base, Proposer: participant, Peers: peers, Parents: parents, IndexMaps: indexMaps, } - return + return prop, nil } // Encode encodes the proposal into an io.Writer. diff --git a/client/proposalmsgs_test.go b/client/proposalmsgs_test.go index 6acb2ef55..2996dd3f3 100644 --- a/client/proposalmsgs_test.go +++ b/client/proposalmsgs_test.go @@ -44,12 +44,12 @@ func TestNewLedgerChannelProposal(t *testing.T) { // FundingAgreements number of assets do not match InitBals. agreement := test.NewRandomBalances(rng, test.WithNumAssets(len(base.InitBals.Assets)+1)) _, err = client.NewLedgerChannelProposal(base.ChallengeDuration, base.Participant, base.InitBals, base.Peers, client.WithFundingAgreement(agreement)) - assert.EqualError(t, err, "comparing FundingAgreement and initial balances sum: dimension mismatch") + require.EqualError(t, err, "comparing FundingAgreement and initial balances sum: dimension mismatch") // FundingAgreements sum do not match InitBals sum. agreement = test.NewRandomBalances(rng, test.WithNumAssets(len(base.InitBals.Assets))) _, err = client.NewLedgerChannelProposal(base.ChallengeDuration, base.Participant, base.InitBals, base.Peers, client.WithFundingAgreement(agreement)) - assert.EqualError(t, err, "FundingAgreement and initial balances differ") + require.EqualError(t, err, "FundingAgreement and initial balances differ") } func TestLedgerChannelProposalReqProposalID(t *testing.T) { diff --git a/client/restore_internal_test.go b/client/restore_internal_test.go index c2b8a723f..4656e2a99 100644 --- a/client/restore_internal_test.go +++ b/client/restore_internal_test.go @@ -33,10 +33,10 @@ import ( ) func patchChFromSource( - c *Client, + _ *Client, ch *persistence.Channel, parent *Channel, - peers ...wire.Address, + _ ...wire.Address, ) (*Channel, error) { acc, _ := wallettest.RandomWallet().Unlock(ch.ParamsV.Parts[ch.IdxV]) machine, _ := channel.NewStateMachine(acc, *ch.ParamsV) @@ -131,8 +131,8 @@ func mkRndChanTree( rng *rand.Rand, depth, minChildren, maxChildren int, db map[channel.ID]*persistence.Channel, -) (root *persistence.Channel) { - root = mkRndChan(rng) +) *persistence.Channel { + root := mkRndChan(rng) db[root.ID()] = root if depth > 0 && maxChildren > 0 { @@ -146,5 +146,5 @@ func mkRndChanTree( *t.Parent = root.ID() } } - return + return root } diff --git a/client/serialize.go b/client/serialize.go index 8a696ae01..191f119b5 100644 --- a/client/serialize.go +++ b/client/serialize.go @@ -30,23 +30,24 @@ type ( ) // Encode encodes the object to the writer. -func (a channelIDsWithLen) Encode(w io.Writer) (err error) { - err = perunio.Encode(w, sliceLen(len(a))) +func (a channelIDsWithLen) Encode(w io.Writer) error { + err := perunio.Encode(w, sliceLen(len(a))) if err != nil { - return + return err } for _, id := range a { err = perunio.Encode(w, id) if err != nil { - return + return err } } - return + return err } // Decode decodes the object from the reader. -func (a *channelIDsWithLen) Decode(r io.Reader) (err error) { +func (a *channelIDsWithLen) Decode(r io.Reader) error { + var err error var l sliceLen if err = perunio.Decode(r, &l); err != nil { return errors.WithMessage(err, "decoding length") @@ -61,27 +62,28 @@ func (a *channelIDsWithLen) Decode(r io.Reader) (err error) { } (*a)[i] = id } - return + return err } // Encode encodes the object to the writer. -func (a indexMapsWithLen) Encode(w io.Writer) (err error) { - err = perunio.Encode(w, sliceLen(len(a))) +func (a indexMapsWithLen) Encode(w io.Writer) error { + err := perunio.Encode(w, sliceLen(len(a))) if err != nil { - return + return err } for _, m := range a { err = perunio.Encode(w, indexMapWithLen(m)) if err != nil { - return + return err } } - return + return err } // Decode decodes the object from the reader. -func (a *indexMapsWithLen) Decode(r io.Reader) (err error) { +func (a *indexMapsWithLen) Decode(r io.Reader) error { + var err error var l sliceLen if err = perunio.Decode(r, &l); err != nil { return errors.WithMessage(err, "decoding length") @@ -90,30 +92,31 @@ func (a *indexMapsWithLen) Decode(r io.Reader) (err error) { *a = make(indexMapsWithLen, l) for i := range *a { if err = perunio.Decode(r, (*indexMapWithLen)(&(*a)[i])); err != nil { - return + return err } } - return + return err } // Encode encodes the object to the writer. -func (a indexMapWithLen) Encode(w io.Writer) (err error) { - err = perunio.Encode(w, sliceLen(len(a))) +func (a indexMapWithLen) Encode(w io.Writer) error { + err := perunio.Encode(w, sliceLen(len(a))) if err != nil { - return + return err } for _, b := range a { err = perunio.Encode(w, b) if err != nil { - return + return err } } - return + return err } // Decode decodes the object from the reader. -func (a *indexMapWithLen) Decode(r io.Reader) (err error) { +func (a *indexMapWithLen) Decode(r io.Reader) error { + var err error var l sliceLen if err = perunio.Decode(r, &l); err != nil { return errors.WithMessage(err, "decoding length") @@ -128,5 +131,5 @@ func (a *indexMapWithLen) Decode(r io.Reader) (err error) { } (*a)[i] = b } - return + return err } diff --git a/client/sync.go b/client/sync.go index efe60e810..119b79e3e 100644 --- a/client/sync.go +++ b/client/sync.go @@ -67,7 +67,8 @@ func (c *Client) handleSyncMsg(peer wire.Address, msg *ChannelSyncMsg) { // syncChannel synchronizes the channel state with the given peer and modifies // the current state if required. -// nolint:unused +// +//nolint:unused func (c *Client) syncChannel(ctx context.Context, ch *persistence.Channel, p wire.Address) (err error) { recv := wire.NewReceiver() defer recv.Close() // ignore error @@ -117,7 +118,8 @@ func (c *Client) syncChannel(ctx context.Context, ch *persistence.Channel, p wir } // validateMessage validates the remote channel sync message. -// nolint:unused, nestif +// +//nolint:unused, nestif func validateMessage(ch *persistence.Channel, msg *ChannelSyncMsg) error { v := ch.CurrentTX().Version mv := msg.CurrentTX.Version @@ -147,7 +149,7 @@ func validateMessage(ch *persistence.Channel, msg *ChannelSyncMsg) error { return nil } -// nolint:unused +//nolint:unused func revisePhase(ch *persistence.Channel) error { //nolint:gocritic if ch.PhaseV <= channel.Funding && ch.CurrentTXV.Version == 0 { diff --git a/client/test/backend.go b/client/test/backend.go index 2ea22648e..5c331d8e8 100644 --- a/client/test/backend.go +++ b/client/test/backend.go @@ -228,8 +228,8 @@ func (b *MockBackend) Progress(_ context.Context, req channel.ProgressReq) error } // outcomeRecursive returns the accumulated outcome of the channel and its sub-channels. -func outcomeRecursive(state *channel.State, subStates channel.StateMap) (outcome channel.Balances) { - outcome = state.Balances.Clone() +func outcomeRecursive(state *channel.State, subStates channel.StateMap) channel.Balances { + outcome := state.Balances.Clone() for _, subAlloc := range state.Locked { subOutcome := outcomeRecursive(subStates[subAlloc.ID], subStates) for a, bals := range subOutcome { @@ -242,7 +242,7 @@ func outcomeRecursive(state *channel.State, subStates channel.StateMap) (outcome } } } - return + return outcome } type checkStateFunc func(e channel.AdjudicatorEvent, ok bool, s *channel.State) error @@ -566,7 +566,7 @@ type MockSubscription struct { } // NewMockSubscription creates a new MockSubscription. -func NewMockSubscription(ctx context.Context) *MockSubscription { +func NewMockSubscription(_ context.Context) *MockSubscription { return &MockSubscription{ events: make(chan channel.AdjudicatorEvent, 1), err: make(chan error, 1), diff --git a/client/test/bob.go b/client/test/bob.go index de215f6bf..4f4dc56bb 100644 --- a/client/test/bob.go +++ b/client/test/bob.go @@ -35,7 +35,7 @@ func (r *Bob) Execute(cfg ExecConfig) { r.Responder.Execute(cfg, r.exec) } -func (r *Bob) exec(_cfg ExecConfig, ch *paymentChannel, propHandler *acceptNextPropHandler) { +func (r *Bob) exec(_cfg ExecConfig, ch *paymentChannel, _ *acceptNextPropHandler) { cfg := _cfg.(*AliceBobExecConfig) we, them := r.Idxs(cfg.Peers()) diff --git a/client/test/carol.go b/client/test/carol.go index 518de1f5c..8c0a92e36 100644 --- a/client/test/carol.go +++ b/client/test/carol.go @@ -49,7 +49,7 @@ func (r *Carol) Execute(cfg ExecConfig) { r.Responder.Execute(cfg, r.exec) } -func (r *Carol) exec(_cfg ExecConfig, ch *paymentChannel, propHandler *acceptNextPropHandler) { +func (r *Carol) exec(_cfg ExecConfig, ch *paymentChannel, _ *acceptNextPropHandler) { cfg := _cfg.(*MalloryCarolExecConfig) _, them := r.Idxs(cfg.Peers()) diff --git a/client/test/fund.go b/client/test/fund.go index 76a15900d..873d8333e 100644 --- a/client/test/fund.go +++ b/client/test/fund.go @@ -107,7 +107,7 @@ func runFredFridaTest( // New channels and errors are passed via the corresponding Go channels. chsFred := make(chan *client.Channel, 1) errsFred := make(chan error, 1) - go fred.Handle( + go fred.Handle( //nolint:contextcheck AlwaysAcceptChannelHandler(ctx, fredWalletAddr, chsFred, errsFred), AlwaysRejectUpdateHandler(ctx, errsFred), ) @@ -161,6 +161,6 @@ func runFredFridaTest( type FailingFunder struct{} // Fund returns an error to simulate failed funding. -func (m FailingFunder) Fund(ctx context.Context, req channel.FundingReq) error { +func (m FailingFunder) Fund(_ context.Context, _ channel.FundingReq) error { return errors.New("funding failed") } diff --git a/client/test/handler.go b/client/test/handler.go index b0813985f..1ffadd2f8 100644 --- a/client/test/handler.go +++ b/client/test/handler.go @@ -46,7 +46,7 @@ func AlwaysAcceptChannelHandler(ctx context.Context, addr wallet.Address, channe // AlwaysRejectChannelHandler returns a channel proposal handler that rejects // all channel proposals. func AlwaysRejectChannelHandler(ctx context.Context, errs chan<- error) client.ProposalHandlerFunc { - return func(cp client.ChannelProposal, pr *client.ProposalResponder) { + return func(_ client.ChannelProposal, pr *client.ProposalResponder) { err := pr.Reject(ctx, "not accepting channels") if err != nil { errs <- err @@ -58,7 +58,7 @@ func AlwaysRejectChannelHandler(ctx context.Context, errs chan<- error) client.P // all channel updates. func AlwaysAcceptUpdateHandler(ctx context.Context, errs chan error) client.UpdateHandlerFunc { return func( - s *channel.State, cu client.ChannelUpdate, ur *client.UpdateResponder, + _ *channel.State, _ client.ChannelUpdate, ur *client.UpdateResponder, ) { err := ur.Accept(ctx) if err != nil { @@ -70,7 +70,7 @@ func AlwaysAcceptUpdateHandler(ctx context.Context, errs chan error) client.Upda // AlwaysRejectUpdateHandler returns a channel update handler that rejects all // channel updates. func AlwaysRejectUpdateHandler(ctx context.Context, errs chan error) client.UpdateHandlerFunc { - return func(state *channel.State, update client.ChannelUpdate, responder *client.UpdateResponder) { + return func(_ *channel.State, _ client.ChannelUpdate, responder *client.UpdateResponder) { err := responder.Reject(ctx, "") if err != nil { errs <- errors.WithMessage(err, "rejecting channel update") diff --git a/client/test/multiledger_dispute.go b/client/test/multiledger_dispute.go index b153f4435..dc34b1290 100644 --- a/client/test/multiledger_dispute.go +++ b/client/test/multiledger_dispute.go @@ -75,11 +75,11 @@ func TestMultiLedgerDispute( // Setup proposal handler. channels := make(chan *client.Channel, 1) errs := make(chan error) - go alice.Handle( + go alice.Handle( //nolint:contextcheck AlwaysRejectChannelHandler(ctx, errs), AlwaysAcceptUpdateHandler(ctx, errs), ) - go bob.Handle( + go bob.Handle( //nolint:contextcheck AlwaysAcceptChannelHandler(ctx, bob.WalletAddress, channels, errs), AlwaysAcceptUpdateHandler(ctx, errs), ) @@ -123,7 +123,7 @@ func TestMultiLedgerDispute( require.NoError(err) e := <-bob.Events - require.IsType(e, &channel.RegisteredEvent{}) + require.IsType(&channel.RegisteredEvent{}, e) err = e.(*channel.RegisteredEvent).TimeoutV.Wait(ctx) require.NoError(err) diff --git a/client/test/multiledger_happy.go b/client/test/multiledger_happy.go index 9ec8c021b..1bf694071 100644 --- a/client/test/multiledger_happy.go +++ b/client/test/multiledger_happy.go @@ -55,11 +55,11 @@ func TestMultiLedgerHappy(ctx context.Context, t *testing.T, mlt MultiLedgerSetu // Setup proposal handler. channels := make(chan *client.Channel, 1) errs := make(chan error) - go alice.Handle( + go alice.Handle( //nolint:contextcheck // context is checked in the test AlwaysRejectChannelHandler(ctx, errs), AlwaysAcceptUpdateHandler(ctx, errs), ) - go bob.Handle( + go bob.Handle( //nolint:contextcheck // context is checked in the test AlwaysAcceptChannelHandler(ctx, bob.WalletAddress, channels, errs), AlwaysAcceptUpdateHandler(ctx, errs), ) diff --git a/client/test/progression.go b/client/test/progression.go index be498dd9c..74b4cc3d5 100644 --- a/client/test/progression.go +++ b/client/test/progression.go @@ -80,7 +80,7 @@ func (r *Paul) Execute(cfg ExecConfig) { r.Proposer.Execute(cfg, r.exec) } -func (r *Paul) exec(_cfg ExecConfig, ch *paymentChannel) { +func (r *Paul) exec(_ ExecConfig, ch *paymentChannel) { ctx := r.Ctx() assetIdx := 0 @@ -142,7 +142,7 @@ func (r *Paula) Execute(cfg ExecConfig) { r.Responder.Execute(cfg, r.exec) } -func (r *Paula) exec(_cfg ExecConfig, ch *paymentChannel, _ *acceptNextPropHandler) { +func (r *Paula) exec(_ ExecConfig, ch *paymentChannel, _ *acceptNextPropHandler) { ctx := r.Ctx() assetIdx := 0 diff --git a/client/test/proposalmsgs.go b/client/test/proposalmsgs.go index c8984807a..cd6de99a3 100644 --- a/client/test/proposalmsgs.go +++ b/client/test/proposalmsgs.go @@ -105,9 +105,10 @@ func channelProposalRejSerializationTest(t *testing.T, serializerTest func(t *te } } -func newRandomProposalID(rng *rand.Rand) (id client.ProposalID) { +func newRandomProposalID(rng *rand.Rand) client.ProposalID { + var id client.ProposalID rng.Read(id[:]) - return + return id } // newRandomASCIIString returns a random ascii string of length between minLen and diff --git a/client/test/role.go b/client/test/role.go index 211f7bef5..96a75c325 100644 --- a/client/test/role.go +++ b/client/test/role.go @@ -28,7 +28,7 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/channel" "perun.network/go-perun/channel/persistence" "perun.network/go-perun/client" @@ -106,7 +106,7 @@ type ( // EnableStages enables role synchronization. EnableStages() Stages // SetStages enables role synchronization using the given stages. - SetStages(Stages) + SetStages(stages Stages) // Errors returns the error channel. Errors() <-chan error } @@ -128,7 +128,7 @@ func NewClients(t *testing.T, rng *rand.Rand, setups []RoleSetup) []*Client { clients := make([]*Client, len(setups)) for i, setup := range setups { cl, err := client.New(setup.Identity.Address(), setup.Bus, setup.Funder, setup.Adjudicator, setup.Wallet, setup.Watcher) - assert.NoError(t, err) + require.NoError(t, err) clients[i] = &Client{ Client: cl, RoleSetup: setup, @@ -208,9 +208,9 @@ func (c *BaseExecConfig) App() client.ProposalOpts { } // makeRole creates a client for the given setup and wraps it into a Role. -func makeRole(t *testing.T, setup RoleSetup, numStages int) (r role) { +func makeRole(t *testing.T, setup RoleSetup, numStages int) role { t.Helper() - r = role{ + r := role{ chans: &channelMap{entries: make(map[channel.ID]*paymentChannel)}, setup: setup, timeout: setup.Timeout, @@ -243,11 +243,11 @@ func (r *role) setClient(cl *client.Client) { r.log = log.AppendField(cl, "role", r.setup.Name) } -func (chs *channelMap) channel(ch channel.ID) (_ch *paymentChannel, ok bool) { +func (chs *channelMap) channel(ch channel.ID) (*paymentChannel, bool) { chs.RLock() defer chs.RUnlock() - _ch, ok = chs.entries[ch] - return + _ch, ok := chs.entries[ch] + return _ch, ok } func (chs *channelMap) add(ch *paymentChannel) { @@ -297,7 +297,8 @@ func (r *role) waitStage() { // Idxs maps the passed addresses to the indices in the 2-party-channel. If the // setup's Identity is not found in peers, Idxs panics. -func (r *role) Idxs(peers [2]wire.Address) (our, their channel.Index) { +// First return value is our. Second return value is the peer's index. +func (r *role) Idxs(peers [2]wire.Address) (channel.Index, channel.Index) { if r.setup.Identity.Address().Equal(peers[0]) { return 0, 1 } else if r.setup.Identity.Address().Equal(peers[1]) { @@ -337,7 +338,7 @@ func (r *role) RequireNoErrorf(err error, msg string, args ...interface{}) { func (r *role) RequireTrue(b bool) { if !b { - r.errs <- fmt.Errorf("expected true, got false") + r.errs <- errors.New("expected true, got false") } } @@ -375,7 +376,7 @@ type ( // GoHandle starts the handler routine on the current client and returns a // wait() function with which it can be waited for the handler routine to stop. -func (r *role) GoHandle(rng *rand.Rand) (h *acceptNextPropHandler, wait func()) { +func (r *role) GoHandle(rng *rand.Rand) (*acceptNextPropHandler, func()) { done := make(chan struct{}) propHandler := r.acceptNextPropHandler(rng) go func() { @@ -385,10 +386,12 @@ func (r *role) GoHandle(rng *rand.Rand) (h *acceptNextPropHandler, wait func()) r.log.Debug("Request handler returned.") }() - return propHandler, func() { + wait := func() { r.log.Debug("Waiting for request handler to return...") <-done } + + return propHandler, wait } func (r *role) LedgerChannelProposal(rng *rand.Rand, cfg ExecConfig) *client.LedgerChannelProposalMsg { diff --git a/client/test/subchannel.go b/client/test/subchannel.go index 3480751d5..2d308cfc3 100644 --- a/client/test/subchannel.go +++ b/client/test/subchannel.go @@ -34,8 +34,8 @@ type SusieTimExecConfig struct { // NewSusieTimExecConfig creates a new object from the given parameters. func NewSusieTimExecConfig( base BaseExecConfig, - numSubChannels int, - numSubSubChannels int, + _ int, + _ int, subChannelFunds [][2]*big.Int, subSubChannelFunds [][2]*big.Int, leafChannelApp client.ProposalOpts, diff --git a/client/test/updatemsgs.go b/client/test/updatemsgs.go index 676617cba..a0df34ef1 100644 --- a/client/test/updatemsgs.go +++ b/client/test/updatemsgs.go @@ -146,10 +146,10 @@ func newRandomSig(rng *rand.Rand) wallet.Sig { } // newRandomSigs generates a list of random signatures. -func newRandomSigs(rng *rand.Rand, n int) (a []wallet.Sig) { - a = make([]wallet.Sig, n) +func newRandomSigs(rng *rand.Rand, n int) []wallet.Sig { + a := make([]wallet.Sig, n) for i := range a { a[i] = newRandomSig(rng) } - return + return a } diff --git a/client/test/virtualchannel.go b/client/test/virtualchannel.go index 5d1449160..233764c9b 100644 --- a/client/test/virtualchannel.go +++ b/client/test/virtualchannel.go @@ -74,9 +74,9 @@ func TestVirtualChannelOptimistic( //nolint:revive // test.Test... stutters but // Test final balances. err := vct.chAliceIngrid.State().Balances.AssertEqual(channel.Balances{vct.finalBalsAlice}) - assert.NoError(t, err, "Alice: invalid final balances") + require.NoError(t, err, "Alice: invalid final balances") err = vct.chBobIngrid.State().Balances.AssertEqual(channel.Balances{vct.finalBalsBob}) - assert.NoError(t, err, "Bob: invalid final balances") + require.NoError(t, err, "Bob: invalid final balances") } // TestVirtualChannelDispute tests virtual channel functionality in the dispute @@ -96,14 +96,14 @@ func TestVirtualChannelDispute( //nolint:revive // test.Test... stutters but OK t.Logf("perm = %v", perm) for _, i := range perm { err := client.NewTestChannel(chs[i]).Register(ctx) - assert.NoErrorf(err, "register channel: %d", i) + require.NoErrorf(t, err, "register channel: %d", i) time.Sleep(waitTimeout) // Sleep to ensure that events have been processed and local client states have been updated. } // Settle the channels in a random order. for _, i := range rand.Perm(len(chs)) { err := chs[i].Settle(ctx, false) - assert.NoErrorf(err, "settle channel: %d", i) + require.NoErrorf(t, err, "settle channel: %d", i) } // Check final balances. @@ -164,10 +164,11 @@ func setupVirtualChannelTest( t *testing.T, ctx context.Context, setup VirtualChannelSetup, -) (vct virtualChannelTest) { +) virtualChannelTest { t.Helper() require := require.New(t) + var vct virtualChannelTest // Set test values. asset := setup.Asset vct.asset = asset @@ -211,10 +212,10 @@ func setupVirtualChannelTest( } } var updateProposalHandlerIngrid client.UpdateHandlerFunc = func( - s *channel.State, cu client.ChannelUpdate, ur *client.UpdateResponder, + _ *channel.State, _ client.ChannelUpdate, _ *client.UpdateResponder, ) { } - go ingrid.Client.Handle(openingProposalHandlerIngrid, updateProposalHandlerIngrid) + go ingrid.Client.Handle(openingProposalHandlerIngrid, updateProposalHandlerIngrid) //nolint:contextcheck // context is checked in the test // Establish ledger channel between Alice and Ingrid. peersAlice := []wire.Address{alice.Identity.Address(), ingrid.Identity.Address()} @@ -273,14 +274,14 @@ func setupVirtualChannelTest( } } var updateProposalHandlerBob client.UpdateHandlerFunc = func( - s *channel.State, cu client.ChannelUpdate, ur *client.UpdateResponder, + _ *channel.State, _ client.ChannelUpdate, ur *client.UpdateResponder, ) { err := ur.Accept(ctx) if err != nil { vct.errs <- errors.WithMessage(err, "Bob: accepting channel update") } } - go bob.Client.Handle(openingProposalHandlerBob, updateProposalHandlerBob) + go bob.Client.Handle(openingProposalHandlerBob, updateProposalHandlerBob) //nolint:contextcheck // context is checked in the test // Establish virtual channel between Alice and Bob via Ingrid. initAllocVirtual := channel.Allocation{ diff --git a/client/update.go b/client/update.go index 363b84c0f..465deda2c 100644 --- a/client/update.go +++ b/client/update.go @@ -16,7 +16,6 @@ package client import ( "context" - "fmt" "github.com/pkg/errors" @@ -42,7 +41,7 @@ func (c *Client) handleChannelUpdate(uh UpdateHandler, p wire.Address, m Channel return } pidx := ch.Idx() ^ 1 - ch.handleUpdateReq(pidx, m, uh) //nolint:contextcheck + ch.handleUpdateReq(pidx, m, uh) } func (c *Client) cacheVersion1Update(uh UpdateHandler, p wire.Address, m ChannelUpdateProposal) bool { @@ -78,13 +77,13 @@ type ( // incoming update request. The first argument contains the current state // of the channel before the update is applied. Clone it if you want to // modify it. - HandleUpdate(*channel.State, ChannelUpdate, *UpdateResponder) + HandleUpdate(current *channel.State, update ChannelUpdate, responder *UpdateResponder) } // UpdateHandlerFunc is an adapter type to allow the use of functions as // update handlers. UpdateHandlerFunc(f) is an UpdateHandler that calls // f when HandleUpdate is called. - UpdateHandlerFunc func(*channel.State, ChannelUpdate, *UpdateResponder) + UpdateHandlerFunc func(current *channel.State, update ChannelUpdate, responder *UpdateResponder) // The UpdateResponder allows the user to react to the incoming channel update // request. If the user wants to accept the update, Accept() should be called, @@ -119,7 +118,7 @@ func (r *UpdateResponder) Accept(ctx context.Context) error { return errors.New("context must not be nil") } if !r.called.TrySet() { - return fmt.Errorf("multiple calls on channel update responder") + return errors.New("multiple calls on channel update responder") } return r.channel.acceptUpdate(ctx, r.pidx, r.req) @@ -135,7 +134,7 @@ func (r *UpdateResponder) Reject(ctx context.Context, reason string) error { return errors.New("context must not be nil") } if !r.called.TrySet() { - return fmt.Errorf("multiple calls on channel update responder") + return errors.New("multiple calls on channel update responder") } return r.channel.rejectUpdate(ctx, r.pidx, r.req, reason) @@ -187,7 +186,8 @@ func (c *Channel) updateGeneric( ctx context.Context, next *channel.State, prepareMsg func(*ChannelUpdateMsg) wire.Msg, -) (err error) { +) error { + var err error up := makeChannelUpdate(next, c.machine.Idx()) if err = c.machine.Update(ctx, up.State, up.ActorIdx); err != nil { return errors.WithMessage(err, "updating machine") @@ -251,7 +251,7 @@ func (c *Channel) checkUpdateError(ctx context.Context, updateErr error) { } } -func (c *Channel) update(ctx context.Context, updater func(*channel.State) error) (err error) { +func (c *Channel) update(ctx context.Context, updater func(*channel.State) error) error { state := c.machine.State().Clone() if err := updater(state); err != nil { return err @@ -287,10 +287,10 @@ func (c *Channel) handleUpdateReq( // Check whether we have an update related to a virtual channel. switch prop := req.(type) { case *VirtualChannelFundingProposalMsg: - client.handleVirtualChannelFundingProposal(c, prop, responder) //nolint:contextcheck + client.handleVirtualChannelFundingProposal(c, prop, responder) return case *VirtualChannelSettlementProposalMsg: - client.handleVirtualChannelSettlementProposal(c, prop, responder) //nolint:contextcheck + client.handleVirtualChannelSettlementProposal(c, prop, responder) return } @@ -371,7 +371,8 @@ func (c *Channel) rejectUpdate( pidx channel.Index, req ChannelUpdateProposal, reason string, -) (err error) { +) error { + var err error defer func() { if err != nil { c.logPeer(pidx).Errorf("error rejecting state: %v", err) @@ -383,7 +384,8 @@ func (c *Channel) rejectUpdate( Version: req.Base().State.Version, Reason: reason, } - return errors.WithMessage(c.conn.Send(ctx, msgUpRej), "sending reject message") + err = errors.WithMessage(c.conn.Send(ctx, msgUpRej), "sending reject message") + return err } // enableNotifyUpdate enables the current staging state of the machine. If the diff --git a/client/updatemsgs.go b/client/updatemsgs.go index 6a06f3250..bee328620 100644 --- a/client/updatemsgs.go +++ b/client/updatemsgs.go @@ -139,7 +139,8 @@ func (c ChannelUpdateMsg) Encode(w io.Writer) error { } // Decode decodes the ChannelUpdateMsg from the io.Reader. -func (c *ChannelUpdateMsg) Decode(r io.Reader) (err error) { +func (c *ChannelUpdateMsg) Decode(r io.Reader) error { + var err error if c.State == nil { c.State = new(channel.State) } @@ -156,7 +157,8 @@ func (c ChannelUpdateAccMsg) Encode(w io.Writer) error { } // Decode decodes the ChannelUpdateAccMsg from the io.Reader. -func (c *ChannelUpdateAccMsg) Decode(r io.Reader) (err error) { +func (c *ChannelUpdateAccMsg) Decode(r io.Reader) error { + var err error if err := perunio.Decode(r, &c.ChannelID, &c.Version); err != nil { return err } @@ -170,7 +172,7 @@ func (c ChannelUpdateRejMsg) Encode(w io.Writer) error { } // Decode decodes the ChannelUpdateRejMsg from the io.Reader. -func (c *ChannelUpdateRejMsg) Decode(r io.Reader) (err error) { +func (c *ChannelUpdateRejMsg) Decode(r io.Reader) error { return perunio.Decode(r, &c.ChannelID, &c.Version, &c.Reason) } @@ -224,7 +226,8 @@ func (*VirtualChannelFundingProposalMsg) Type() wire.Type { } // Encode encodes the VirtualChannelFundingProposalMsg into the io.Writer. -func (m VirtualChannelFundingProposalMsg) Encode(w io.Writer) (err error) { +func (m VirtualChannelFundingProposalMsg) Encode(w io.Writer) error { + var err error err = perunio.Encode(w, m.ChannelUpdateMsg, m.Initial.Params, @@ -232,26 +235,27 @@ func (m VirtualChannelFundingProposalMsg) Encode(w io.Writer) (err error) { indexMapWithLen(m.IndexMap), ) if err != nil { - return + return err } - return wallet.EncodeSparseSigs(w, m.Initial.Sigs) + err = wallet.EncodeSparseSigs(w, m.Initial.Sigs) + return err } // Decode decodes the VirtualChannelFundingProposalMsg from the io.Reader. -func (m *VirtualChannelFundingProposalMsg) Decode(r io.Reader) (err error) { +func (m *VirtualChannelFundingProposalMsg) Decode(r io.Reader) error { m.Initial = channel.SignedState{ Params: &channel.Params{}, State: &channel.State{}, } - err = perunio.Decode(r, + err := perunio.Decode(r, &m.ChannelUpdateMsg, m.Initial.Params, m.Initial.State, (*indexMapWithLen)(&m.IndexMap), ) if err != nil { - return + return err } m.Initial.Sigs = make([]wallet.Sig, m.Initial.State.NumParts()) @@ -264,21 +268,22 @@ func (*VirtualChannelSettlementProposalMsg) Type() wire.Type { } // Encode encodes the VirtualChannelSettlementProposalMsg into the io.Writer. -func (m VirtualChannelSettlementProposalMsg) Encode(w io.Writer) (err error) { - err = perunio.Encode(w, +func (m VirtualChannelSettlementProposalMsg) Encode(w io.Writer) error { + err := perunio.Encode(w, m.ChannelUpdateMsg, m.Final.Params, *m.Final.State, ) if err != nil { - return + return err } return wallet.EncodeSparseSigs(w, m.Final.Sigs) } // Decode decodes the VirtualChannelSettlementProposalMsg from the io.Reader. -func (m *VirtualChannelSettlementProposalMsg) Decode(r io.Reader) (err error) { +func (m *VirtualChannelSettlementProposalMsg) Decode(r io.Reader) error { + var err error m.Final = channel.SignedState{ Params: &channel.Params{}, State: &channel.State{}, @@ -289,7 +294,7 @@ func (m *VirtualChannelSettlementProposalMsg) Decode(r io.Reader) (err error) { m.Final.State, ) if err != nil { - return + return err } m.Final.Sigs = make([]wallet.Sig, m.Final.State.NumParts()) diff --git a/client/virtual_channel.go b/client/virtual_channel.go index c903fc88f..3f72507bf 100644 --- a/client/virtual_channel.go +++ b/client/virtual_channel.go @@ -90,7 +90,7 @@ func (c *Client) handleVirtualChannelFundingProposal( ) { err := c.validateVirtualChannelFundingProposal(ch, prop) if err != nil { - c.rejectProposal(responder, err.Error()) //nolint:contextcheck + c.rejectProposal(responder, err.Error()) } ctx, cancel := context.WithTimeout(c.Ctx(), virtualFundingTimeout) @@ -98,10 +98,10 @@ func (c *Client) handleVirtualChannelFundingProposal( err = c.fundingWatcher.Await(ctx, prop) if err != nil { - c.rejectProposal(responder, err.Error()) //nolint:contextcheck + c.rejectProposal(responder, err.Error()) } - c.acceptProposal(responder) //nolint:contextcheck + c.acceptProposal(responder) } func (c *Channel) watchVirtual() error { @@ -349,7 +349,7 @@ func (c *Client) matchFundingProposal(ctx context.Context, a, b interface{}) boo go func() { // The context will be derived from the channel context. - err := virtual.watchVirtual() //nolint:contextcheck + err := virtual.watchVirtual() c.log.Debugf("channel %v: watcher stopped: %v", virtual.ID(), err) }() return true @@ -379,8 +379,8 @@ func (c *Client) gatherChannels(props ...*VirtualChannelFundingProposalMsg) ([]* return channels, nil } -func (c *Client) gatherPeers(channels ...*Channel) (peers []wire.Address) { - peers = make([]wire.Address, len(channels)) +func (c *Client) gatherPeers(channels ...*Channel) []wire.Address { + peers := make([]wire.Address, len(channels)) for i, ch := range channels { chPeers := ch.Peers() if len(chPeers) != gatherNumPeers { @@ -388,5 +388,5 @@ func (c *Client) gatherPeers(channels ...*Channel) (peers []wire.Address) { } peers[i] = chPeers[1-ch.Idx()] } - return + return peers } diff --git a/client/virtual_channel_settlement.go b/client/virtual_channel_settlement.go index 71abb0880..f90042c58 100644 --- a/client/virtual_channel_settlement.go +++ b/client/virtual_channel_settlement.go @@ -79,7 +79,7 @@ func (c *Client) handleVirtualChannelSettlementProposal( ) { err := c.validateVirtualChannelSettlementProposal(parent, prop) if err != nil { - c.rejectProposal(responder, err.Error()) //nolint:contextcheck + c.rejectProposal(responder, err.Error()) } ctx, cancel := context.WithTimeout(c.Ctx(), virtualSettlementTimeout) @@ -90,7 +90,7 @@ func (c *Client) handleVirtualChannelSettlementProposal( resp: responder, }) if err != nil { - c.rejectProposal(responder, err.Error()) //nolint:contextcheck + c.rejectProposal(responder, err.Error()) } } diff --git a/client/virtual_channel_util.go b/client/virtual_channel_util.go index 7c3ebe479..5833de368 100644 --- a/client/virtual_channel_util.go +++ b/client/virtual_channel_util.go @@ -27,8 +27,8 @@ func (c *Channel) translateBalances(indexMap []channel.Index) channel.Balances { return transformBalances(state.Balances, state.NumParts(), indexMap) } -func transformBalances(b channel.Balances, numParts int, indexMap []channel.Index) (_b channel.Balances) { - _b = make(channel.Balances, len(b)) +func transformBalances(b channel.Balances, numParts int, indexMap []channel.Index) channel.Balances { + _b := make(channel.Balances, len(b)) for a := range _b { _b[a] = make([]*big.Int, numParts) // Init with zero. @@ -40,7 +40,7 @@ func transformBalances(b channel.Balances, numParts int, indexMap []channel.Inde _b[a][_p] = b[a][p] } } - return + return _b } func (c *Client) rejectProposal(responder *UpdateResponder, reason string) { @@ -84,7 +84,8 @@ func newStateWatcher(c func(ctx context.Context, a, b interface{}) bool) *stateW func (w *stateWatcher) Await( ctx context.Context, state interface{}, -) (err error) { +) error { + var err error match := make(chan struct{}, 1) w.register(ctx, state, match) defer w.deregister(state) @@ -93,7 +94,7 @@ func (w *stateWatcher) Await( case <-ctx.Done(): err = ctx.Err() } - return + return err } func (w *stateWatcher) register( diff --git a/go.mod b/go.mod index 18373cc42..4d782adfe 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module perun.network/go-perun -go 1.17 +go 1.21 require ( github.com/pkg/errors v0.9.1 diff --git a/go.sum b/go.sum index ba9700f3c..22c350b7c 100644 --- a/go.sum +++ b/go.sum @@ -12,7 +12,6 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -91,7 +90,6 @@ golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912 h1:uCLL3g5wH2xjxVREVuAbP9JM5PPKjRbXKRa6IBjkzmU= golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -118,7 +116,6 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/log/log.go b/log/log.go index c84497659..c993ddaf4 100644 --- a/log/log.go +++ b/log/log.go @@ -54,24 +54,26 @@ type StdLogger interface { // Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. Printf(format string, args ...interface{}) // Print prints to the logger. Arguments are handled in the manner of fmt.Print. - Print(...interface{}) + Print(args ...interface{}) // Println prints to the logger. Arguments are handled in the manner of fmt.Println. - Println(...interface{}) + Println(args ...interface{}) // Fatalf is equivalent to Printf() followed by a call to os.Exit(1). Fatalf(format string, args ...interface{}) // Fatal is equivalent to Print() followed by a call to os.Exit(1). - Fatal(...interface{}) + Fatal(args ...interface{}) // Fatalln is equivalent to Println() followed by a call to os.Exit(1). - Fatalln(...interface{}) + Fatalln(args ...interface{}) // Panicf is equivalent to Printf() followed by a call to panic(). Panicf(format string, args ...interface{}) // Panic is equivalent to Print() followed by a call to panic(). - Panic(...interface{}) + Panic(args ...interface{}) // Panicln is equivalent to Println() followed by a call to panic(). - Panicln(...interface{}) + Panicln(args ...interface{}) } // LevelLogger is an extension to the StdLogger with different verbosity levels. +// +//nolint:interfacebloat type LevelLogger interface { StdLogger // Tracef logs a message at level Trace. Arguments are handled in the manner of fmt.Printf. @@ -85,25 +87,25 @@ type LevelLogger interface { // Errorf logs a message at level Error. Arguments are handled in the manner of fmt.Printf. Errorf(format string, args ...interface{}) // Trace logs a message at level Trace. - Trace(...interface{}) + Trace(msgs ...interface{}) // Debug logs a message at level Debug. - Debug(...interface{}) + Debug(msgs ...interface{}) // Info logs a message at level Info. - Info(...interface{}) + Info(msgs ...interface{}) // Warn logs a message at level Warn. - Warn(...interface{}) + Warn(msgs ...interface{}) // Error logs a message at level Error. - Error(...interface{}) + Error(msgs ...interface{}) // Traceln logs a message at level Trace. Arguments are handled in the manner of fmt.Println. - Traceln(...interface{}) + Traceln(msgs ...interface{}) // Debugln logs a message at level Debug. Arguments are handled in the manner of fmt.Println. - Debugln(...interface{}) + Debugln(msgs ...interface{}) // Infoln logs a message at level Info. Arguments are handled in the manner of fmt.Println. - Infoln(...interface{}) + Infoln(msgs ...interface{}) // Warnln logs a message at level Warn. Arguments are handled in the manner of fmt.Println. - Warnln(...interface{}) + Warnln(msgs ...interface{}) // Errorln logs a message at level Error. Arguments are handled in the manner of fmt.Println. - Errorln(...interface{}) + Errorln(msgs ...interface{}) } // Fields is a collection of fields that can be passed to FieldLogger.WithFields. @@ -114,8 +116,8 @@ type Fields map[string]interface{} type Logger interface { LevelLogger WithField(key string, value interface{}) Logger - WithFields(Fields) Logger - WithError(error) Logger + WithFields(fields Fields) Logger + WithError(err error) Logger } // Printf calls Printf on the global Logger object. @@ -211,7 +213,7 @@ type ( // Log returns the logger used by the Owner. Log() Logger // SetLog sets the logger that the Owner uses in the future. - SetLog(Logger) + SetLog(logger Logger) } // An Embedding can be embedded into any struct to endow it with a logger and diff --git a/log/logrus/logrus.go b/log/logrus/logrus.go index 31913f0c1..869b555a6 100644 --- a/log/logrus/logrus.go +++ b/log/logrus/logrus.go @@ -53,7 +53,7 @@ func stringify(value interface{}) interface{} { } // WithFields calls WithField for all passed fields. -func (l *Logger) WithFields(fields log.Fields) (ret log.Logger) { +func (l *Logger) WithFields(fields log.Fields) log.Logger { newFields := make(map[string]interface{}) for k, v := range fields { newFields[k] = stringify(v) diff --git a/log/logrus/logrus_internal_test.go b/log/logrus/logrus_internal_test.go index e95884423..c2aaa89c1 100644 --- a/log/logrus/logrus_internal_test.go +++ b/log/logrus/logrus_internal_test.go @@ -42,9 +42,9 @@ func testLogrusInfo(t *testing.T) { logger, hook := test.NewNullLogger() FromLogrus(logger).Println("Anton Ausdemhaus") - assert.Equal(t, len(hook.Entries), 1) - assert.Equal(t, hook.LastEntry().Level, logrus.InfoLevel) - assert.Equal(t, hook.LastEntry().Message, "Anton Ausdemhaus") + assert.Len(t, hook.Entries, 1) + assert.Equal(t, logrus.InfoLevel, hook.LastEntry().Level) + assert.Equal(t, "Anton Ausdemhaus", hook.LastEntry().Message) } func testLogrusStringer(t *testing.T) { @@ -80,11 +80,11 @@ func testLogrusWithField(t *testing.T) { logger.SetLevel(logrus.DebugLevel) FromLogrus(logger).WithField("field", 123456).Debugln("Bertha Bremsweg") - assert.Equal(t, len(hook.Entries), 1) - assert.Equal(t, hook.LastEntry().Level, logrus.DebugLevel) - assert.Equal(t, hook.LastEntry().Message, "Bertha Bremsweg") + assert.Len(t, hook.Entries, 1) + assert.Equal(t, logrus.DebugLevel, hook.LastEntry().Level) + assert.Equal(t, "Bertha Bremsweg", hook.LastEntry().Message) assert.Contains(t, hook.LastEntry().Data, "field") - assert.Equal(t, hook.LastEntry().Data["field"], 123456) + assert.Equal(t, 123456, hook.LastEntry().Data["field"]) } func testLogrusWithFields(t *testing.T) { @@ -97,8 +97,8 @@ func testLogrusWithFields(t *testing.T) { } FromLogrus(logger).WithFields(fields).Errorln("Christian Chaos") - assert.Equal(t, len(hook.Entries), 1) - assert.Equal(t, hook.LastEntry().Level, logrus.ErrorLevel) - assert.Equal(t, hook.LastEntry().Message, "Christian Chaos") + assert.Len(t, hook.Entries, 1) + assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) + assert.Equal(t, "Christian Chaos", hook.LastEntry().Message) assert.EqualValues(t, hook.LastEntry().Data, fields) } diff --git a/log/none.go b/log/none.go index 5148ce0dd..4eb77bdfc 100644 --- a/log/none.go +++ b/log/none.go @@ -61,7 +61,7 @@ func (none) Fatalln(args ...interface{}) { exit(1) } -func (n *none) WithField(key string, value interface{}) Logger { +func (n *none) WithField(_ string, _ interface{}) Logger { return n } diff --git a/wallet/address.go b/wallet/address.go index ec89873e1..fd5c9355f 100644 --- a/wallet/address.go +++ b/wallet/address.go @@ -41,7 +41,7 @@ type Address interface { fmt.Stringer // Equal returns wether the two addresses are equal. The implementation // must be equivalent to checking `Address.Cmp(Address) == 0`. - Equal(Address) bool + Equal(addr Address) bool } // IndexOfAddr returns the index of the given address in the address slice, @@ -125,10 +125,10 @@ func (a AddressesWithLen) Encode(w stdio.Writer) error { // Decode decodes a wallet address slice of known length. The slice has to be // allocated to the correct size already. -func (a Addresses) Decode(r stdio.Reader) (err error) { +func (a Addresses) Decode(r stdio.Reader) error { for i := range a { a[i] = NewAddress() - err = perunio.Decode(r, a[i]) + err := perunio.Decode(r, a[i]) if err != nil { return errors.WithMessagef(err, "decoding %d-th address", i) } @@ -137,9 +137,9 @@ func (a Addresses) Decode(r stdio.Reader) (err error) { } // Decode decodes a wallet address slice of unknown length. -func (a *AddressesWithLen) Decode(r stdio.Reader) (err error) { +func (a *AddressesWithLen) Decode(r stdio.Reader) error { var parts addressSliceLen - if err = perunio.Decode(r, &parts); err != nil { + if err := perunio.Decode(r, &parts); err != nil { return errors.WithMessage(err, "decoding count") } @@ -148,10 +148,9 @@ func (a *AddressesWithLen) Decode(r stdio.Reader) (err error) { } // Decode decodes a single wallet address. -func (a AddressDec) Decode(r stdio.Reader) (err error) { +func (a AddressDec) Decode(r stdio.Reader) error { *a.Addr = NewAddress() - err = perunio.Decode(r, *a.Addr) - return err + return perunio.Decode(r, *a.Addr) } // Key returns the `AddrKey` corresponding to the passed `Address`. diff --git a/wallet/backend.go b/wallet/backend.go index 43565fc78..86dbadc18 100644 --- a/wallet/backend.go +++ b/wallet/backend.go @@ -30,7 +30,7 @@ type Backend interface { // DecodeSig reads a signature from the provided stream. It is needed for // decoding of wire messages. - DecodeSig(io.Reader) (Sig, error) + DecodeSig(reader io.Reader) (Sig, error) // VerifySignature verifies if this signature was signed by this address. // It should return an error iff the signature or message are malformed. diff --git a/wallet/sig.go b/wallet/sig.go index 98a0375ec..a91060f9e 100644 --- a/wallet/sig.go +++ b/wallet/sig.go @@ -51,12 +51,13 @@ type SigDec struct { } // Decode decodes a single signature. -func (s SigDec) Decode(r io.Reader) (err error) { +func (s SigDec) Decode(r io.Reader) error { + var err error *s.Sig, err = DecodeSig(r) return err } -// EncodeSparseSigs encodes a collection of signatures in the form ( mask, sig, sig, sig, ...). +// EncodeSparseSigs encodes a collection of signatures in the form ( mask, sigs). func EncodeSparseSigs(w io.Writer, sigs []Sig) error { n := len(sigs) @@ -82,8 +83,9 @@ func EncodeSparseSigs(w io.Writer, sigs []Sig) error { return nil } -// DecodeSparseSigs decodes a collection of signatures in the form (mask, sig, sig, sig, ...). -func DecodeSparseSigs(r io.Reader, sigs *[]Sig) (err error) { +// DecodeSparseSigs decodes a collection of signatures in the form (mask, sigs). +func DecodeSparseSigs(r io.Reader, sigs *[]Sig) error { + var err error masklen := int(math.Ceil(float64(len(*sigs)) / float64(bitsPerByte))) mask := make([]uint8, masklen) diff --git a/wallet/test/address.go b/wallet/test/address.go index ff6cb1f8c..f7d86c71f 100644 --- a/wallet/test/address.go +++ b/wallet/test/address.go @@ -29,7 +29,7 @@ import ( func TestAddress(t *testing.T, s *Setup) { //nolint:revive // `test.Test...` stutters, but we accept that here. null := s.ZeroAddress addr := s.Backend.NewAddress() - assert.NoError(t, addr.UnmarshalBinary(s.AddressMarshalled), "Byte deserialization of address should work") + require.NoError(t, addr.UnmarshalBinary(s.AddressMarshalled), "Byte deserialization of address should work") // Test Address.String. nullString := null.String() @@ -44,9 +44,9 @@ func TestAddress(t *testing.T, s *Setup) { //nolint:revive // `test.Test...` stu // Test Address.Bytes. addrBytes, err := addr.MarshalBinary() - assert.NoError(t, err, "Marshaling address should not error") + require.NoError(t, err, "Marshaling address should not error") nullBytes, err := null.MarshalBinary() - assert.NoError(t, err, "Marshaling zero address should not error") + require.NoError(t, err, "Marshaling zero address should not error") assert.False(t, bytes.Equal(addrBytes, nullBytes), "Expected inequality of byte representations of nonzero and zero address") // a.Equal(Decode(Encode(a))) diff --git a/wallet/test/randomizer.go b/wallet/test/randomizer.go index 4171d120b..9d9303018 100644 --- a/wallet/test/randomizer.go +++ b/wallet/test/randomizer.go @@ -26,7 +26,7 @@ type ( Randomizer interface { // NewRandomAddress should return a new random address generated from the // passed rng. - NewRandomAddress(*rand.Rand) wallet.Address + NewRandomAddress(rng *rand.Rand) wallet.Address // RandomWallet should return a fixed random wallet that is part of the // randomizer's state. It will be used to generate accounts with @@ -45,7 +45,7 @@ type ( // NewRandomAccount should return an account generated from the passed rng. // The account should be stored and unlocked in the Wallet. - NewRandomAccount(*rand.Rand) wallet.Account + NewRandomAccount(rng *rand.Rand) wallet.Account } ) diff --git a/wallet/test/wallet.go b/wallet/test/wallet.go index 83d469076..79e397359 100644 --- a/wallet/test/wallet.go +++ b/wallet/test/wallet.go @@ -45,20 +45,20 @@ type Setup struct { // This function should be called by every implementation of the wallet interface. func TestAccountWithWalletAndBackend(t *testing.T, s *Setup) { //nolint:revive // `test.Test...` stutters, but we accept that here. acc, err := s.Wallet.Unlock(s.AddressInWallet) - assert.NoError(t, err) + require.NoError(t, err) // Check unlocked account sig, err := acc.SignData(s.DataToSign) - assert.NoError(t, err, "Sign with unlocked account should succeed") + require.NoError(t, err, "Sign with unlocked account should succeed") valid, err := s.Backend.VerifySignature(s.DataToSign, sig, acc.Address()) assert.True(t, valid, "Verification should succeed") - assert.NoError(t, err, "Verification should not produce error") + require.NoError(t, err, "Verification should not produce error") addr := s.Backend.NewAddress() err = addr.UnmarshalBinary(s.AddressMarshalled) - assert.NoError(t, err, "Binary unmarshalling of address should work") + require.NoError(t, err, "Binary unmarshalling of address should work") valid, err = s.Backend.VerifySignature(s.DataToSign, sig, addr) assert.False(t, valid, "Verification with wrong address should fail") - assert.NoError(t, err, "Verification of valid signature should not produce error") + require.NoError(t, err, "Verification of valid signature should not produce error") tampered := make([]byte, len(sig)) copy(tampered, sig) @@ -90,7 +90,7 @@ func TestAccountWithWalletAndBackend(t *testing.T, s *Setup) { //nolint:revive / err = perunio.Encode(buff, sig) require.NoError(t, err, "encode sig") sign2, err := s.Backend.DecodeSig(buff) - assert.NoError(t, err, "Decoded signature should work") + require.NoError(t, err, "Decoded signature should work") assert.Equal(t, sig, sign2, "Decoded signature should be equal to the original") // Test DecodeSig on short stream @@ -119,7 +119,7 @@ func GenericSignatureSizeTest(t *testing.T, s *Setup) { for i := 0; i < 256; i++ { sign, err := acc.SignData(s.DataToSign) require.NoError(t, err, "Sign with unlocked account should succeed") - require.Equal(t, l, len(sign), "Signatures should have constant length: %d vs %d", l, len(sign)) + require.Len(t, sign, l, "Signatures should have constant length: %d vs %d", l, len(sign)) } }) } diff --git a/wallet/wallet.go b/wallet/wallet.go index 621598749..59ee270d6 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -24,7 +24,7 @@ type Wallet interface { // LockAll has been called, or a matching count of IncrementUsage and // DecrementUsage calls on the account's address has been made. Unlock may // be called multiple times for the same Address by the Perun SDK. - Unlock(Address) (Account, error) + Unlock(addr Address) (Account, error) // LockAll is called by the framework when a Client shuts down. This should // release all temporary resources held by the wallet, and accesses to @@ -36,7 +36,7 @@ type Wallet interface { // The address passed to the function belongs to the Account the Client is // using to participate in the channel. Implementing this function with any // behavior is not essential. - IncrementUsage(Address) + IncrementUsage(addr Address) // DecrementUsage is called whenever a channel is settled. The address // passed to the function belongs to the Account the Client is using to @@ -46,5 +46,5 @@ type Wallet interface { // the wallet implementation. In that event, the affected account does not // have to be able to sign messages anymore. Implementing this function with // any behavior is not essential. - DecrementUsage(Address) + DecrementUsage(addr Address) } diff --git a/watcher/local/adjudicatorpubsub.go b/watcher/local/adjudicatorpubsub.go index 6f94a9571..31a3db7ef 100644 --- a/watcher/local/adjudicatorpubsub.go +++ b/watcher/local/adjudicatorpubsub.go @@ -34,7 +34,7 @@ type ( // adjudicatorPub is used by the watcher to publish the adjudicator events // received from the blockchain to the client. adjudicatorPub interface { - publish(channel.AdjudicatorEvent) + publish(adjEvent channel.AdjudicatorEvent) close() } ) @@ -48,14 +48,14 @@ func newAdjudicatorEventsPubSub() *adjudicatorPubSub { // publish publishes the given adjudicator event to the subscriber. // // Panics if the pub-sub instance is already closed. It is implemented this -// way, because -// 1. The watcher will publish on this pub-sub only when it receives an -// adjudicator event from the blockchain. -// 2. When de-registering a channel from the watcher, watcher will close the -// subscription for adjudicator events from blockchain, before closing this -// pub-sub. -// 3. This way, it can be guaranteed that, this method will never be called -// after the pub-sub instance is closed. +// way, because: +// 1. The watcher will publish on this pub-sub only when it receives an +// adjudicator event from the blockchain. +// 2. When de-registering a channel from the watcher, watcher will close the +// subscription for adjudicator events from blockchain, before closing this +// pub-sub. +// 3. This way, it can be guaranteed that, this method will never be called +// after the pub-sub instance is closed. func (a *adjudicatorPubSub) publish(e channel.AdjudicatorEvent) { a.pipe <- e } diff --git a/watcher/local/statespubsub.go b/watcher/local/statespubsub.go index 90ef993fd..402b1851d 100644 --- a/watcher/local/statespubsub.go +++ b/watcher/local/statespubsub.go @@ -47,17 +47,17 @@ func newStatesPubSub() *statesPubSub { } // Publish publishes the given transaction (state and signatures on it) to the -// subscriber. +// subscriber. It always returns nil. The error result is for implementing +// watcher.StatesPub. // -// Always returns nil. Error result is for implementing watcher.StatesPub. -// -// Panics if the pub-sub instance is already closed. It is implemented this -// way, because -// 1. Watcher requires that, the Publish method must not be called after stop -// watching for a channel. See docs of watcher.StatesPub for more details. -// 2. Hence, by properly integrating the watcher into the client, it can be -// guaranteed that, this method will never be called after the pub-sub -// instance is closed and that, this method will never panic. +// This function panics if the pub-sub instance is already closed. This design +// choice is made because: +// 1. The Watcher requires that the Publish method must not be called after +// stop watching for a channel. See the documentation of watcher.StatesPub +// for more details. +// 2. By properly integrating the watcher into the client, it can be guaranteed +// that this method will never be called after the pub-sub instance is +// closed and that this method will never panic. func (s *statesPubSub) Publish(_ context.Context, tx channel.Transaction) error { s.pipe <- tx return nil diff --git a/watcher/local/watcher.go b/watcher/local/watcher.go index b74de505f..b374bd944 100644 --- a/watcher/local/watcher.go +++ b/watcher/local/watcher.go @@ -206,7 +206,7 @@ func (w *Watcher) startWatching( Sigs: signedState.Sigs, } ch.Go(func() { ch.handleStatesFromClient(initialTx) }) - ch.Go(func() { ch.handleEventsFromChain(w.rs, w.registry) }) //nolint:contextcheck + ch.Go(func() { ch.handleEventsFromChain(w.rs, w.registry) }) return statesPubSub, eventsToClientPubSub, nil } diff --git a/watcher/local/watcher_test.go b/watcher/local/watcher_test.go index fc6872b3f..3fbc1b9f3 100644 --- a/watcher/local/watcher_test.go +++ b/watcher/local/watcher_test.go @@ -774,6 +774,7 @@ func (t *adjEventSource) close() { // the "Subscribe" method to be called once. The adjSub and the err are set as // the return values for the call and will be returned when the method is // called. +// //nolint:unparam func setExpectationSubscribeCall(rs *mocks.RegisterSubscriber, adjSub channel.AdjudicatorSubscription, err error) { rs.On("Subscribe", testifyMock.Anything, testifyMock.Anything).Return(adjSub, err).Once() @@ -973,6 +974,6 @@ func triggerAdjEventAndExpectNotification( wantEvent := trigger.trigger() t.Logf("waiting for adjudicator event for ch %x, version: %v", wantEvent.ID(), wantEvent.Version()) gotEvent := <-eventsForClient.EventStream() - require.EqualValues(t, gotEvent, wantEvent) + require.EqualValues(t, wantEvent, gotEvent) t.Logf("received adjudicator event for ch %x, version: %v", wantEvent.ID(), wantEvent.Version()) } diff --git a/watcher/watcher.go b/watcher/watcher.go index ce528bae0..59efd518f 100644 --- a/watcher/watcher.go +++ b/watcher/watcher.go @@ -39,10 +39,10 @@ type ( // AdjudicatorSub and StatesSub. The client must not publish states after // this. Watcher interface { - StartWatchingLedgerChannel(context.Context, channel.SignedState) (StatesPub, AdjudicatorSub, error) + StartWatchingLedgerChannel(ctx context.Context, signedState channel.SignedState) (StatesPub, AdjudicatorSub, error) StartWatchingSubChannel(_ context.Context, parent channel.ID, _ channel.SignedState) ( StatesPub, AdjudicatorSub, error) - StopWatching(context.Context, channel.ID) error + StopWatching(ctx context.Context, id channel.ID) error } // StatesPub is the interface used to send newer off-chain states from the @@ -58,7 +58,7 @@ type ( // stop watching or when there is an error. After the client requests the // watcher to stop watching, method `Publish` must not be called anymore. StatesPub interface { - Publish(context.Context, channel.Transaction) error + Publish(ctx context.Context, tx channel.Transaction) error } // AdjudicatorSub is the interface used to relay the adjudicator events diff --git a/wire/account.go b/wire/account.go index 5b8abb25b..0c537db57 100644 --- a/wire/account.go +++ b/wire/account.go @@ -67,7 +67,8 @@ func (m *AuthResponseMsg) Encode(w io.Writer) error { } // Decode decodes an AuthResponseMsg from an io.Reader. -func (m *AuthResponseMsg) Decode(r io.Reader) (err error) { +func (m *AuthResponseMsg) Decode(r io.Reader) error { + var err error // Read the signature size first if m.SignatureSize, err = decodeUint32(r); err != nil { return err diff --git a/wire/address.go b/wire/address.go index de48ab1ec..43986e216 100644 --- a/wire/address.go +++ b/wire/address.go @@ -37,10 +37,10 @@ type Address interface { // BinaryUnmarshaler unmarshals an address from binary. encoding.BinaryUnmarshaler // Equal returns wether the two addresses are equal. - Equal(Address) bool + Equal(addr Address) bool // Cmp compares the byte representation of two addresses. For `a.Cmp(b)` // returns -1 if a < b, 0 if a == b, 1 if a > b. - Cmp(Address) int + Cmp(addr Address) int // Verify verifies a message signature. // It returns an error if the signature is invalid. Verify(msg []byte, sig []byte) error diff --git a/wire/cache.go b/wire/cache.go index 0810dd335..2fabe70d8 100644 --- a/wire/cache.go +++ b/wire/cache.go @@ -22,12 +22,12 @@ type ( } // A Predicate defines a message filter. - Predicate = func(*Envelope) bool + Predicate = func(env *Envelope) bool // A Cacher has the Cache method to enable caching of messages. Cacher interface { // Cache should enable the caching of messages - Cache(*Predicate) + Cache(pred *Predicate) } ) diff --git a/wire/cache_internal_test.go b/wire/cache_internal_test.go index 055ec4984..07166ff22 100644 --- a/wire/cache_internal_test.go +++ b/wire/cache_internal_test.go @@ -61,7 +61,7 @@ func TestCache(t *testing.T) { c.Release(&isPing) assert.False(c.Put(ping2), "Put into cache with canceled predicate") assert.Equal(2, c.Size()) - assert.Len(c.preds, 0, "internal: Put should have removed canceled predicate") + assert.Empty(c.preds, "internal: Put should have removed canceled predicate") msgs := c.Messages(func(e *Envelope) bool { return e.Msg.Type() == Ping && diff --git a/wire/consumer.go b/wire/consumer.go index 2bfdb4262..908bdea78 100644 --- a/wire/consumer.go +++ b/wire/consumer.go @@ -24,5 +24,5 @@ type Consumer interface { // closed. sync.OnCloser // Put is called by the emitter when relaying a message. - Put(*Envelope) + Put(env *Envelope) } diff --git a/wire/hybridbus_test.go b/wire/hybridbus_test.go index 32d7f6c77..9a8cc43c1 100644 --- a/wire/hybridbus_test.go +++ b/wire/hybridbus_test.go @@ -19,7 +19,7 @@ import ( "github.com/stretchr/testify/require" - . "perun.network/go-perun/wire" + . "perun.network/go-perun/wire" //nolint:revive "perun.network/go-perun/wire/test" ) @@ -41,11 +41,13 @@ func TestHybridBus(t *testing.T) { hybridBus := NewHybridBus(buses...) i := 0 - test.GenericBusTest(t, func(Account) (pub Bus, sub Bus) { + test.GenericBusTest(t, func(Account) (Bus, Bus) { i++ // Split the clients evenly among the sub-buses, and let them publish // over the hybrid bus. - return hybridBus, buses[i%nBuses] + pub := hybridBus + sub := buses[i%nBuses] + return pub, sub }, 16, 10) } diff --git a/wire/localbus_test.go b/wire/localbus_test.go index 971f70123..3e0371231 100644 --- a/wire/localbus_test.go +++ b/wire/localbus_test.go @@ -17,7 +17,7 @@ package wire_test import ( "testing" - . "perun.network/go-perun/wire" + . "perun.network/go-perun/wire" //nolint:revive "perun.network/go-perun/wire/test" ) diff --git a/wire/net/bus.go b/wire/net/bus.go index 90161aad0..84d72fa60 100644 --- a/wire/net/bus.go +++ b/wire/net/bus.go @@ -74,7 +74,8 @@ func (b *Bus) SubscribeClient(c wire.Consumer, addr wire.Address) error { // Publish sends an envelope to its recipient. Automatically establishes a // communication channel to the recipient using the bus' dialer. Only returns // when the context is aborted or the envelope was sent successfully. -func (b *Bus) Publish(ctx context.Context, e *wire.Envelope) (err error) { +func (b *Bus) Publish(ctx context.Context, e *wire.Envelope) error { + var err error for attempt := 1; attempt <= PublishAttempts; attempt++ { log.Tracef("Bus.Publish attempt: %d/%d", attempt, PublishAttempts) var ep *Endpoint @@ -98,7 +99,7 @@ func (b *Bus) Publish(ctx context.Context, e *wire.Envelope) (err error) { case <-time.After(PublishCooldown): } } - return + return err } // Close closes the bus and terminates its goroutines. diff --git a/wire/net/conn.go b/wire/net/conn.go index a6ee84307..d23206992 100644 --- a/wire/net/conn.go +++ b/wire/net/conn.go @@ -26,7 +26,7 @@ type Conn interface { Recv() (*wire.Envelope, error) // Send sends an envelope to the peer. // If an error occurs, the connection must close itself. - Send(*wire.Envelope) error + Send(env *wire.Envelope) error // Close closes the connection and aborts any ongoing Send() and Recv() // calls. // diff --git a/wire/net/endpoint.go b/wire/net/endpoint.go index 5b0b5d8b1..14eb8d7dc 100644 --- a/wire/net/endpoint.go +++ b/wire/net/endpoint.go @@ -91,7 +91,7 @@ func (p *Endpoint) Send(ctx context.Context, e *wire.Envelope) error { } // Close closes the Endpoint's connection. A closed Endpoint is no longer usable. -func (p *Endpoint) Close() (err error) { +func (p *Endpoint) Close() error { return p.conn.Close() } diff --git a/wire/net/endpoint_internal_test.go b/wire/net/endpoint_internal_test.go index d1ca3f691..ad8635e2b 100644 --- a/wire/net/endpoint_internal_test.go +++ b/wire/net/endpoint_internal_test.go @@ -23,6 +23,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" _ "perun.network/go-perun/backend/sim" // backend init "perun.network/go-perun/wire" @@ -53,7 +54,7 @@ func makeSetup(rng *rand.Rand) *setup { } // Dial simulates creating a connection to a. -func (s *setup) Dial(ctx context.Context, addr wire.Address, _ wire.EnvelopeSerializer) (Conn, error) { +func (s *setup) Dial(_ context.Context, addr wire.Address, _ wire.EnvelopeSerializer) (Conn, error) { s.mutex.RLock() defer s.mutex.RUnlock() @@ -64,16 +65,14 @@ func (s *setup) Dial(ctx context.Context, addr wire.Address, _ wire.EnvelopeSeri // a: Alice's end, b: Bob's end. a, b := newPipeConnPair() - //nolint:gocritic if addr.Equal(s.alice.endpoint.Address) { // Dialing Bob? s.bob.Registry.addEndpoint(s.bob.endpoint.Address, b, true) // Bob accepts connection. return a, nil } else if addr.Equal(s.bob.endpoint.Address) { // Dialing Alice? s.alice.Registry.addEndpoint(s.alice.endpoint.Address, a, true) // Alice accepts connection. return b, nil - } else { - return nil, errors.New("unknown peer") } + return nil, errors.New("unknown peer") } func (s *setup) Close() error { @@ -119,14 +118,14 @@ func TestEndpoint_Close(t *testing.T) { found := s.alice.Registry.find(bobAddr) assert.Equal(t, s.alice.endpoint, found) // Close Alice's connection to Bob. - assert.NoError(t, s.alice.endpoint.Close(), "closing a peer once must succeed") - assert.Error(t, s.alice.endpoint.Close(), "closing peers twice must fail") + require.NoError(t, s.alice.endpoint.Close(), "closing a peer once must succeed") + require.Error(t, s.alice.endpoint.Close(), "closing peers twice must fail") // Sending over closed peers (not connections) must fail. err := s.alice.endpoint.Send( context.Background(), wiretest.NewRandomEnvelope(test.Prng(t), wire.NewPingMsg())) - assert.Error(t, err, "sending to bob must fail", err) + require.Error(t, err, "sending to bob must fail", err) } func TestEndpoint_Send_ImmediateAbort(t *testing.T) { @@ -138,10 +137,10 @@ func TestEndpoint_Send_ImmediateAbort(t *testing.T) { cancel() // This operation should abort immediately. - assert.Error(t, s.alice.endpoint.Send(ctx, + require.Error(t, s.alice.endpoint.Send(ctx, wiretest.NewRandomEnvelope(test.Prng(t), wire.NewPingMsg()))) - assert.Error(t, s.alice.endpoint.Close(), + require.Error(t, s.alice.endpoint.Close(), "peer must be closed after failed sending") } @@ -154,9 +153,9 @@ func TestEndpoint_Send_Timeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() - assert.Error(t, p.Send(ctx, wiretest.NewRandomEnvelope(rng, wire.NewPingMsg())), + require.Error(t, p.Send(ctx, wiretest.NewRandomEnvelope(rng, wire.NewPingMsg())), "Send() must timeout on blocked connection") - assert.Error(t, p.Close(), + require.Error(t, p.Close(), "peer must be closed after failed Send()") } @@ -173,9 +172,9 @@ func TestEndpoint_Send_Timeout_Mutex_TryLockCtx(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() - assert.Error(t, p.Send(ctx, wiretest.NewRandomEnvelope(rng, wire.NewPingMsg())), + require.Error(t, p.Send(ctx, wiretest.NewRandomEnvelope(rng, wire.NewPingMsg())), "Send() must timeout on locked mutex") - assert.Error(t, p.Close(), + require.Error(t, p.Close(), "peer must be closed after failed Send()") } @@ -190,7 +189,7 @@ func TestEndpoint_Send_Close(t *testing.T) { p.Close() }() - assert.Error(t, p.Send(context.Background(), wiretest.NewRandomEnvelope(rng, wire.NewPingMsg())), + require.Error(t, p.Send(context.Background(), wiretest.NewRandomEnvelope(rng, wire.NewPingMsg())), "Send() must be aborted by Close()") } @@ -214,5 +213,5 @@ func TestEndpoint_ClosedByRecvLoopOnConnClose(t *testing.T) { conn1.Close() <-eofReceived - assert.Error(t, peer.Close()) + require.Error(t, peer.Close()) } diff --git a/wire/net/endpoint_registry.go b/wire/net/endpoint_registry.go index 149edf1b3..044e8db5c 100644 --- a/wire/net/endpoint_registry.go +++ b/wire/net/endpoint_registry.go @@ -101,9 +101,10 @@ func NewEndpointRegistry( } // Close closes the registry's dialer and all its peers. -func (r *EndpointRegistry) Close() (err error) { +func (r *EndpointRegistry) Close() error { + var err error if err = r.Closer.Close(); err != nil { - return + return err } r.mutex.Lock() @@ -125,7 +126,7 @@ func (r *EndpointRegistry) Close() (err error) { } } - return + return err } // Listen starts listening for incoming connections on the provided listener and @@ -220,7 +221,8 @@ func (r *EndpointRegistry) authenticatedDial( addr wire.Address, de *dialingEndpoint, created bool, -) (ret *Endpoint, _ error) { +) (*Endpoint, error) { + var ret *Endpoint key := wire.Key(addr) // Short cut: another dial for that peer is already in progress. @@ -256,12 +258,12 @@ func (r *EndpointRegistry) authenticatedDial( conn.Close() return nil, errors.WithMessage(err, "ExchangeAddrs failed") } - - return r.addEndpoint(addr, conn, true), nil + ret = r.addEndpoint(addr, conn, true) + return ret, nil } // dialingEndpoint retrieves or creates a dialingEndpoint for the passed address. -func (r *EndpointRegistry) dialingEndpoint(a wire.Address) (_ *dialingEndpoint, created bool) { +func (r *EndpointRegistry) dialingEndpoint(a wire.Address) (*dialingEndpoint, bool) { key := wire.Key(a) entry, ok := r.dialing[key] if !ok { @@ -317,7 +319,7 @@ func (r *EndpointRegistry) addEndpoint(addr wire.Address, conn Conn, dialer bool } // fullEndpoint retrieves or creates a fullEndpoint for the passed address. -func (r *EndpointRegistry) fullEndpoint(addr wire.Address, e *Endpoint) (_ *fullEndpoint, created bool) { +func (r *EndpointRegistry) fullEndpoint(addr wire.Address, e *Endpoint) (*fullEndpoint, bool) { key := wire.Key(addr) r.mutex.Lock() defer r.mutex.Unlock() @@ -332,7 +334,7 @@ func (r *EndpointRegistry) fullEndpoint(addr wire.Address, e *Endpoint) (_ *full // replace sets a new endpoint and resolves ties when both parties dial each // other concurrently. It returns the endpoint that is selected after potential // tie resolving, and whether the supplied endpoint was closed in the process. -func (p *fullEndpoint) replace(newValue *Endpoint, self wire.Address, dialer bool) (updated *Endpoint, closed bool) { +func (p *fullEndpoint) replace(newValue *Endpoint, self wire.Address, dialer bool) (*Endpoint, bool) { // If there was no previous endpoint, just set the new one. wasNil := atomic.CompareAndSwapPointer(&p.endpoint, nil, unsafe.Pointer(newValue)) if wasNil { diff --git a/wire/net/endpoint_registry_external_test.go b/wire/net/endpoint_registry_external_test.go index 486ade7e5..198a86c15 100644 --- a/wire/net/endpoint_registry_external_test.go +++ b/wire/net/endpoint_registry_external_test.go @@ -57,14 +57,14 @@ func TestEndpointRegistry_Get_Pair(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 2*timeout) defer cancel() p, err := dialerReg.Endpoint(ctx, listenerID.Address()) - assert.NoError(err) + require.NoError(err) require.NotNil(p) assert.True(p.Address.Equal(listenerID.Address())) // should allow the listener routine to add the peer to its registry time.Sleep(timeout) p, err = listenerReg.Endpoint(ctx, dialerID.Address()) - assert.NoError(err) + require.NoError(err) require.NotNil(p) assert.True(p.Address.Equal(dialerID.Address())) @@ -107,7 +107,7 @@ func TestEndpointRegistry_Get_Multiple(t *testing.T) { for i := 0; i < N; i++ { go func() { p, err := dialerReg.Endpoint(ctx, listenerID.Address()) - assert.NoError(err) + require.NoError(t, err) //nolint:testifylint if p != nil { assert.True(p.Address.Equal(listenerID.Address())) } @@ -136,7 +136,7 @@ func TestEndpointRegistry_Get_Multiple(t *testing.T) { // should allow the listener routine to add the peer to its registry time.Sleep(timeout) p, err := listenerReg.Endpoint(ctx, dialerID.Address()) - assert.NoError(err) + require.NoError(t, err) assert.NotNil(p) assert.True(p.Address.Equal(dialerID.Address())) assert.Equal(1, listener.NumAccepted()) diff --git a/wire/net/endpoint_registry_internal_test.go b/wire/net/endpoint_registry_internal_test.go index 34160e1e6..2b54760e4 100644 --- a/wire/net/endpoint_registry_internal_test.go +++ b/wire/net/endpoint_registry_internal_test.go @@ -51,7 +51,7 @@ func (d *mockDialer) Close() error { return nil } -func (d *mockDialer) Dial(ctx context.Context, addr wire.Address, _ wire.EnvelopeSerializer) (Conn, error) { +func (d *mockDialer) Dial(ctx context.Context, _ wire.Address, _ wire.EnvelopeSerializer) (Conn, error) { d.mutex.Lock() defer d.mutex.Unlock() @@ -111,6 +111,8 @@ func nilConsumer(wire.Address) wire.Consumer { return nil } // dialed in the background. It also tests that the dialing process combines // with the Listener, so that if a connection to a peer that is still being // dialed comes in, the peer is assigned that connection. +// +//nolint:testify func TestRegistry_Get(t *testing.T) { t.Parallel() rng := test.Prng(t) @@ -128,7 +130,7 @@ func TestRegistry_Get(t *testing.T) { r.endpoints[wire.Key(peerAddr)] = newFullEndpoint(existing) ctxtest.AssertTerminates(t, timeout, func() { p, err := r.Endpoint(context.Background(), peerAddr) - assert.NoError(t, err) + require.NoError(t, err) assert.Same(t, p, existing) }) }) @@ -142,7 +144,7 @@ func TestRegistry_Get(t *testing.T) { dialer.Close() ctxtest.AssertTerminates(t, timeout, func() { p, err := r.Endpoint(context.Background(), peerAddr) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, p) }) @@ -162,9 +164,9 @@ func TestRegistry_Get(t *testing.T) { go ct.Stage("receiver", func(t test.ConcT) { dialer.put(a) _, err := ExchangeAddrsPassive(ctx, peerID, b) - require.NoError(t, err) + require.NoError(t, err) //nolint:testifylint _, err = b.Recv() - require.NoError(t, err) + require.NoError(t, err) //nolint:testifylint }) p, err := r.Endpoint(ctx, peerAddr) require.NoError(t, err) @@ -193,7 +195,7 @@ func TestRegistry_authenticatedDial(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() e, err := r.authenticatedDial(ctx, addr, de, created) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, e) }) @@ -217,7 +219,7 @@ func TestRegistry_authenticatedDial(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() e, err := r.authenticatedDial(ctx, remoteAddr, de, created) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, e) }) @@ -229,11 +231,11 @@ func TestRegistry_authenticatedDial(t *testing.T) { go ct.Stage("passive", func(rt test.ConcT) { d.put(a) _, err := ExchangeAddrsPassive(ctx, wiretest.NewRandomAccount(rng), b) - require.True(rt, IsAuthenticationError(err)) + require.True(rt, IsAuthenticationError(err)) //nolint:testifylint }) de, created := r.dialingEndpoint(remoteAddr) e, err := r.authenticatedDial(ctx, remoteAddr, de, created) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, e) ct.Wait("passive") }) @@ -253,7 +255,7 @@ func TestRegistry_authenticatedDial(t *testing.T) { defer cancel() de, created := r.dialingEndpoint(remoteAddr) e, err := r.authenticatedDial(ctx, remoteAddr, de, created) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, e) }) } @@ -279,7 +281,7 @@ func TestRegistry_setupConn(t *testing.T) { } }() ctxtest.AssertTerminates(t, timeout, func() { - assert.Error(t, r.setupConn(a)) + require.Error(t, r.setupConn(a)) }) }) @@ -296,7 +298,7 @@ func TestRegistry_setupConn(t *testing.T) { r.addEndpoint(remoteID.Address(), newMockConn(), false) ctxtest.AssertTerminates(t, timeout, func() { - assert.NoError(t, r.setupConn(a)) + require.NoError(t, r.setupConn(a)) }) }) @@ -312,7 +314,7 @@ func TestRegistry_setupConn(t *testing.T) { }() ctxtest.AssertTerminates(t, timeout, func() { - assert.NoError(t, r.setupConn(a)) + require.NoError(t, r.setupConn(a)) }) }) } @@ -347,7 +349,7 @@ func TestRegistry_Listen(t *testing.T) { <-time.After(timeout) assert.True(r.Has(remoteAddr)) - assert.NoError(r.Close()) + require.NoError(t, r.Close()) assert.True(l.isClosed(), "closing the registry should close the listener") l2 := newMockListener() @@ -389,7 +391,7 @@ func TestRegistry_Close(t *testing.T) { perunio.Serializer(), ) r.Close() - assert.Error(t, r.Close()) + require.Error(t, r.Close()) }) t.Run("dialer close error", func(t *testing.T) { @@ -402,12 +404,12 @@ func TestRegistry_Close(t *testing.T) { perunio.Serializer(), ) - assert.Error(t, r.Close()) + require.Error(t, r.Close()) }) } // newPipeConnPair creates endpoints that are connected via pipes. -func newPipeConnPair() (a Conn, b Conn) { +func newPipeConnPair() (Conn, Conn) { c0, c1 := net.Pipe() ser := perunio.Serializer() return NewIoConn(c0, ser), NewIoConn(c1, ser) diff --git a/wire/net/exchange_addr.go b/wire/net/exchange_addr.go index f57bb225a..c4ff77dc1 100644 --- a/wire/net/exchange_addr.go +++ b/wire/net/exchange_addr.go @@ -78,9 +78,9 @@ func ExchangeAddrsActive(ctx context.Context, id wire.Account, peer wire.Address var e *wire.Envelope if e, err = conn.Recv(); err != nil { err = errors.WithMessage(err, "receiving message") - } else if _, ok := e.Msg.(*wire.AuthResponseMsg); !ok { + } else if authMsg, ok := e.Msg.(*wire.AuthResponseMsg); !ok { err = errors.Errorf("expected AuthResponse wire msg, got %v", e.Msg.Type()) - } else if check := verifyAddressSignature(peer, e.Msg.(*wire.AuthResponseMsg).Signature); check != nil { + } else if check := verifyAddressSignature(peer, authMsg.Signature); check != nil { err = errors.WithMessage(err, "verifying peer address's signature") } else if !e.Recipient.Equal(id.Address()) && !e.Sender.Equal(peer) { @@ -105,11 +105,11 @@ func ExchangeAddrsPassive(ctx context.Context, id wire.Account, conn Conn) (wire var e *wire.Envelope if e, err = conn.Recv(); err != nil { err = errors.WithMessage(err, "receiving auth message") - } else if _, ok := e.Msg.(*wire.AuthResponseMsg); !ok { + } else if authMsg, ok := e.Msg.(*wire.AuthResponseMsg); !ok { err = errors.Errorf("expected AuthResponse wire msg, got %v", e.Msg.Type()) } else if !e.Recipient.Equal(id.Address()) { err = NewAuthenticationError(e.Sender, e.Recipient, id.Address(), "unmatched response sender or recipient") - } else if err = verifyAddressSignature(e.Sender, e.Msg.(*wire.AuthResponseMsg).Signature); err != nil { + } else if err = verifyAddressSignature(e.Sender, authMsg.Signature); err != nil { err = errors.WithMessage(err, "verifying peer address's signature") } diff --git a/wire/net/exchange_addr_internal_test.go b/wire/net/exchange_addr_internal_test.go index 4abf6f83c..c575ec83d 100644 --- a/wire/net/exchange_addr_internal_test.go +++ b/wire/net/exchange_addr_internal_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire" wiretest "perun.network/go-perun/wire/test" @@ -33,7 +34,7 @@ func TestExchangeAddrs_ConnFail(t *testing.T) { a.Close() addr, err := ExchangeAddrsPassive(context.Background(), wiretest.NewRandomAccount(rng), a) assert.Nil(t, addr) - assert.Error(t, err) + require.Error(t, err) } func TestExchangeAddrs_Success(t *testing.T) { @@ -49,12 +50,12 @@ func TestExchangeAddrs_Success(t *testing.T) { defer conn1.Close() recvAddr0, err := ExchangeAddrsPassive(context.Background(), account1, conn1) - assert.NoError(t, err) + require.NoError(t, err) //nolint:testifylint assert.True(t, recvAddr0.Equal(account0.Address())) }() err := ExchangeAddrsActive(context.Background(), account0, account1.Address(), conn0) - assert.NoError(t, err) + require.NoError(t, err) wg.Wait() } @@ -68,7 +69,7 @@ func TestExchangeAddrs_Timeout(t *testing.T) { ctxtest.AssertTerminates(t, 2*timeout, func() { addr, err := ExchangeAddrsPassive(ctx, wiretest.NewRandomAccount(rng), a) assert.Nil(t, addr) - assert.Error(t, err) + require.Error(t, err) }) } @@ -79,6 +80,6 @@ func TestExchangeAddrs_BogusMsg(t *testing.T) { conn.recvQueue <- wiretest.NewRandomEnvelope(rng, wire.NewPingMsg()) addr, err := ExchangeAddrsPassive(context.Background(), acc, conn) - assert.Error(t, err, "ExchangeAddrs should error when peer sends a non-AuthResponseMsg") + require.Error(t, err, "ExchangeAddrs should error when peer sends a non-AuthResponseMsg") assert.Nil(t, addr) } diff --git a/wire/net/simple/address.go b/wire/net/simple/address.go index a5e02b505..81c5cfaff 100644 --- a/wire/net/simple/address.go +++ b/wire/net/simple/address.go @@ -30,7 +30,6 @@ import ( type Address struct { Name string PublicKey *rsa.PublicKey // Public key for verifying signatures - } var _ wire.Address = (*Address)(nil) @@ -112,6 +111,8 @@ func (a *Address) Equal(b wire.Address) bool { } // Cmp compares the byte representation of two addresses. +// +//nolint:mirror func (a *Address) Cmp(b wire.Address) int { bTyped, ok := b.(*Address) if !ok { diff --git a/wire/net/simple/dialer_internal_test.go b/wire/net/simple/dialer_internal_test.go index a493eb9fb..b2436f2c9 100644 --- a/wire/net/simple/dialer_internal_test.go +++ b/wire/net/simple/dialer_internal_test.go @@ -22,12 +22,12 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/pem" - "fmt" "math/big" "net" "testing" "time" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -43,7 +43,7 @@ func TestNewTCPDialer(t *testing.T) { MinVersion: tls.VersionTLS12, // Set minimum TLS version to TLS 1.2 } d := NewTCPDialer(0, tlsConfig) - assert.Equal(t, d.network, "tcp") + assert.Equal(t, "tcp", d.network) } func TestNewUnixDialer(t *testing.T) { @@ -51,7 +51,7 @@ func TestNewUnixDialer(t *testing.T) { MinVersion: tls.VersionTLS12, // Set minimum TLS version to TLS 1.2 } d := NewUnixDialer(0, tlsConfig) - assert.Equal(t, d.network, "unix") + assert.Equal(t, "unix", d.network) } func TestDialer_Register(t *testing.T) { @@ -70,7 +70,7 @@ func TestDialer_Register(t *testing.T) { host, ok := d.host(key) assert.True(t, ok) - assert.Equal(t, host, "host") + assert.Equal(t, "host", host) } func TestDialer_Dial(t *testing.T) { @@ -103,21 +103,21 @@ func TestDialer_Dial(t *testing.T) { ct := test.NewConcurrent(t) go ct.Stage("accept", func(rt test.ConcT) { conn, err := l.Accept(ser) - assert.NoError(t, err) - require.NotNil(rt, conn) + require.NoError(t, err) //nolint: testifylint + require.NotNil(rt, conn) //nolint: testifylint re, err := conn.Recv() - assert.NoError(t, err) + require.NoError(t, err) //nolint: testifylint assert.Equal(t, re, e) }) ct.Stage("dial", func(rt test.ConcT) { ctxtest.AssertTerminates(t, timeout, func() { conn, err := d.Dial(context.Background(), laddr, ser) - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(rt, conn) - assert.NoError(t, conn.Send(e)) + require.NoError(t, conn.Send(e)) }) }) @@ -130,7 +130,7 @@ func TestDialer_Dial(t *testing.T) { ctxtest.AssertTerminates(t, timeout, func() { conn, err := d.Dial(ctx, laddr, ser) assert.Nil(t, conn) - assert.Error(t, err) + require.Error(t, err) }) }) @@ -141,7 +141,7 @@ func TestDialer_Dial(t *testing.T) { ctxtest.AssertTerminates(t, timeout, func() { conn, err := d.Dial(context.Background(), noHostAddr, ser) assert.Nil(t, conn) - assert.Error(t, err) + require.Error(t, err) }) }) @@ -149,7 +149,7 @@ func TestDialer_Dial(t *testing.T) { ctxtest.AssertTerminates(t, timeout, func() { unkownAddr := NewRandomAddress(rng) conn, err := d.Dial(context.Background(), unkownAddr, ser) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, conn) }) }) @@ -247,7 +247,7 @@ func generateSelfSignedCertConfigs(commonName string, sans []string) (*tls.Confi serverCertPool := x509.NewCertPool() ok := serverCertPool.AppendCertsFromPEM(clientCertPEM) if !ok { - return nil, nil, fmt.Errorf("failed to parse root certificate") + return nil, nil, errors.New("failed to parse root certificate") } // Create the server-side TLS configuration @@ -261,7 +261,7 @@ func generateSelfSignedCertConfigs(commonName string, sans []string) (*tls.Confi clientCertPool := x509.NewCertPool() ok = clientCertPool.AppendCertsFromPEM(serverCertPEM) if !ok { - return nil, nil, fmt.Errorf("failed to parse root certificate") + return nil, nil, errors.New("failed to parse root certificate") } // Create the client-side TLS configuration diff --git a/wire/net/simple/listener_internal_test.go b/wire/net/simple/listener_internal_test.go index b5cc7258b..29acfe908 100644 --- a/wire/net/simple/listener_internal_test.go +++ b/wire/net/simple/listener_internal_test.go @@ -31,6 +31,8 @@ const addr = "0.0.0.0:1337" // serverKey and serverCert are generated with the following commands: // openssl ecparam -genkey -name prime256v1 -out server.key // openssl req -new -x509 -key server.key -out server.pem -days 3650. +// +//nolint:gosec const testServerKey = `-----BEGIN EC PARAMETERS----- BggqhkjOPQMBBw== -----END EC PARAMETERS----- @@ -38,7 +40,7 @@ BggqhkjOPQMBBw== MHcCAQEEIHg+g2unjA5BkDtXSN9ShN7kbPlbCcqcYdDu+QeV8XWuoAoGCCqGSM49 AwEHoUQDQgAEcZpodWh3SEs5Hh3rrEiu1LZOYSaNIWO34MgRxvqwz1FMpLxNlx0G cSqrxhPubawptX5MSr02ft32kfOlYbaF5Q== ------END EC PRIVATE KEY----- +-----END EC PRIVATE KEY----- ` const testServerCert = `-----BEGIN CERTIFICATE----- @@ -90,8 +92,8 @@ func TestListener_Close(t *testing.T) { t.Run("double close", func(t *testing.T) { l, err := NewTCPListener(addr, tlsConfig) require.NoError(t, err) - assert.NoError(t, l.Close(), "first close must not return error") - assert.Error(t, l.Close(), "second close must result in error") + require.NoError(t, l.Close(), "first close must not return error") + require.Error(t, l.Close(), "second close must result in error") }) } @@ -104,14 +106,14 @@ func TestNewListener(t *testing.T) { } t.Run("happy", func(t *testing.T) { l, err := NewTCPListener(addr, tlsConfig) - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, l) l.Close() }) t.Run("sad", func(t *testing.T) { l, err := NewTCPListener("not an address", tlsConfig) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, l) }) @@ -152,7 +154,7 @@ func TestListener_Accept(t *testing.T) { test.AssertTerminates(t, timeout, func() { conn, err := l.Accept(ser) assert.Nil(t, conn) - assert.Error(t, err) + require.Error(t, err) }) }) } diff --git a/wire/net/simple/simple_exchange_addr_test.go b/wire/net/simple/simple_exchange_addr_test.go index 4dbd13646..4d20da69e 100644 --- a/wire/net/simple/simple_exchange_addr_test.go +++ b/wire/net/simple/simple_exchange_addr_test.go @@ -27,6 +27,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire" wirenet "perun.network/go-perun/wire/net" @@ -44,7 +45,7 @@ func TestExchangeAddrs_ConnFail(t *testing.T) { a.Close() addr, err := wirenet.ExchangeAddrsPassive(context.Background(), wiretest.NewRandomAccount(rng), a) assert.Nil(t, addr) - assert.Error(t, err) + require.Error(t, err) } func TestExchangeAddrs_Success(t *testing.T) { @@ -60,12 +61,12 @@ func TestExchangeAddrs_Success(t *testing.T) { defer conn1.Close() recvAddr0, err := wirenet.ExchangeAddrsPassive(context.Background(), account1, conn1) - assert.NoError(t, err) + require.NoError(t, err) //nolint:testifylint assert.True(t, recvAddr0.Equal(account0.Address())) }() err := wirenet.ExchangeAddrsActive(context.Background(), account0, account1.Address(), conn0) - assert.NoError(t, err) + require.NoError(t, err) wg.Wait() } @@ -79,7 +80,7 @@ func TestExchangeAddrs_Timeout(t *testing.T) { ctxtest.AssertTerminates(t, 20*timeout, func() { addr, err := wirenet.ExchangeAddrsPassive(ctx, wiretest.NewRandomAccount(rng), a) assert.Nil(t, addr) - assert.Error(t, err) + require.Error(t, err) }) } @@ -90,12 +91,12 @@ func TestExchangeAddrs_BogusMsg(t *testing.T) { conn.recvQueue <- newRandomEnvelope(rng, wire.NewPingMsg()) addr, err := wirenet.ExchangeAddrsPassive(context.Background(), acc, conn) - assert.Error(t, err, "ExchangeAddrs should error when peer sends a non-AuthResponseMsg") + require.Error(t, err, "ExchangeAddrs should error when peer sends a non-AuthResponseMsg") assert.Nil(t, addr) } // newPipeConnPair creates endpoints that are connected via pipes. -func newPipeConnPair() (a wirenet.Conn, b wirenet.Conn) { +func newPipeConnPair() (wirenet.Conn, wirenet.Conn) { c0, c1 := net.Pipe() ser := perunio.Serializer() return wirenet.NewIoConn(c0, ser), wirenet.NewIoConn(c1, ser) diff --git a/wire/net/test/connhub.go b/wire/net/test/connhub.go index 1c958b78c..b3d3c9c2a 100644 --- a/wire/net/test/connhub.go +++ b/wire/net/test/connhub.go @@ -75,10 +75,10 @@ func (h *ConnHub) NewNetDialer() *Dialer { } // Close closes the ConnHub and all its listeners. -func (h *ConnHub) Close() (err error) { +func (h *ConnHub) Close() error { h.mutex.Lock() defer h.mutex.Unlock() - + var err error if err := h.Closer.Close(); err != nil { return errors.WithMessage(err, "ConnHub already closed") } @@ -95,5 +95,5 @@ func (h *ConnHub) Close() (err error) { } } - return + return err } diff --git a/wire/net/test/connhub_internal_test.go b/wire/net/test/connhub_internal_test.go index f061c765d..f8e730482 100644 --- a/wire/net/test/connhub_internal_test.go +++ b/wire/net/test/connhub_internal_test.go @@ -46,19 +46,19 @@ func TestConnHub_Create(t *testing.T) { go ctxtest.AssertTerminates(t, timeout, func() { ct.Stage("accept", func(rt pkgtest.ConcT) { conn, err := l.Accept(ser) - assert.NoError(err) - require.NotNil(rt, conn) - assert.NoError(conn.Send(wiretest.NewRandomEnvelope(rng, wire.NewPingMsg()))) + require.NoError(t, err) //nolint: testifylint + require.NotNil(rt, conn) //nolint: testifylint + require.NoError(t, conn.Send(wiretest.NewRandomEnvelope(rng, wire.NewPingMsg()))) //nolint: testifylint }) }) ctxtest.AssertTerminates(t, timeout, func() { ct.Stage("dial", func(rt pkgtest.ConcT) { conn, err := d.Dial(context.Background(), addr, ser) - assert.NoError(err) + require.NoError(t, err) require.NotNil(rt, conn) m, err := conn.Recv() - assert.NoError(err) + require.NoError(t, err) assert.IsType(wire.NewPingMsg(), m.Msg) }) }) @@ -87,7 +87,7 @@ func TestConnHub_Create(t *testing.T) { ctxtest.AssertTerminates(t, timeout, func() { conn, err := d.Dial(context.Background(), wiretest.NewRandomAddress(rng), ser) assert.Nil(conn) - assert.Error(err) + require.Error(t, err) }) }) @@ -110,7 +110,7 @@ func TestConnHub_Close(t *testing.T) { var c ConnHub l := c.NewNetListener(wiretest.NewRandomAddress(rng)) - assert.NoError(c.Close()) + require.NoError(t, c.Close()) assert.True(l.IsClosed()) }) @@ -122,8 +122,8 @@ func TestConnHub_Close(t *testing.T) { l2 := NewNetListener() l2.Close() err := c.insert(wiretest.NewRandomAccount(rng).Address(), l2) - assert.NoError(err) - assert.Error(c.Close()) + require.NoError(t, err) + require.Error(t, c.Close()) assert.True(l.IsClosed()) }) @@ -135,7 +135,7 @@ func TestConnHub_Close(t *testing.T) { d2 := &Dialer{} d2.Close() c.dialers.insert(d2) - assert.Error(c.Close()) + require.Error(t, c.Close()) assert.True(d.IsClosed()) }) @@ -143,9 +143,9 @@ func TestConnHub_Close(t *testing.T) { assert := assert.New(t) var c ConnHub - assert.NoError(c.Close()) + require.NoError(t, c.Close()) err := c.Close() - assert.Error(err) + require.Error(t, err) assert.True(sync.IsAlreadyClosedError(err)) }) } diff --git a/wire/net/test/dialer_internal_test.go b/wire/net/test/dialer_internal_test.go index e24748916..4748c8d49 100644 --- a/wire/net/test/dialer_internal_test.go +++ b/wire/net/test/dialer_internal_test.go @@ -19,6 +19,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" perunio "perun.network/go-perun/wire/perunio/serializer" "perun.network/go-perun/wire/test" @@ -35,7 +36,7 @@ func TestDialer_Dial(t *testing.T) { conn, err := d.Dial(context.Background(), test.NewRandomAddress(rng), ser) assert.Nil(t, conn) - assert.Error(t, err) + require.Error(t, err) }) // Cancelling the context must result in error. @@ -45,12 +46,12 @@ func TestDialer_Dial(t *testing.T) { cancel() conn, err := d.Dial(ctx, test.NewRandomAddress(rng), ser) assert.Nil(t, conn) - assert.Error(t, err) + require.Error(t, err) }) } func TestDialer_Close(t *testing.T) { var d Dialer - assert.NoError(t, d.Close()) - assert.Error(t, d.Close()) + require.NoError(t, d.Close()) + require.Error(t, d.Close()) } diff --git a/wire/net/test/dialerlist_internal_test.go b/wire/net/test/dialerlist_internal_test.go index 41093a8c1..24577b8b5 100644 --- a/wire/net/test/dialerlist_internal_test.go +++ b/wire/net/test/dialerlist_internal_test.go @@ -40,12 +40,12 @@ func TestDialerList_erase(t *testing.T) { assert := assert.New(t) var l dialerList - assert.Error(l.erase(&Dialer{})) + require.Error(t, l.erase(&Dialer{})) d := &Dialer{} l.insert(d) - assert.NoError(l.erase(d)) - assert.Len(l.entries, 0) - assert.Error(l.erase(d)) + require.NoError(t, l.erase(d)) + assert.Empty(l.entries) + require.Error(t, l.erase(d)) } func TestDialerList_clear(t *testing.T) { @@ -54,6 +54,6 @@ func TestDialerList_clear(t *testing.T) { d := &Dialer{} l.insert(d) - assert.Equal(l.clear(), []*Dialer{d}) - assert.Len(l.entries, 0) + assert.Equal([]*Dialer{d}, l.clear()) + assert.Empty(l.entries) } diff --git a/wire/net/test/listener_internal_test.go b/wire/net/test/listener_internal_test.go index 87b253cd3..25008dc3c 100644 --- a/wire/net/test/listener_internal_test.go +++ b/wire/net/test/listener_internal_test.go @@ -20,6 +20,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire" wirenet "perun.network/go-perun/wire/net" @@ -49,7 +50,7 @@ func TestListener_Accept_Put(t *testing.T) { ctxtest.AssertTerminates(t, timeout, func() { conn, err := l.Accept(perunio.Serializer()) - assert.NoError(t, err, "Accept must not fail") + require.NoError(t, err, "Accept must not fail") //nolint:testifylint assert.Same(t, connection, conn, "Accept must receive connection from Put") assert.Equal(t, 1, l.NumAccepted(), @@ -75,7 +76,7 @@ func TestListener_Accept_Close(t *testing.T) { l.Close() ctxtest.AssertTerminates(t, timeout, func() { conn, err := l.Accept(ser) - assert.Error(t, err, "Accept must fail") + require.Error(t, err, "Accept must fail") assert.Nil(t, conn) assert.Zero(t, l.NumAccepted()) }) @@ -90,7 +91,7 @@ func TestListener_Accept_Close(t *testing.T) { ctxtest.AssertTerminates(t, 2*timeout, func() { conn, err := l.Accept(ser) - assert.Error(t, err, "Accept must fail") + require.Error(t, err, "Accept must fail") assert.Nil(t, conn) assert.Zero(t, l.NumAccepted()) }) @@ -121,7 +122,7 @@ func TestListener_Put(t *testing.T) { // Accept() must always fail when closed. conn, err := l.Accept(perunio.Serializer()) assert.Nil(t, conn) - assert.Error(t, err) + require.Error(t, err) assert.Zero(t, l.NumAccepted()) }) }) @@ -130,7 +131,7 @@ func TestListener_Put(t *testing.T) { func TestListener_Close(t *testing.T) { l := NewNetListener() assert.False(t, l.IsClosed()) - assert.NoError(t, l.Close()) + require.NoError(t, l.Close()) assert.True(t, l.IsClosed()) - assert.Error(t, l.Close()) + require.Error(t, l.Close()) } diff --git a/wire/net/test/listenermap_internal_test.go b/wire/net/test/listenermap_internal_test.go index 05eff932e..ae14810a0 100644 --- a/wire/net/test/listenermap_internal_test.go +++ b/wire/net/test/listenermap_internal_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire/test" pkgtest "polycry.pt/poly-go/test" @@ -56,7 +57,7 @@ func TestListenerMap_insert(t *testing.T) { m := listenerMap{} for i := 0; i < 10; i++ { key := test.NewRandomAddress(rng) - assert.NoError(t, m.insert(key, NewNetListener())) + require.NoError(t, m.insert(key, NewNetListener())) _, ok := m.find(key) assert.True(t, ok) } @@ -65,8 +66,8 @@ func TestListenerMap_insert(t *testing.T) { t.Run("double insert", func(t *testing.T) { m := listenerMap{} key := test.NewRandomAddress(rng) - assert.NoError(t, m.insert(key, NewNetListener())) - assert.Error(t, m.insert(key, NewNetListener())) + require.NoError(t, m.insert(key, NewNetListener())) + require.Error(t, m.insert(key, NewNetListener())) }) } @@ -77,8 +78,8 @@ func TestListenerMap_erase(t *testing.T) { m := listenerMap{} for i := 0; i < 10; i++ { key := test.NewRandomAddress(rng) - assert.NoError(t, m.insert(key, NewNetListener())) - assert.NoError(t, m.erase(key)) + require.NoError(t, m.insert(key, NewNetListener())) + require.NoError(t, m.erase(key)) _, ok := m.find(key) assert.False(t, ok) } @@ -86,6 +87,6 @@ func TestListenerMap_erase(t *testing.T) { t.Run("erase nonexistent", func(t *testing.T) { m := listenerMap{} - assert.Error(t, m.erase(test.NewRandomAddress(rng))) + require.Error(t, m.erase(test.NewRandomAddress(rng))) }) } diff --git a/wire/net/test/pipeconn.go b/wire/net/test/pipeconn.go index bd95f36d1..ca670fa8c 100644 --- a/wire/net/test/pipeconn.go +++ b/wire/net/test/pipeconn.go @@ -32,19 +32,21 @@ type Conn struct { } // Send sends an envelope. -func (c *Conn) Send(e *wire.Envelope) (err error) { +func (c *Conn) Send(e *wire.Envelope) error { + var err error if err = c.conn.Send(e); err != nil { c.Close() } - return + return err } // Recv receives an envelope. -func (c *Conn) Recv() (e *wire.Envelope, err error) { - if e, err = c.conn.Recv(); err != nil { +func (c *Conn) Recv() (*wire.Envelope, error) { + e, err := c.conn.Recv() + if err != nil { c.Close() } - return + return e, err } // Close closes the Conn. @@ -61,7 +63,7 @@ func (c *Conn) IsClosed() bool { } // NewTestConnPair creates endpoints that are connected via pipes. -func NewTestConnPair() (a wirenet.Conn, b wirenet.Conn) { +func NewTestConnPair() (wirenet.Conn, wirenet.Conn) { closed := new(atomic.Bool) c0, c1 := net.Pipe() ser := perunio.Serializer() diff --git a/wire/perunio/bigint_external_test.go b/wire/perunio/bigint_external_test.go index 4850cd693..c95c1343f 100644 --- a/wire/perunio/bigint_external_test.go +++ b/wire/perunio/bigint_external_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire/perunio" peruniotest "perun.network/go-perun/wire/perunio/test" ) @@ -39,14 +40,14 @@ func TestBigInt_DecodeZeroLength(t *testing.T) { buf := bytes.NewBuffer([]byte{0}) var result perunio.BigInt - assert.NoError(result.Decode(buf), "decoding zero length big.Int should work") + require.NoError(t, result.Decode(buf), "decoding zero length big.Int should work") assert.Zero(new(big.Int).Cmp(result.Int), "decoding zero length should set big.Int to 0") } func TestBigInt_DecodeToExisting(t *testing.T) { x, buf := new(big.Int), bytes.NewBuffer([]byte{1, 42}) wx := perunio.BigInt{Int: x} - assert.NoError(t, wx.Decode(buf), "decoding {1, 42} into big.Int should work") + require.NoError(t, wx.Decode(buf), "decoding {1, 42} into big.Int should work") assert.Zero(t, big.NewInt(42).Cmp(x), "decoding {1, 42} into big.Int should result in 42") } @@ -65,7 +66,7 @@ func TestBigInt_Invalid(t *testing.T) { tooBig := perunio.BigInt{Int: big.NewInt(1)} tooBig.Lsh(tooBig.Int, pos) - a.Error(tooBig.Encode(buf), "encoding too big big.Int should fail") + require.Error(t, tooBig.Encode(buf), "encoding too big big.Int should fail") a.Zero(buf.Len(), "encoding too big big.Int should not have written anything") buf.Reset() // in case above test failed } @@ -77,12 +78,12 @@ func TestBigInt_Invalid(t *testing.T) { } var result perunio.BigInt - a.Error(result.Decode(buf), "decoding of an integer that is too big should fail") + require.Error(t, result.Decode(buf), "decoding of an integer that is too big should fail") buf.Reset() // Test not sending value, only length buf.WriteByte(1) - a.Error(result.Decode(buf), "decoding after sender only sent length should fail") + require.Error(t, result.Decode(buf), "decoding after sender only sent length should fail") a.Panics(func() { _ = perunio.BigInt{Int: nil}.Encode(buf) }, "encoding nil big.Int failed to panic") } diff --git a/wire/perunio/byteslice_external_test.go b/wire/perunio/byteslice_external_test.go index c90ee62c9..c6b47ead4 100644 --- a/wire/perunio/byteslice_external_test.go +++ b/wire/perunio/byteslice_external_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire/perunio" peruniotest "perun.network/go-perun/wire/perunio/test" @@ -40,13 +41,13 @@ func TestStutter(t *testing.T) { go func() { for _, v := range values { _, err := w.Write([]byte{v}) - assert.NoError(t, err) + require.NoError(t, err) //nolint:testifylint } }() var decodedValue perunio.ByteSlice = make([]byte, len(values)) ctxtest.AssertTerminatesQuickly(t, func() { - assert.NoError(t, decodedValue.Decode(r)) + require.NoError(t, decodedValue.Decode(r)) }) for i, v := range values { assert.Equal(t, decodedValue[i], v) @@ -70,7 +71,7 @@ func testByteSlices(t *testing.T, serial ...perunio.ByteSlice) { d := make([]byte, len(v)) dest := perunio.ByteSlice(d) - a.NoError(dest.Decode(r), "failed to decode element") + require.NoError(t, dest.Decode(r), "failed to decode element") if !reflect.DeepEqual(v, dest) { t.Errorf("encoding and decoding the %dth element (%T) resulted in different value: %v, %v", i, v, reflect.ValueOf(v).Elem(), dest) diff --git a/wire/perunio/serialize.go b/wire/perunio/serialize.go index 259e0e805..c0ab7670e 100644 --- a/wire/perunio/serialize.go +++ b/wire/perunio/serialize.go @@ -31,7 +31,8 @@ var byteOrder = binary.LittleEndian // Encode encodes multiple primitive values into a writer. // All passed values must be copies, not references. -func Encode(writer io.Writer, values ...interface{}) (err error) { //nolint: cyclop // by design, +func Encode(writer io.Writer, values ...interface{}) error { //nolint: cyclop // by design, + var err error // encode function has many paths. Hence, we accept a higher complexity here. for i, value := range values { switch v := value.(type) { @@ -86,7 +87,8 @@ func Encode(writer io.Writer, values ...interface{}) (err error) { //nolint: cyc // Decode decodes multiple primitive values from a reader. // All passed values must be references, not copies. -func Decode(reader io.Reader, values ...interface{}) (err error) { +func Decode(reader io.Reader, values ...interface{}) error { + var err error for i, value := range values { switch v := value.(type) { case *bool, *int8, *uint8, *int16, *uint16, *int32, *uint32, *int64, *uint64: diff --git a/wire/perunio/serializer.go b/wire/perunio/serializer.go index ce160b9e5..f2304f8ee 100644 --- a/wire/perunio/serializer.go +++ b/wire/perunio/serializer.go @@ -29,13 +29,13 @@ type ( Encoder interface { // Encode writes itself to a stream. // If the stream fails, the underlying error is returned. - Encode(io.Writer) error + Encode(writer io.Writer) error } // A Decoder can decode itself from a stream. Decoder interface { // Decode reads an object from a stream. // If the stream fails, the underlying error is returned. - Decode(io.Reader) error + Decode(reader io.Reader) error } ) diff --git a/wire/perunio/serializer/serializer.go b/wire/perunio/serializer/serializer.go index ff86ae6d1..751fba81e 100644 --- a/wire/perunio/serializer/serializer.go +++ b/wire/perunio/serializer/serializer.go @@ -38,8 +38,9 @@ func (serializer) Encode(w io.Writer, env *wire.Envelope) error { } // Decode decodes an envelope from the wire using perunio encoding format. -func (serializer) Decode(r io.Reader) (env *wire.Envelope, err error) { - env = &wire.Envelope{} +func (serializer) Decode(r io.Reader) (*wire.Envelope, error) { + var err error + env := &wire.Envelope{} env.Sender = wire.NewAddress() if err = perunio.Decode(r, env.Sender); err != nil { return env, errors.WithMessage(err, "decoding sender address") diff --git a/wire/perunio/string_internal_test.go b/wire/perunio/string_internal_test.go index 4310ec9a8..6544a9f37 100644 --- a/wire/perunio/string_internal_test.go +++ b/wire/perunio/string_internal_test.go @@ -33,7 +33,7 @@ func TestEncodeDecodeString(t *testing.T) { rng.Read(uint8buf) rng.Read(uint16buf) - t.Run("valid strings", func(t *testing.T) { + t.Run("valid strings", func(_ *testing.T) { ss := []string{"", "a", "perun", string(uint8buf), string(uint16buf)} for _, s := range ss { @@ -42,21 +42,21 @@ func TestEncodeDecodeString(t *testing.T) { go func() { defer close(done) defer w.Close() - assert.NoError(encodeString(w, s)) + require.NoError(t, encodeString(w, s)) //nolint:testifylint }() var d string - assert.NoError(decodeString(r, &d)) + require.NoError(t, decodeString(r, &d)) r.Close() assert.Equal(s, d) <-done } }) - t.Run("too long string", func(t *testing.T) { + t.Run("too long string", func(_ *testing.T) { tooLong := string(append(uint16buf, 42)) //nolint: makezero var buf bytes.Buffer - assert.Error(encodeString(&buf, tooLong)) + require.Error(t, encodeString(&buf, tooLong)) assert.Zero(buf.Len(), "nothing should have been written to the stream") }) @@ -67,7 +67,7 @@ func TestEncodeDecodeString(t *testing.T) { buf.Write(make([]byte, 8)) // 8 bytes missing var d string - assert.Error(decodeString(&buf, &d)) + require.Error(t, decodeString(&buf, &d)) assert.Zero(buf.Len(), "buffer should be exhausted") }) } diff --git a/wire/perunio/test/msgtest.go b/wire/perunio/test/msgtest.go index 86a55cb54..39e0b9188 100644 --- a/wire/perunio/test/msgtest.go +++ b/wire/perunio/test/msgtest.go @@ -37,7 +37,8 @@ func (e *serializableEnvelope) Encode(writer io.Writer) error { return serializer.Encode(writer, e.env) } -func (e *serializableEnvelope) Decode(reader io.Reader) (err error) { +func (e *serializableEnvelope) Decode(reader io.Reader) error { + var err error e.env, err = serializer.Decode(reader) return err } diff --git a/wire/perunio/wire_internal_test.go b/wire/perunio/wire_internal_test.go index 4d9640a46..baec69f72 100644 --- a/wire/perunio/wire_internal_test.go +++ b/wire/perunio/wire_internal_test.go @@ -23,6 +23,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" polytest "polycry.pt/poly-go/test" ) @@ -54,7 +55,6 @@ func TestWrongTypes(t *testing.T) { } func TestEncodeDecode(t *testing.T) { - a := assert.New(t) r, w := io.Pipe() longInt, _ := new(big.Int).SetString("12345671823897123798901234561234567890", 16) @@ -85,7 +85,7 @@ func TestEncodeDecode(t *testing.T) { } go func() { - a.NoError(Encode(w, values...), "failed to encode values") + require.NoError(t, Encode(w, values...), "failed to encode values") //nolint:testifylint }() d := make([]interface{}, len(values)) @@ -103,7 +103,7 @@ func TestEncodeDecode(t *testing.T) { } } - a.Nil(Decode(r, d...), "failed to decode values") + require.NoError(t, Decode(r, d...), "failed to decode values") for i, v := range values { if !reflect.DeepEqual(reflect.ValueOf(d[i]).Elem().Interface(), v) { diff --git a/wire/protobuf/controlmsgs.go b/wire/protobuf/controlmsgs.go index 2fb1675f9..6a7fd3309 100644 --- a/wire/protobuf/controlmsgs.go +++ b/wire/protobuf/controlmsgs.go @@ -21,20 +21,23 @@ import ( ) func fromPingMsg(msg *wire.PingMsg) *Envelope_PingMsg { - protoMsg := &PingMsg{} - protoMsg.Created = msg.Created.UnixNano() + protoMsg := &PingMsg{ + Created: msg.Created.UnixNano(), + } return &Envelope_PingMsg{protoMsg} } func fromPongMsg(msg *wire.PongMsg) *Envelope_PongMsg { - protoMsg := &PongMsg{} - protoMsg.Created = msg.Created.UnixNano() + protoMsg := &PongMsg{ + Created: msg.Created.UnixNano(), + } return &Envelope_PongMsg{protoMsg} } func fromShutdownMsg(msg *wire.ShutdownMsg) *Envelope_ShutdownMsg { - protoMsg := &ShutdownMsg{} - protoMsg.Reason = msg.Reason + protoMsg := &ShutdownMsg{ + Reason: msg.Reason, + } return &Envelope_ShutdownMsg{protoMsg} } @@ -45,28 +48,32 @@ func fromAuthResponseMsg(msg *wire.AuthResponseMsg) *Envelope_AuthResponseMsg { return &Envelope_AuthResponseMsg{protoMsg} } -func toPingMsg(protoMsg *Envelope_PingMsg) (msg *wire.PingMsg) { - msg = &wire.PingMsg{} - msg.Created = time.Unix(0, protoMsg.PingMsg.Created) +//nolint:forbidigo +func toPingMsg(protoMsg *Envelope_PingMsg) *wire.PingMsg { + msg := &wire.PingMsg{} + msg.Created = time.Unix(0, protoMsg.PingMsg.GetCreated()) return msg } -func toPongMsg(protoEnvMsg *Envelope_PongMsg) (msg *wire.PongMsg) { - msg = &wire.PongMsg{} - msg.Created = time.Unix(0, protoEnvMsg.PongMsg.Created) +//nolint:forbidigo +func toPongMsg(protoEnvMsg *Envelope_PongMsg) *wire.PongMsg { + msg := &wire.PongMsg{} + msg.Created = time.Unix(0, protoEnvMsg.PongMsg.GetCreated()) return msg } -func toShutdownMsg(protoEnvMsg *Envelope_ShutdownMsg) (msg *wire.ShutdownMsg) { - msg = &wire.ShutdownMsg{} - msg.Reason = protoEnvMsg.ShutdownMsg.Reason +//nolint:forbidigo +func toShutdownMsg(protoEnvMsg *Envelope_ShutdownMsg) *wire.ShutdownMsg { + msg := &wire.ShutdownMsg{} + msg.Reason = protoEnvMsg.ShutdownMsg.GetReason() return msg } -func toAuthResponseMsg(protoEnvMsg *Envelope_AuthResponseMsg) (msg *wire.AuthResponseMsg) { - msg = &wire.AuthResponseMsg{} - msg.SignatureSize = protoEnvMsg.AuthResponseMsg.SignatureSize - msg.Signature = protoEnvMsg.AuthResponseMsg.Signature +//nolint:forbidigo +func toAuthResponseMsg(protoEnvMsg *Envelope_AuthResponseMsg) *wire.AuthResponseMsg { + msg := &wire.AuthResponseMsg{} + msg.SignatureSize = protoEnvMsg.AuthResponseMsg.GetSignatureSize() + msg.Signature = protoEnvMsg.AuthResponseMsg.GetSignature() if msg.Signature == nil { msg.Signature = make([]byte, msg.SignatureSize) } diff --git a/wire/protobuf/proposalmsgs.go b/wire/protobuf/proposalmsgs.go index af1b6b44b..116f2953c 100644 --- a/wire/protobuf/proposalmsgs.go +++ b/wire/protobuf/proposalmsgs.go @@ -28,100 +28,107 @@ import ( // ToLedgerChannelProposalMsg converts a protobuf Envelope_LedgerChannelProposalMsg to a client // LedgerChannelProposalMsg. -func ToLedgerChannelProposalMsg(protoEnvMsg *Envelope_LedgerChannelProposalMsg) (msg *client.LedgerChannelProposalMsg, err error) { +func ToLedgerChannelProposalMsg(protoEnvMsg *Envelope_LedgerChannelProposalMsg) (*client.LedgerChannelProposalMsg, error) { protoMsg := protoEnvMsg.LedgerChannelProposalMsg - msg = &client.LedgerChannelProposalMsg{} - msg.BaseChannelProposal, err = ToBaseChannelProposal(protoMsg.BaseChannelProposal) + var err error + msg := &client.LedgerChannelProposalMsg{} + msg.BaseChannelProposal, err = ToBaseChannelProposal(protoMsg.GetBaseChannelProposal()) if err != nil { return nil, err } - msg.Participant, err = ToWalletAddr(protoMsg.Participant) + msg.Participant, err = ToWalletAddr(protoMsg.GetParticipant()) if err != nil { return nil, errors.WithMessage(err, "participant address") } - msg.Peers, err = ToWireAddrs(protoMsg.Peers) + msg.Peers, err = ToWireAddrs(protoMsg.GetPeers()) return msg, errors.WithMessage(err, "peers") } // ToSubChannelProposalMsg converts a protobuf Envelope_SubChannelProposalMsg to a client SubChannelProposalMsg. -func ToSubChannelProposalMsg(protoEnvMsg *Envelope_SubChannelProposalMsg) (msg *client.SubChannelProposalMsg, err error) { +func ToSubChannelProposalMsg(protoEnvMsg *Envelope_SubChannelProposalMsg) (*client.SubChannelProposalMsg, error) { protoMsg := protoEnvMsg.SubChannelProposalMsg - msg = &client.SubChannelProposalMsg{} - copy(msg.Parent[:], protoMsg.Parent) - msg.BaseChannelProposal, err = ToBaseChannelProposal(protoMsg.BaseChannelProposal) + var err error + msg := &client.SubChannelProposalMsg{} + copy(msg.Parent[:], protoMsg.GetParent()) + msg.BaseChannelProposal, err = ToBaseChannelProposal(protoMsg.GetBaseChannelProposal()) return msg, err } // ToVirtualChannelProposalMsg converts a protobuf Envelope_VirtualChannelProposalMsg to a client // VirtualChannelProposalMsg. -func ToVirtualChannelProposalMsg(protoEnvMsg *Envelope_VirtualChannelProposalMsg) (msg *client.VirtualChannelProposalMsg, err error) { +// +//nolint:forbidigo +func ToVirtualChannelProposalMsg(protoEnvMsg *Envelope_VirtualChannelProposalMsg) (*client.VirtualChannelProposalMsg, error) { protoMsg := protoEnvMsg.VirtualChannelProposalMsg - msg = &client.VirtualChannelProposalMsg{} - msg.BaseChannelProposal, err = ToBaseChannelProposal(protoMsg.BaseChannelProposal) + var err error + msg := &client.VirtualChannelProposalMsg{} + msg.BaseChannelProposal, err = ToBaseChannelProposal(protoMsg.GetBaseChannelProposal()) if err != nil { return nil, err } - msg.Proposer, err = ToWalletAddr(protoMsg.Proposer) + msg.Proposer, err = ToWalletAddr(protoMsg.GetProposer()) if err != nil { return nil, errors.WithMessage(err, "proposer") } - msg.Parents = make([]channel.ID, len(protoMsg.Parents)) - for i := range protoMsg.Parents { - copy(msg.Parents[i][:], protoMsg.Parents[i]) + msg.Parents = make([]channel.ID, len(protoMsg.GetParents())) + for i := range protoMsg.GetParents() { + copy(msg.Parents[i][:], protoMsg.GetParents()[i]) } - msg.IndexMaps = make([][]channel.Index, len(protoMsg.IndexMaps)) - for i := range protoMsg.IndexMaps { - msg.IndexMaps[i], err = ToIndexMap(protoMsg.IndexMaps[i].IndexMap) + msg.IndexMaps = make([][]channel.Index, len(protoMsg.GetIndexMaps())) + for i := range protoMsg.GetIndexMaps() { + msg.IndexMaps[i], err = ToIndexMap(protoMsg.GetIndexMaps()[i].GetIndexMap()) if err != nil { return nil, err } } - msg.Peers, err = ToWireAddrs(protoMsg.Peers) + msg.Peers, err = ToWireAddrs(protoMsg.GetPeers()) return msg, errors.WithMessage(err, "peers") } // ToLedgerChannelProposalAccMsg converts a protobuf Envelope_LedgerChannelProposalAccMsg to a client // LedgerChannelProposalAccMsg. -func ToLedgerChannelProposalAccMsg(protoEnvMsg *Envelope_LedgerChannelProposalAccMsg) (msg *client.LedgerChannelProposalAccMsg, err error) { +func ToLedgerChannelProposalAccMsg(protoEnvMsg *Envelope_LedgerChannelProposalAccMsg) (*client.LedgerChannelProposalAccMsg, error) { protoMsg := protoEnvMsg.LedgerChannelProposalAccMsg - msg = &client.LedgerChannelProposalAccMsg{} - msg.BaseChannelProposalAcc = ToBaseChannelProposalAcc(protoMsg.BaseChannelProposalAcc) - msg.Participant, err = ToWalletAddr(protoMsg.Participant) + var err error + msg := &client.LedgerChannelProposalAccMsg{} + msg.BaseChannelProposalAcc = ToBaseChannelProposalAcc(protoMsg.GetBaseChannelProposalAcc()) + msg.Participant, err = ToWalletAddr(protoMsg.GetParticipant()) return msg, errors.WithMessage(err, "participant") } // ToSubChannelProposalAccMsg converts a protobuf Envelope_SubChannelProposalAccMsg to a client // SubChannelProposalAccMsg. -func ToSubChannelProposalAccMsg(protoEnvMsg *Envelope_SubChannelProposalAccMsg) (msg *client.SubChannelProposalAccMsg) { +func ToSubChannelProposalAccMsg(protoEnvMsg *Envelope_SubChannelProposalAccMsg) *client.SubChannelProposalAccMsg { protoMsg := protoEnvMsg.SubChannelProposalAccMsg - msg = &client.SubChannelProposalAccMsg{} - msg.BaseChannelProposalAcc = ToBaseChannelProposalAcc(protoMsg.BaseChannelProposalAcc) + msg := &client.SubChannelProposalAccMsg{} + msg.BaseChannelProposalAcc = ToBaseChannelProposalAcc(protoMsg.GetBaseChannelProposalAcc()) return msg } // ToVirtualChannelProposalAccMsg converts a protobuf Envelope_VirtualChannelProposalAccMsg to a client // VirtualChannelProposalAccMsg. -func ToVirtualChannelProposalAccMsg(protoEnvMsg *Envelope_VirtualChannelProposalAccMsg) (msg *client.VirtualChannelProposalAccMsg, err error) { +func ToVirtualChannelProposalAccMsg(protoEnvMsg *Envelope_VirtualChannelProposalAccMsg) (*client.VirtualChannelProposalAccMsg, error) { protoMsg := protoEnvMsg.VirtualChannelProposalAccMsg - msg = &client.VirtualChannelProposalAccMsg{} - msg.BaseChannelProposalAcc = ToBaseChannelProposalAcc(protoMsg.BaseChannelProposalAcc) - msg.Responder, err = ToWalletAddr(protoMsg.Responder) + var err error + msg := &client.VirtualChannelProposalAccMsg{} + msg.BaseChannelProposalAcc = ToBaseChannelProposalAcc(protoMsg.GetBaseChannelProposalAcc()) + msg.Responder, err = ToWalletAddr(protoMsg.GetResponder()) return msg, errors.WithMessage(err, "responder") } // ToChannelProposalRejMsg converts a protobuf Envelope_ChannelProposalRejMsg to a client ChannelProposalRejMsg. -func ToChannelProposalRejMsg(protoEnvMsg *Envelope_ChannelProposalRejMsg) (msg *client.ChannelProposalRejMsg) { +func ToChannelProposalRejMsg(protoEnvMsg *Envelope_ChannelProposalRejMsg) *client.ChannelProposalRejMsg { protoMsg := protoEnvMsg.ChannelProposalRejMsg - msg = &client.ChannelProposalRejMsg{} - copy(msg.ProposalID[:], protoMsg.ProposalId) - msg.Reason = protoMsg.Reason + msg := &client.ChannelProposalRejMsg{} + copy(msg.ProposalID[:], protoMsg.GetProposalId()) + msg.Reason = protoMsg.GetReason() return msg } @@ -158,37 +165,41 @@ func ToWireAddrs(protoAddrs [][]byte) ([]wire.Address, error) { } // ToBaseChannelProposal converts a protobuf BaseChannelProposal to a client BaseChannelProposal. -func ToBaseChannelProposal(protoProp *BaseChannelProposal) (prop client.BaseChannelProposal, err error) { - prop.ChallengeDuration = protoProp.ChallengeDuration - copy(prop.ProposalID[:], protoProp.ProposalId) - copy(prop.NonceShare[:], protoProp.NonceShare) - prop.InitBals, err = ToAllocation(protoProp.InitBals) +func ToBaseChannelProposal(protoProp *BaseChannelProposal) (client.BaseChannelProposal, error) { + var prop client.BaseChannelProposal + var err error + prop.ChallengeDuration = protoProp.GetChallengeDuration() + copy(prop.ProposalID[:], protoProp.GetProposalId()) + copy(prop.NonceShare[:], protoProp.GetNonceShare()) + prop.InitBals, err = ToAllocation(protoProp.GetInitBals()) if err != nil { return prop, errors.WithMessage(err, "init bals") } - prop.FundingAgreement = ToBalances(protoProp.FundingAgreement) + prop.FundingAgreement = ToBalances(protoProp.GetFundingAgreement()) if err != nil { return prop, errors.WithMessage(err, "funding agreement") } - prop.App, prop.InitData, err = ToAppAndData(protoProp.App, protoProp.InitData) + prop.App, prop.InitData, err = ToAppAndData(protoProp.GetApp(), protoProp.GetInitData()) return prop, err } // ToBaseChannelProposalAcc converts a protobuf BaseChannelProposalAcc to a client BaseChannelProposalAcc. -func ToBaseChannelProposalAcc(protoPropAcc *BaseChannelProposalAcc) (propAcc client.BaseChannelProposalAcc) { - copy(propAcc.ProposalID[:], protoPropAcc.ProposalId) - copy(propAcc.NonceShare[:], protoPropAcc.NonceShare) - return +func ToBaseChannelProposalAcc(protoPropAcc *BaseChannelProposalAcc) client.BaseChannelProposalAcc { + var propAcc client.BaseChannelProposalAcc + copy(propAcc.ProposalID[:], protoPropAcc.GetProposalId()) + copy(propAcc.NonceShare[:], protoPropAcc.GetNonceShare()) + return propAcc } // ToApp converts a protobuf app to a channel.App. -func ToApp(protoApp []byte) (app channel.App, err error) { +func ToApp(protoApp []byte) (channel.App, error) { + var app channel.App if len(protoApp) == 0 { app = channel.NoApp() return app, nil } appDef := channel.NewAppID() - err = appDef.UnmarshalBinary(protoApp) + err := appDef.UnmarshalBinary(protoApp) if err != nil { return app, err } @@ -197,80 +208,86 @@ func ToApp(protoApp []byte) (app channel.App, err error) { } // ToAppAndData converts protobuf app and data to a channel.App and channel.Data. -func ToAppAndData(protoApp, protoData []byte) (app channel.App, data channel.Data, err error) { +func ToAppAndData(protoApp, protoData []byte) (channel.App, channel.Data, error) { + var app channel.App + var data channel.Data if len(protoApp) == 0 { app = channel.NoApp() data = channel.NoData() return app, data, nil } appDef := channel.NewAppID() - err = appDef.UnmarshalBinary(protoApp) + err := appDef.UnmarshalBinary(protoApp) if err != nil { return nil, nil, err } app, err = channel.Resolve(appDef) if err != nil { - return + return app, data, err } data = app.NewData() return app, data, data.UnmarshalBinary(protoData) } // ToAllocation converts a protobuf allocation to a channel.Allocation. -func ToAllocation(protoAlloc *Allocation) (alloc *channel.Allocation, err error) { - alloc = &channel.Allocation{} - alloc.Assets = make([]channel.Asset, len(protoAlloc.Assets)) - for i := range protoAlloc.Assets { +func ToAllocation(protoAlloc *Allocation) (*channel.Allocation, error) { + var err error + alloc := &channel.Allocation{} + alloc.Assets = make([]channel.Asset, len(protoAlloc.GetAssets())) + for i := range protoAlloc.GetAssets() { alloc.Assets[i] = channel.NewAsset() - err = alloc.Assets[i].UnmarshalBinary(protoAlloc.Assets[i]) + err = alloc.Assets[i].UnmarshalBinary(protoAlloc.GetAssets()[i]) if err != nil { return nil, errors.WithMessagef(err, "%d'th asset", i) } } - alloc.Locked = make([]channel.SubAlloc, len(protoAlloc.Locked)) - for i := range protoAlloc.Locked { - alloc.Locked[i], err = ToSubAlloc(protoAlloc.Locked[i]) + alloc.Locked = make([]channel.SubAlloc, len(protoAlloc.GetLocked())) + for i := range protoAlloc.GetLocked() { + alloc.Locked[i], err = ToSubAlloc(protoAlloc.GetLocked()[i]) if err != nil { return nil, errors.WithMessagef(err, "%d'th sub alloc", i) } } - alloc.Balances = ToBalances(protoAlloc.Balances) + alloc.Balances = ToBalances(protoAlloc.GetBalances()) return alloc, nil } // ToBalances converts a protobuf Balances to a channel.Balances. -func ToBalances(protoBalances *Balances) (balances channel.Balances) { - balances = make([][]channel.Bal, len(protoBalances.Balances)) - for i := range protoBalances.Balances { - balances[i] = ToBalance(protoBalances.Balances[i]) +func ToBalances(protoBalances *Balances) channel.Balances { + balances := make([][]channel.Bal, len(protoBalances.GetBalances())) + for i := range protoBalances.GetBalances() { + balances[i] = ToBalance(protoBalances.GetBalances()[i]) } return balances } // ToBalance converts a protobuf Balance to a channel.Bal. -func ToBalance(protoBalance *Balance) (balance []channel.Bal) { - balance = make([]channel.Bal, len(protoBalance.Balance)) - for j := range protoBalance.Balance { - balance[j] = new(big.Int).SetBytes(protoBalance.Balance[j]) +func ToBalance(protoBalance *Balance) []channel.Bal { + balance := make([]channel.Bal, len(protoBalance.GetBalance())) + for j := range protoBalance.GetBalance() { + balance[j] = new(big.Int).SetBytes(protoBalance.GetBalance()[j]) } return balance } // ToSubAlloc converts a protobuf SubAlloc to a channel.SubAlloc. -func ToSubAlloc(protoSubAlloc *SubAlloc) (subAlloc channel.SubAlloc, err error) { - subAlloc = channel.SubAlloc{} - subAlloc.Bals = ToBalance(protoSubAlloc.Bals) - if len(protoSubAlloc.Id) != len(subAlloc.ID) { +// +//nolint:forbidigo +func ToSubAlloc(protoSubAlloc *SubAlloc) (channel.SubAlloc, error) { + var err error + subAlloc := channel.SubAlloc{} + subAlloc.Bals = ToBalance(protoSubAlloc.GetBals()) + if len(protoSubAlloc.GetId()) != len(subAlloc.ID) { return subAlloc, errors.New("sub alloc id has incorrect length") } - copy(subAlloc.ID[:], protoSubAlloc.Id) - subAlloc.IndexMap, err = ToIndexMap(protoSubAlloc.IndexMap.IndexMap) + copy(subAlloc.ID[:], protoSubAlloc.GetId()) + subAlloc.IndexMap, err = ToIndexMap(protoSubAlloc.GetIndexMap().GetIndexMap()) return subAlloc, err } // ToIndexMap converts a protobuf IndexMap to a channel.IndexMap. -func ToIndexMap(protoIndexMap []uint32) (indexMap []channel.Index, err error) { - indexMap = make([]channel.Index, len(protoIndexMap)) +func ToIndexMap(protoIndexMap []uint32) ([]channel.Index, error) { + indexMap := make([]channel.Index, len(protoIndexMap)) for i := range protoIndexMap { if protoIndexMap[i] > math.MaxUint16 { return nil, fmt.Errorf("%d'th index is invalid", i) //nolint:goerr113 // We do not want to define this as constant error. @@ -282,7 +299,8 @@ func ToIndexMap(protoIndexMap []uint32) (indexMap []channel.Index, err error) { // FromLedgerChannelProposalMsg converts a client LedgerChannelProposalMsg to a protobuf // Envelope_LedgerChannelProposalMsg. -func FromLedgerChannelProposalMsg(msg *client.LedgerChannelProposalMsg) (_ *Envelope_LedgerChannelProposalMsg, err error) { +func FromLedgerChannelProposalMsg(msg *client.LedgerChannelProposalMsg) (*Envelope_LedgerChannelProposalMsg, error) { + var err error protoMsg := &LedgerChannelProposalMsg{} protoMsg.BaseChannelProposal, err = FromBaseChannelProposal(msg.BaseChannelProposal) if err != nil { @@ -297,7 +315,10 @@ func FromLedgerChannelProposalMsg(msg *client.LedgerChannelProposalMsg) (_ *Enve } // FromSubChannelProposalMsg converts a client SubChannelProposalMsg to a protobuf Envelope_SubChannelProposalMsg. -func FromSubChannelProposalMsg(msg *client.SubChannelProposalMsg) (_ *Envelope_SubChannelProposalMsg, err error) { +// +//nolint:protogetter +func FromSubChannelProposalMsg(msg *client.SubChannelProposalMsg) (*Envelope_SubChannelProposalMsg, error) { + var err error protoMsg := &SubChannelProposalMsg{} protoMsg.Parent = make([]byte, len(msg.Parent)) copy(protoMsg.Parent, msg.Parent[:]) @@ -307,7 +328,10 @@ func FromSubChannelProposalMsg(msg *client.SubChannelProposalMsg) (_ *Envelope_S // FromVirtualChannelProposalMsg converts a client VirtualChannelProposalMsg to a protobuf // Envelope_VirtualChannelProposalMsg. -func FromVirtualChannelProposalMsg(msg *client.VirtualChannelProposalMsg) (_ *Envelope_VirtualChannelProposalMsg, err error) { +// +//nolint:protogetter +func FromVirtualChannelProposalMsg(msg *client.VirtualChannelProposalMsg) (*Envelope_VirtualChannelProposalMsg, error) { + var err error protoMsg := &VirtualChannelProposalMsg{} protoMsg.BaseChannelProposal, err = FromBaseChannelProposal(msg.BaseChannelProposal) if err != nil { @@ -332,7 +356,8 @@ func FromVirtualChannelProposalMsg(msg *client.VirtualChannelProposalMsg) (_ *En // FromLedgerChannelProposalAccMsg converts a client LedgerChannelProposalAccMsg to a protobuf // Envelope_LedgerChannelProposalAccMsg. -func FromLedgerChannelProposalAccMsg(msg *client.LedgerChannelProposalAccMsg) (_ *Envelope_LedgerChannelProposalAccMsg, err error) { +func FromLedgerChannelProposalAccMsg(msg *client.LedgerChannelProposalAccMsg) (*Envelope_LedgerChannelProposalAccMsg, error) { + var err error protoMsg := &LedgerChannelProposalAccMsg{} protoMsg.BaseChannelProposalAcc = FromBaseChannelProposalAcc(msg.BaseChannelProposalAcc) protoMsg.Participant, err = FromWalletAddr(msg.Participant) @@ -341,7 +366,7 @@ func FromLedgerChannelProposalAccMsg(msg *client.LedgerChannelProposalAccMsg) (_ // FromSubChannelProposalAccMsg converts a client SubChannelProposalAccMsg to a protobuf // Envelope_SubChannelProposalAccMsg. -func FromSubChannelProposalAccMsg(msg *client.SubChannelProposalAccMsg) (_ *Envelope_SubChannelProposalAccMsg) { +func FromSubChannelProposalAccMsg(msg *client.SubChannelProposalAccMsg) *Envelope_SubChannelProposalAccMsg { protoMsg := &SubChannelProposalAccMsg{} protoMsg.BaseChannelProposalAcc = FromBaseChannelProposalAcc(msg.BaseChannelProposalAcc) return &Envelope_SubChannelProposalAccMsg{protoMsg} @@ -349,7 +374,8 @@ func FromSubChannelProposalAccMsg(msg *client.SubChannelProposalAccMsg) (_ *Enve // FromVirtualChannelProposalAccMsg converts a client VirtualChannelProposalAccMsg to a protobuf // Envelope_VirtualChannelProposalAccMsg. -func FromVirtualChannelProposalAccMsg(msg *client.VirtualChannelProposalAccMsg) (_ *Envelope_VirtualChannelProposalAccMsg, err error) { +func FromVirtualChannelProposalAccMsg(msg *client.VirtualChannelProposalAccMsg) (*Envelope_VirtualChannelProposalAccMsg, error) { + var err error protoMsg := &VirtualChannelProposalAccMsg{} protoMsg.BaseChannelProposalAcc = FromBaseChannelProposalAcc(msg.BaseChannelProposalAcc) protoMsg.Responder, err = FromWalletAddr(msg.Responder) @@ -357,7 +383,9 @@ func FromVirtualChannelProposalAccMsg(msg *client.VirtualChannelProposalAccMsg) } // FromChannelProposalRejMsg converts a client ChannelProposalRejMsg to a protobuf Envelope_ChannelProposalRejMsg. -func FromChannelProposalRejMsg(msg *client.ChannelProposalRejMsg) (_ *Envelope_ChannelProposalRejMsg) { +// +//nolint:protogetter +func FromChannelProposalRejMsg(msg *client.ChannelProposalRejMsg) *Envelope_ChannelProposalRejMsg { protoMsg := &ChannelProposalRejMsg{} protoMsg.ProposalId = make([]byte, len(msg.ProposalID)) copy(protoMsg.ProposalId, msg.ProposalID[:]) @@ -371,8 +399,9 @@ func FromWalletAddr(addr wallet.Address) ([]byte, error) { } // FromWalletAddrs converts a slice of wallet.Address to protobuf wallet addresses. -func FromWalletAddrs(addrs []wallet.Address) (protoAddrs [][]byte, err error) { - protoAddrs = make([][]byte, len(addrs)) +func FromWalletAddrs(addrs []wallet.Address) ([][]byte, error) { + var err error + protoAddrs := make([][]byte, len(addrs)) for i := range addrs { protoAddrs[i], err = addrs[i].MarshalBinary() if err != nil { @@ -383,8 +412,9 @@ func FromWalletAddrs(addrs []wallet.Address) (protoAddrs [][]byte, err error) { } // FromWireAddrs converts a slice of wire.Address to protobuf wire addresses. -func FromWireAddrs(addrs []wire.Address) (protoAddrs [][]byte, err error) { - protoAddrs = make([][]byte, len(addrs)) +func FromWireAddrs(addrs []wire.Address) ([][]byte, error) { + var err error + protoAddrs := make([][]byte, len(addrs)) for i := range addrs { protoAddrs[i], err = addrs[i].MarshalBinary() if err != nil { @@ -395,8 +425,11 @@ func FromWireAddrs(addrs []wire.Address) (protoAddrs [][]byte, err error) { } // FromBaseChannelProposal converts a client BaseChannelProposal to a protobuf BaseChannelProposal. -func FromBaseChannelProposal(prop client.BaseChannelProposal) (protoProp *BaseChannelProposal, err error) { - protoProp = &BaseChannelProposal{} +// +//nolint:protogetter +func FromBaseChannelProposal(prop client.BaseChannelProposal) (*BaseChannelProposal, error) { + protoProp := &BaseChannelProposal{} + var err error protoProp.ProposalId = make([]byte, len(prop.ProposalID)) copy(protoProp.ProposalId, prop.ProposalID[:]) @@ -419,8 +452,10 @@ func FromBaseChannelProposal(prop client.BaseChannelProposal) (protoProp *BaseCh } // FromBaseChannelProposalAcc converts a client BaseChannelProposalAcc to a protobuf BaseChannelProposalAcc. -func FromBaseChannelProposalAcc(propAcc client.BaseChannelProposalAcc) (protoPropAcc *BaseChannelProposalAcc) { - protoPropAcc = &BaseChannelProposalAcc{} +// +//nolint:protogetter +func FromBaseChannelProposalAcc(propAcc client.BaseChannelProposalAcc) *BaseChannelProposalAcc { + protoPropAcc := &BaseChannelProposalAcc{} protoPropAcc.ProposalId = make([]byte, len(propAcc.ProposalID)) protoPropAcc.NonceShare = make([]byte, len(propAcc.NonceShare)) copy(protoPropAcc.ProposalId, propAcc.ProposalID[:]) @@ -429,30 +464,31 @@ func FromBaseChannelProposalAcc(propAcc client.BaseChannelProposalAcc) (protoPro } // FromApp converts a channel.App to a protobuf app. -func FromApp(app channel.App) (protoApp []byte, err error) { +func FromApp(app channel.App) ([]byte, error) { if channel.IsNoApp(app) { return []byte{}, nil } - protoApp, err = app.Def().MarshalBinary() + protoApp, err := app.Def().MarshalBinary() return protoApp, err } // FromAppAndData converts channel.App and channel.Data to protobuf app and data. -func FromAppAndData(app channel.App, data channel.Data) (protoApp, protoData []byte, err error) { +func FromAppAndData(app channel.App, data channel.Data) ([]byte, []byte, error) { if channel.IsNoApp(app) { return []byte{}, []byte{}, nil } - protoApp, err = app.Def().MarshalBinary() + protoApp, err := app.Def().MarshalBinary() if err != nil { return []byte{}, []byte{}, err } - protoData, err = data.MarshalBinary() + protoData, err := data.MarshalBinary() return protoApp, protoData, err } // FromAllocation converts a channel.Allocation to a protobuf Allocation. -func FromAllocation(alloc channel.Allocation) (protoAlloc *Allocation, err error) { - protoAlloc = &Allocation{} +func FromAllocation(alloc channel.Allocation) (*Allocation, error) { + var err error + protoAlloc := &Allocation{} protoAlloc.Assets = make([][]byte, len(alloc.Assets)) for i := range alloc.Assets { protoAlloc.Assets[i], err = alloc.Assets[i].MarshalBinary() @@ -472,10 +508,11 @@ func FromAllocation(alloc channel.Allocation) (protoAlloc *Allocation, err error } // FromBalances converts a channel.Balances to a protobuf Balances. -func FromBalances(balances channel.Balances) (protoBalances *Balances, err error) { - protoBalances = &Balances{ - Balances: make([]*Balance, len(balances)), - } +func FromBalances(balances channel.Balances) (*Balances, error) { + var err error + protoBalances := &Balances{} + protoBalances.Balances = make([]*Balance, len(balances)) + for i := range balances { protoBalances.Balances[i], err = FromBalance(balances[i]) if err != nil { @@ -486,8 +523,8 @@ func FromBalances(balances channel.Balances) (protoBalances *Balances, err error } // FromBalance converts a slice of channel.Bal to a protobuf Balance. -func FromBalance(balance []channel.Bal) (protoBalance *Balance, err error) { - protoBalance = &Balance{ +func FromBalance(balance []channel.Bal) (*Balance, error) { + protoBalance := &Balance{ Balance: make([][]byte, len(balance)), } for i := range balance { @@ -503,8 +540,11 @@ func FromBalance(balance []channel.Bal) (protoBalance *Balance, err error) { } // FromSubAlloc converts a channel.SubAlloc to a protobuf SubAlloc. -func FromSubAlloc(subAlloc channel.SubAlloc) (protoSubAlloc *SubAlloc, err error) { - protoSubAlloc = &SubAlloc{} +// +//nolint:protogetter +func FromSubAlloc(subAlloc channel.SubAlloc) (*SubAlloc, error) { + protoSubAlloc := &SubAlloc{} + var err error protoSubAlloc.Id = make([]byte, len(subAlloc.ID)) copy(protoSubAlloc.Id, subAlloc.ID[:]) protoSubAlloc.IndexMap = &IndexMap{IndexMap: FromIndexMap(subAlloc.IndexMap)} @@ -513,8 +553,8 @@ func FromSubAlloc(subAlloc channel.SubAlloc) (protoSubAlloc *SubAlloc, err error } // FromIndexMap converts a channel.IndexMap to a protobuf index map. -func FromIndexMap(indexMap []channel.Index) (protoIndexMap []uint32) { - protoIndexMap = make([]uint32, len(indexMap)) +func FromIndexMap(indexMap []channel.Index) []uint32 { + protoIndexMap := make([]uint32, len(indexMap)) for i := range indexMap { protoIndexMap[i] = uint32(indexMap[i]) } diff --git a/wire/protobuf/serializer.go b/wire/protobuf/serializer.go index ef18432f8..00b9977f7 100644 --- a/wire/protobuf/serializer.go +++ b/wire/protobuf/serializer.go @@ -34,7 +34,8 @@ func Serializer() wire.EnvelopeSerializer { // Encode encodes an envelope from the reader using protocol buffers // serialization format. -func (serializer) Encode(w io.Writer, env *wire.Envelope) (err error) { //nolint: funlen, cyclop +func (serializer) Encode(w io.Writer, env *wire.Envelope) error { //nolint: funlen, cyclop + var err error protoEnv := &Envelope{} switch msg := env.Msg.(type) { @@ -110,8 +111,8 @@ func writeEnvelope(w io.Writer, env *Envelope) error { // Decode decodes an envelope from the reader, that was encoded using protocol // buffers serialization format. -func (serializer) Decode(r io.Reader) (env *wire.Envelope, err error) { //nolint: funlen, cyclop - env = &wire.Envelope{} +func (serializer) Decode(r io.Reader) (*wire.Envelope, error) { //nolint: funlen, cyclop + env := &wire.Envelope{} protoEnv, err := readEnvelope(r) if err != nil { @@ -123,7 +124,7 @@ func (serializer) Decode(r io.Reader) (env *wire.Envelope, err error) { //nolint return nil, err } - switch protoMsg := protoEnv.Msg.(type) { + switch protoMsg := protoEnv.GetMsg().(type) { case *Envelope_PingMsg: env.Msg = toPingMsg(protoMsg) case *Envelope_PongMsg: @@ -181,10 +182,10 @@ func readEnvelope(r io.Reader) (*Envelope, error) { func unmarshalSenderRecipient(protoEnv *Envelope) (wire.Address, wire.Address, error) { sender := wire.NewAddress() - if err := sender.UnmarshalBinary(protoEnv.Sender); err != nil { + if err := sender.UnmarshalBinary(protoEnv.GetSender()); err != nil { return nil, nil, errors.Wrap(err, "unmarshalling sender address") } recipient := wire.NewAddress() - err := recipient.UnmarshalBinary(protoEnv.Recipient) + err := recipient.UnmarshalBinary(protoEnv.GetRecipient()) return sender, recipient, errors.Wrap(err, "unmarshalling recipient address") } diff --git a/wire/protobuf/syncmsgs.go b/wire/protobuf/syncmsgs.go index fb94a5b19..4f0ded358 100644 --- a/wire/protobuf/syncmsgs.go +++ b/wire/protobuf/syncmsgs.go @@ -19,21 +19,25 @@ import ( "perun.network/go-perun/client" ) -func toChannelSyncMsg(protoEnvMsg *Envelope_ChannelSyncMsg) (msg *client.ChannelSyncMsg, err error) { +//nolint:forbidigo +func toChannelSyncMsg(protoEnvMsg *Envelope_ChannelSyncMsg) (*client.ChannelSyncMsg, error) { protoMsg := protoEnvMsg.ChannelSyncMsg - msg = &client.ChannelSyncMsg{} - msg.Phase = channel.Phase(protoMsg.Phase) - msg.CurrentTX.Sigs = make([][]byte, len(protoMsg.CurrentTx.Sigs)) - for i := range protoMsg.CurrentTx.Sigs { - msg.CurrentTX.Sigs[i] = make([]byte, len(protoMsg.CurrentTx.Sigs[i])) - copy(msg.CurrentTX.Sigs[i], protoMsg.CurrentTx.Sigs[i]) + var err error + msg := &client.ChannelSyncMsg{} + msg.Phase = channel.Phase(protoMsg.GetPhase()) + msg.CurrentTX.Sigs = make([][]byte, len(protoMsg.GetCurrentTx().GetSigs())) + for i := range protoMsg.GetCurrentTx().GetSigs() { + msg.CurrentTX.Sigs[i] = make([]byte, len(protoMsg.GetCurrentTx().GetSigs()[i])) + copy(msg.CurrentTX.Sigs[i], protoMsg.GetCurrentTx().GetSigs()[i]) } - msg.CurrentTX.State, err = ToState(protoMsg.CurrentTx.State) + msg.CurrentTX.State, err = ToState(protoMsg.GetCurrentTx().GetState()) return msg, err } -func fromChannelSyncMsg(msg *client.ChannelSyncMsg) (_ *Envelope_ChannelSyncMsg, err error) { +//nolint:protogetter +func fromChannelSyncMsg(msg *client.ChannelSyncMsg) (*Envelope_ChannelSyncMsg, error) { + var err error protoMsg := &ChannelSyncMsg{} protoMsg.CurrentTx = &Transaction{} diff --git a/wire/protobuf/updatemsgs.go b/wire/protobuf/updatemsgs.go index dc30b00ce..3feac22e8 100644 --- a/wire/protobuf/updatemsgs.go +++ b/wire/protobuf/updatemsgs.go @@ -31,125 +31,135 @@ func ToChannelUpdateMsg(protoEnvMsg *Envelope_ChannelUpdateMsg) (*client.Channel // ToVirtualChannelFundingProposalMsg converts a protobuf Envelope_VirtualChannelFundingProposalMsg to a // client.VirtualChannelFundingProposalMsg. +// +//nolint:forbidigo func ToVirtualChannelFundingProposalMsg(protoEnvMsg *Envelope_VirtualChannelFundingProposalMsg) ( - msg *client.VirtualChannelFundingProposalMsg, - err error, + *client.VirtualChannelFundingProposalMsg, + error, ) { + var err error protoMsg := protoEnvMsg.VirtualChannelFundingProposalMsg - msg = &client.VirtualChannelFundingProposalMsg{} - msg.Initial, err = ToSignedState(protoMsg.Initial) + msg := &client.VirtualChannelFundingProposalMsg{} + msg.Initial, err = ToSignedState(protoMsg.GetInitial()) if err != nil { return nil, errors.WithMessage(err, "initial state") } - msg.IndexMap, err = ToIndexMap(protoMsg.IndexMap.IndexMap) + msg.IndexMap, err = ToIndexMap(protoMsg.GetIndexMap().GetIndexMap()) if err != nil { return nil, err } - msg.ChannelUpdateMsg, err = ToChannelUpdate(protoMsg.ChannelUpdateMsg) + msg.ChannelUpdateMsg, err = ToChannelUpdate(protoMsg.GetChannelUpdateMsg()) return msg, err } // ToVirtualChannelSettlementProposalMsg converts a protobuf Envelope_VirtualChannelSettlementProposalMsg to a // client.VirtualChannelSettlementProposalMsg. func ToVirtualChannelSettlementProposalMsg(protoEnvMsg *Envelope_VirtualChannelSettlementProposalMsg) ( - msg *client.VirtualChannelSettlementProposalMsg, - err error, + *client.VirtualChannelSettlementProposalMsg, + error, ) { protoMsg := protoEnvMsg.VirtualChannelSettlementProposalMsg - msg = &client.VirtualChannelSettlementProposalMsg{} - msg.Final, err = ToSignedState(protoMsg.Final) + msg := &client.VirtualChannelSettlementProposalMsg{} + var err error + msg.Final, err = ToSignedState(protoMsg.GetFinal()) if err != nil { return nil, errors.WithMessage(err, "final state") } - msg.ChannelUpdateMsg, err = ToChannelUpdate(protoMsg.ChannelUpdateMsg) + msg.ChannelUpdateMsg, err = ToChannelUpdate(protoMsg.GetChannelUpdateMsg()) return msg, err } // ToChannelUpdateAccMsg converts a protobuf Envelope_ChannelUpdateAccMsg to a client.ChannelUpdateAccMsg. -func ToChannelUpdateAccMsg(protoEnvMsg *Envelope_ChannelUpdateAccMsg) (msg *client.ChannelUpdateAccMsg) { +func ToChannelUpdateAccMsg(protoEnvMsg *Envelope_ChannelUpdateAccMsg) *client.ChannelUpdateAccMsg { protoMsg := protoEnvMsg.ChannelUpdateAccMsg - msg = &client.ChannelUpdateAccMsg{} - copy(msg.ChannelID[:], protoMsg.ChannelId) - msg.Version = protoMsg.Version - msg.Sig = make([]byte, len(protoMsg.Sig)) - copy(msg.Sig, protoMsg.Sig) + msg := &client.ChannelUpdateAccMsg{} + copy(msg.ChannelID[:], protoMsg.GetChannelId()) + msg.Version = protoMsg.GetVersion() + msg.Sig = make([]byte, len(protoMsg.GetSig())) + copy(msg.Sig, protoMsg.GetSig()) return msg } // ToChannelUpdateRejMsg converts a protobuf Envelope_ChannelUpdateRejMsg to a client.ChannelUpdateRejMsg. -func ToChannelUpdateRejMsg(protoEnvMsg *Envelope_ChannelUpdateRejMsg) (msg *client.ChannelUpdateRejMsg) { +func ToChannelUpdateRejMsg(protoEnvMsg *Envelope_ChannelUpdateRejMsg) *client.ChannelUpdateRejMsg { protoMsg := protoEnvMsg.ChannelUpdateRejMsg - msg = &client.ChannelUpdateRejMsg{} - copy(msg.ChannelID[:], protoMsg.ChannelId) - msg.Version = protoMsg.Version - msg.Reason = protoMsg.Reason + msg := &client.ChannelUpdateRejMsg{} + copy(msg.ChannelID[:], protoMsg.GetChannelId()) + msg.Version = protoMsg.GetVersion() + msg.Reason = protoMsg.GetReason() return msg } // ToChannelUpdate parses protobuf channel updates. -func ToChannelUpdate(protoUpdate *ChannelUpdateMsg) (update client.ChannelUpdateMsg, err error) { - if protoUpdate.ChannelUpdate.ActorIdx > math.MaxUint16 { +// +//nolint:forbidigo +func ToChannelUpdate(protoUpdate *ChannelUpdateMsg) (client.ChannelUpdateMsg, error) { + update := client.ChannelUpdateMsg{} + var err error + if protoUpdate.GetChannelUpdate().GetActorIdx() > math.MaxUint16 { return update, errors.New("actor index is invalid") } - update.ActorIdx = channel.Index(protoUpdate.ChannelUpdate.ActorIdx) - update.Sig = make([]byte, len(protoUpdate.Sig)) - copy(update.Sig, protoUpdate.Sig) - update.State, err = ToState(protoUpdate.ChannelUpdate.State) + update.ActorIdx = channel.Index(protoUpdate.GetChannelUpdate().GetActorIdx()) + update.Sig = make([]byte, len(protoUpdate.GetSig())) + copy(update.Sig, protoUpdate.GetSig()) + update.State, err = ToState(protoUpdate.GetChannelUpdate().GetState()) return update, err } // ToSignedState converts a protobuf SignedState to a channel.SignedState. -func ToSignedState(protoSignedState *SignedState) (signedState channel.SignedState, err error) { - signedState.Params, err = ToParams(protoSignedState.Params) +func ToSignedState(protoSignedState *SignedState) (channel.SignedState, error) { + signedState := channel.SignedState{} + var err error + signedState.Params, err = ToParams(protoSignedState.GetParams()) if err != nil { return signedState, err } - signedState.Sigs = make([][]byte, len(protoSignedState.Sigs)) - for i := range protoSignedState.Sigs { - signedState.Sigs[i] = make([]byte, len(protoSignedState.Sigs[i])) - copy(signedState.Sigs[i], protoSignedState.Sigs[i]) + signedState.Sigs = make([][]byte, len(protoSignedState.GetSigs())) + for i := range protoSignedState.GetSigs() { + signedState.Sigs[i] = make([]byte, len(protoSignedState.GetSigs()[i])) + copy(signedState.Sigs[i], protoSignedState.GetSigs()[i]) } - signedState.State, err = ToState(protoSignedState.State) + signedState.State, err = ToState(protoSignedState.GetState()) return signedState, err } // ToParams converts a protobuf Params to a channel.Params. func ToParams(protoParams *Params) (*channel.Params, error) { - app, err := ToApp(protoParams.App) + app, err := ToApp(protoParams.GetApp()) if err != nil { return nil, err } - parts, err := ToWalletAddrs(protoParams.Parts) + parts, err := ToWalletAddrs(protoParams.GetParts()) if err != nil { return nil, errors.WithMessage(err, "parts") } params := channel.NewParamsUnsafe( - protoParams.ChallengeDuration, + protoParams.GetChallengeDuration(), parts, app, - (new(big.Int)).SetBytes(protoParams.Nonce), - protoParams.LedgerChannel, - protoParams.VirtualChannel) + (new(big.Int)).SetBytes(protoParams.GetNonce()), + protoParams.GetLedgerChannel(), + protoParams.GetVirtualChannel()) return params, nil } // ToState converts a protobuf State to a channel.State. -func ToState(protoState *State) (state *channel.State, err error) { - state = &channel.State{} - copy(state.ID[:], protoState.Id) - state.Version = protoState.Version - state.IsFinal = protoState.IsFinal - allocation, err := ToAllocation(protoState.Allocation) +func ToState(protoState *State) (*channel.State, error) { + state := &channel.State{} + copy(state.ID[:], protoState.GetId()) + state.Version = protoState.GetVersion() + state.IsFinal = protoState.GetIsFinal() + allocation, err := ToAllocation(protoState.GetAllocation()) if err != nil { return nil, errors.WithMessage(err, "allocation") } state.Allocation = *allocation - state.App, state.Data, err = ToAppAndData(protoState.App, protoState.Data) + state.App, state.Data, err = ToAppAndData(protoState.GetApp(), protoState.GetData()) return state, err } @@ -162,9 +172,10 @@ func FromChannelUpdateMsg(msg *client.ChannelUpdateMsg) (*Envelope_ChannelUpdate // FromVirtualChannelFundingProposalMsg converts a client.VirtualChannelFundingProposalMsg to a protobuf // Envelope_VirtualChannelFundingProposalMsg. func FromVirtualChannelFundingProposalMsg(msg *client.VirtualChannelFundingProposalMsg) ( - _ *Envelope_VirtualChannelFundingProposalMsg, - err error, + *Envelope_VirtualChannelFundingProposalMsg, + error, ) { + var err error protoMsg := &VirtualChannelFundingProposalMsg{} protoMsg.Initial, err = FromSignedState(&msg.Initial) @@ -179,9 +190,10 @@ func FromVirtualChannelFundingProposalMsg(msg *client.VirtualChannelFundingPropo // FromVirtualChannelSettlementProposalMsg converts a client.VirtualChannelSettlementProposalMsg to a protobuf // Envelope_VirtualChannelSettlementProposalMsg. func FromVirtualChannelSettlementProposalMsg(msg *client.VirtualChannelSettlementProposalMsg) ( - _ *Envelope_VirtualChannelSettlementProposalMsg, - err error, + *Envelope_VirtualChannelSettlementProposalMsg, + error, ) { + var err error protoMsg := &VirtualChannelSettlementProposalMsg{} protoMsg.ChannelUpdateMsg, err = FromChannelUpdate(&msg.ChannelUpdateMsg) @@ -193,6 +205,8 @@ func FromVirtualChannelSettlementProposalMsg(msg *client.VirtualChannelSettlemen } // FromChannelUpdateAccMsg converts a client.ChannelUpdateAccMsg to a protobuf Envelope_ChannelUpdateAccMsg. +// +//nolint:protogetter func FromChannelUpdateAccMsg(msg *client.ChannelUpdateAccMsg) *Envelope_ChannelUpdateAccMsg { protoMsg := &ChannelUpdateAccMsg{} @@ -205,6 +219,8 @@ func FromChannelUpdateAccMsg(msg *client.ChannelUpdateAccMsg) *Envelope_ChannelU } // FromChannelUpdateRejMsg converts a client.ChannelUpdateRejMsg to a protobuf Envelope_ChannelUpdateRejMsg. +// +//nolint:protogetter func FromChannelUpdateRejMsg(msg *client.ChannelUpdateRejMsg) *Envelope_ChannelUpdateRejMsg { protoMsg := &ChannelUpdateRejMsg{} protoMsg.ChannelId = make([]byte, len(msg.ChannelID)) @@ -215,8 +231,11 @@ func FromChannelUpdateRejMsg(msg *client.ChannelUpdateRejMsg) *Envelope_ChannelU } // FromChannelUpdate converts a client.ChannelUpdateMsg to a protobuf ChannelUpdateMsg. -func FromChannelUpdate(update *client.ChannelUpdateMsg) (protoUpdate *ChannelUpdateMsg, err error) { - protoUpdate = &ChannelUpdateMsg{} +// +//nolint:protogetter +func FromChannelUpdate(update *client.ChannelUpdateMsg) (*ChannelUpdateMsg, error) { + protoUpdate := &ChannelUpdateMsg{} + var err error protoUpdate.ChannelUpdate = &ChannelUpdate{} protoUpdate.ChannelUpdate.ActorIdx = uint32(update.ChannelUpdate.ActorIdx) @@ -227,8 +246,12 @@ func FromChannelUpdate(update *client.ChannelUpdateMsg) (protoUpdate *ChannelUpd } // FromSignedState converts a channel.SignedState to a protobuf SignedState. -func FromSignedState(signedState *channel.SignedState) (protoSignedState *SignedState, err error) { - protoSignedState = &SignedState{} +// +//nolint:protogetter +func FromSignedState(signedState *channel.SignedState) (*SignedState, error) { + protoSignedState := &SignedState{} + var err error + protoSignedState.Sigs = make([][]byte, len(signedState.Sigs)) for i := range signedState.Sigs { protoSignedState.Sigs[i] = make([]byte, len(signedState.Sigs[i])) @@ -243,8 +266,9 @@ func FromSignedState(signedState *channel.SignedState) (protoSignedState *Signed } // FromParams converts a channel.Params to a protobuf Params. -func FromParams(params *channel.Params) (protoParams *Params, err error) { - protoParams = &Params{} +func FromParams(params *channel.Params) (*Params, error) { + protoParams := &Params{} + var err error protoParams.Nonce = params.Nonce.Bytes() protoParams.ChallengeDuration = params.ChallengeDuration @@ -259,11 +283,12 @@ func FromParams(params *channel.Params) (protoParams *Params, err error) { } // FromState converts a channel.State to a protobuf State. -func FromState(state *channel.State) (protoState *State, err error) { - protoState = &State{} +func FromState(state *channel.State) (*State, error) { + protoState := &State{} + var err error protoState.Id = make([]byte, len(state.ID)) - copy(protoState.Id, state.ID[:]) + copy(protoState.GetId(), state.ID[:]) protoState.Version = state.Version protoState.IsFinal = state.IsFinal protoState.Allocation, err = FromAllocation(state.Allocation) diff --git a/wire/pubsub.go b/wire/pubsub.go index a3375bf1a..de9831353 100644 --- a/wire/pubsub.go +++ b/wire/pubsub.go @@ -22,7 +22,7 @@ type ( // Publish should return nil when the message was delivered (outgoing) or is // guaranteed to be eventually delivered (cached), depending on the goal of the // implementation. - Publish(context.Context, *Envelope) error + Publish(ctx context.Context, env *Envelope) error } // A Subscriber allows to subscribe Consumers, which will receive messages @@ -30,6 +30,6 @@ type ( Subscriber interface { // Subscribe adds a Consumer to the subscriptions. // If the Consumer is already subscribed, Subscribe panics. - Subscribe(Consumer, Predicate) error + Subscribe(consumer Consumer, predicate Predicate) error } ) diff --git a/wire/receiver_internal_test.go b/wire/receiver_internal_test.go index acf712453..3f5994acc 100644 --- a/wire/receiver_internal_test.go +++ b/wire/receiver_internal_test.go @@ -20,6 +20,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ctxtest "polycry.pt/poly-go/context/test" ) @@ -32,8 +33,8 @@ func TestReceiver_Close(t *testing.T) { t.Parallel() r := NewReceiver() - assert.NoError(t, r.Close()) - assert.Error(t, r.Close()) + require.NoError(t, r.Close()) + require.Error(t, r.Close()) } func TestReceiver_Next(t *testing.T) { @@ -46,7 +47,7 @@ func TestReceiver_Next(t *testing.T) { r := NewReceiver() go r.Put(e) re, err := r.Next(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.Same(t, e, re) }) }) @@ -58,7 +59,7 @@ func TestReceiver_Next(t *testing.T) { r.Close() re, err := r.Next(context.Background()) assert.Nil(t, re) - assert.Error(t, err) + require.Error(t, err) }) }) @@ -72,7 +73,7 @@ func TestReceiver_Next(t *testing.T) { }() re, err := r.Next(context.Background()) assert.Nil(t, re) - assert.Error(t, err) + require.Error(t, err) }) }) @@ -84,7 +85,7 @@ func TestReceiver_Next(t *testing.T) { cancel() re, err := r.Next(ctx) assert.Nil(t, re) - assert.Error(t, err) + require.Error(t, err) }) }) @@ -96,7 +97,7 @@ func TestReceiver_Next(t *testing.T) { defer cancel() re, err := r.Next(ctx) assert.Nil(t, re) - assert.Error(t, err) + require.Error(t, err) }) }) } diff --git a/wire/relay_internal_test.go b/wire/relay_internal_test.go index 3e6fcd6ae..e3703dcac 100644 --- a/wire/relay_internal_test.go +++ b/wire/relay_internal_test.go @@ -36,13 +36,13 @@ func TestProducer(t *testing.T) { pred := func(*Envelope) bool { return true } assert.True(t, p.isEmpty()) - assert.NoError(t, p.Subscribe(r0, pred)) + require.NoError(t, p.Subscribe(r0, pred)) assert.False(t, p.isEmpty()) - assert.NoError(t, p.Subscribe(r1, pred)) - assert.NoError(t, p.Subscribe(r2, pred)) - assert.Equal(t, len(p.consumers), 3) + require.NoError(t, p.Subscribe(r1, pred)) + require.NoError(t, p.Subscribe(r2, pred)) + assert.Len(t, p.consumers, 3) p.delete(r0) - assert.Equal(t, len(p.consumers), 2) + assert.Len(t, p.consumers, 2) assert.False(t, p.isEmpty()) assert.Panics(t, func() { p.delete(r0) }) } @@ -62,10 +62,10 @@ func TestProducer_SetDefaultMsgHandler(t *testing.T) { func TestProducer_Close(t *testing.T) { p := NewRelay() - assert.NoError(t, p.Close()) + require.NoError(t, p.Close()) err := p.Close() - assert.Error(t, err) + require.Error(t, err) assert.True(t, sync.IsAlreadyClosedError(err)) assert.NotPanics(t, func() { p.delete(nil) }, @@ -77,13 +77,13 @@ func TestProducer_Subscribe(t *testing.T) { t.Run("closed", func(t *testing.T) { p := NewRelay() p.Close() - assert.Error(t, p.Subscribe(NewReceiver(), fn)) + require.Error(t, p.Subscribe(NewReceiver(), fn)) }) t.Run("duplicate", func(t *testing.T) { p := NewRelay() r := NewReceiver() - assert.NoError(t, p.Subscribe(r, fn)) + require.NoError(t, p.Subscribe(r, fn)) assert.Panics(t, func() { p.Subscribe(r, fn) }) //nolint:errcheck }) @@ -92,11 +92,11 @@ func TestProducer_Subscribe(t *testing.T) { r := NewReceiver() r.Close() ctxtest.AssertTerminates(t, timeout, func() { - assert.Error(t, p.Subscribe(r, fn)) + require.Error(t, p.Subscribe(r, fn)) }) time.Sleep(timeout) assert.NotPanics(t, func() { - assert.Error(t, p.Subscribe(r, fn)) + require.Error(t, p.Subscribe(r, fn)) }) }) } @@ -120,7 +120,7 @@ func TestProducer_caching(t *testing.T) { prod.Put(ping0) assert.Equal(1, prod.cache.Size()) - assert.Len(unhandlesMsg, 0) + assert.Empty(unhandlesMsg) prod.Put(pong1) assert.Equal(1, prod.cache.Size()) @@ -135,7 +135,7 @@ func TestProducer_caching(t *testing.T) { prod.Subscribe(rec, isPing) //nolint:errcheck ctxtest.AssertTerminates(t, timeout, func() { e, err := rec.Next(ctx) - assert.NoError(err) + require.NoError(t, err) assert.Same(e, ping0) }) assert.Equal(1, prod.cache.Size()) diff --git a/wire/relay_test.go b/wire/relay_test.go index 5f33ff090..a66a52707 100644 --- a/wire/relay_test.go +++ b/wire/relay_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "perun.network/go-perun/wire" wiretest "perun.network/go-perun/wire/test" "polycry.pt/poly-go/test" @@ -27,7 +28,7 @@ func TestProducer_produce_closed(t *testing.T) { var missed *wire.Envelope p := wire.NewRelay() p.SetDefaultMsgHandler(func(e *wire.Envelope) { missed = e }) - assert.NoError(t, p.Close()) + require.NoError(t, p.Close()) rng := test.Prng(t) a := wiretest.NewRandomAddress(rng) b := wiretest.NewRandomAddress(rng) diff --git a/wire/test/address.go b/wire/test/address.go index 6df58e200..6037639de 100644 --- a/wire/test/address.go +++ b/wire/test/address.go @@ -36,8 +36,8 @@ func TestAddressImplementation(t *testing.T, newAddress wire.NewAddressFunc, new // Test Address.MarshalBinary and UnmarshalBinary. data, err := addr.MarshalBinary() - assert.NoError(err) - assert.NoError(addr.UnmarshalBinary(data), "Byte deserialization of address should work") + require.NoError(err) + require.NoError(addr.UnmarshalBinary(data), "Byte deserialization of address should work") // Test Address.Equals. null := newAddress() @@ -51,9 +51,9 @@ func TestAddressImplementation(t *testing.T, newAddress wire.NewAddressFunc, new // Test Address.Bytes. addrBytes, err := addr.MarshalBinary() - assert.NoError(err, "Marshaling address should not error") + require.NoError(err, "Marshaling address should not error") nullBytes, err := null.MarshalBinary() - assert.NoError(err, "Marshaling zero address should not error") + require.NoError(err, "Marshaling zero address should not error") assert.False(bytes.Equal(addrBytes, nullBytes), "Expected inequality of byte representations of nonzero and zero address") // a.Equal(Decode(Encode(a))) diff --git a/wire/test/bustest.go b/wire/test/bustest.go index ab8f34cb4..07bda2bbe 100644 --- a/wire/test/bustest.go +++ b/wire/test/bustest.go @@ -71,10 +71,10 @@ func GenericBusTest(t *testing.T, go ct.StageN("receive timeout", numClients, func(t test.ConcT) { r := wire.NewReceiver() defer r.Close() - err := clients[i].r.Subscribe(r, func(e *wire.Envelope) bool { return true }) - require.NoError(t, err) + err := clients[i].r.Subscribe(r, func(_ *wire.Envelope) bool { return true }) + require.NoError(t, err) //nolint:testifylint _, err = r.Next(ctx) - require.Error(t, err) + require.Error(t, err) //nolint:testifylint }) } ct.Wait("receive timeout") @@ -110,14 +110,14 @@ func GenericBusTest(t *testing.T, defer recv.Close() for i := 0; i < numMsgs; i++ { e, err := recv.Next(ctx) - require.NoError(t, err) - require.Equal(t, e, origEnv) + require.NoError(t, err) //nolint:testifylint + require.Equal(t, e, origEnv) //nolint:testifylint } }) go ct.StageN("publish", numClients*(numClients-1), func(t test.ConcT) { for i := 0; i < numMsgs; i++ { err := clients[sender].pub.Publish(ctx, origEnv) - require.NoError(t, err) + require.NoError(t, err) //nolint:testifylint } }) } diff --git a/wire/test/serializinglocalbus.go b/wire/test/serializinglocalbus.go index 0a2246174..64c2b15da 100644 --- a/wire/test/serializinglocalbus.go +++ b/wire/test/serializinglocalbus.go @@ -37,18 +37,18 @@ func NewSerializingLocalBus() *SerializingLocalBus { } // Publish publishes the message on the bus. -func (b *SerializingLocalBus) Publish(ctx context.Context, e *wire.Envelope) (err error) { +func (b *SerializingLocalBus) Publish(ctx context.Context, e *wire.Envelope) error { // Serialize and deserialize the envelope before publishing it on the local // bus, to simulate envelope serialization. var buf bytes.Buffer - err = b.ser.Encode(&buf, e) + err := b.ser.Encode(&buf, e) if err != nil { - return + return err } deserializedEnvelope, err := b.ser.Decode(&buf) if err != nil { - return + return err } return b.LocalBus.Publish(ctx, deserializedEnvelope) } From 645dec3ff69a4bd9c0811491dd5f6782ef110c40 Mon Sep 17 00:00:00 2001 From: Minh Huy Tran Date: Thu, 29 Feb 2024 10:15:43 +0100 Subject: [PATCH 2/2] chore(ci): fix code for ci linter Signed-off-by: Minh Huy Tran --- .github/workflows/ci.yml | 4 ++-- .golangci.yml | 3 +++ wire/net/endpoint_registry_internal_test.go | 2 -- wire/net/simple/dialer_internal_test.go | 6 +++--- wire/net/test/connhub_internal_test.go | 6 +++--- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e7ded08b..4cce7a146 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,11 +35,11 @@ jobs: uses: actions/setup-go@v4 with: go-version: ${{ env.go-version }} - + - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.55 + version: v1.56.2 - name: Lint proto files uses: plexsystems/protolint-action@v0.7.0 diff --git a/.golangci.yml b/.golangci.yml index 1221be651..9d64fe8b4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -39,6 +39,9 @@ linters: - scopelint - golint - interfacer + - varcheck + - structcheck + - deadcode linters-settings: cyclop: diff --git a/wire/net/endpoint_registry_internal_test.go b/wire/net/endpoint_registry_internal_test.go index 2b54760e4..781e2bf3e 100644 --- a/wire/net/endpoint_registry_internal_test.go +++ b/wire/net/endpoint_registry_internal_test.go @@ -111,8 +111,6 @@ func nilConsumer(wire.Address) wire.Consumer { return nil } // dialed in the background. It also tests that the dialing process combines // with the Listener, so that if a connection to a peer that is still being // dialed comes in, the peer is assigned that connection. -// -//nolint:testify func TestRegistry_Get(t *testing.T) { t.Parallel() rng := test.Prng(t) diff --git a/wire/net/simple/dialer_internal_test.go b/wire/net/simple/dialer_internal_test.go index b2436f2c9..eabed16f4 100644 --- a/wire/net/simple/dialer_internal_test.go +++ b/wire/net/simple/dialer_internal_test.go @@ -103,11 +103,11 @@ func TestDialer_Dial(t *testing.T) { ct := test.NewConcurrent(t) go ct.Stage("accept", func(rt test.ConcT) { conn, err := l.Accept(ser) - require.NoError(t, err) //nolint: testifylint - require.NotNil(rt, conn) //nolint: testifylint + require.NoError(t, err) //nolint:testifylint + require.NotNil(rt, conn) //nolint:testifylint re, err := conn.Recv() - require.NoError(t, err) //nolint: testifylint + require.NoError(t, err) //nolint:testifylint assert.Equal(t, re, e) }) diff --git a/wire/net/test/connhub_internal_test.go b/wire/net/test/connhub_internal_test.go index f8e730482..fa313dffc 100644 --- a/wire/net/test/connhub_internal_test.go +++ b/wire/net/test/connhub_internal_test.go @@ -46,9 +46,9 @@ func TestConnHub_Create(t *testing.T) { go ctxtest.AssertTerminates(t, timeout, func() { ct.Stage("accept", func(rt pkgtest.ConcT) { conn, err := l.Accept(ser) - require.NoError(t, err) //nolint: testifylint - require.NotNil(rt, conn) //nolint: testifylint - require.NoError(t, conn.Send(wiretest.NewRandomEnvelope(rng, wire.NewPingMsg()))) //nolint: testifylint + require.NoError(t, err) //nolint:testifylint + require.NotNil(rt, conn) //nolint:testifylint + require.NoError(t, conn.Send(wiretest.NewRandomEnvelope(rng, wire.NewPingMsg()))) //nolint:testifylint }) })