diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cdcd1989b..265499153a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ See [RELEASE](./RELEASE.md) for workflow instructions. +## UNRELEASED + +### Upgrade information + +### Highlights + +### Features + +### Improvements + ## v1.7.7 ### Improvements diff --git a/activation/activation.go b/activation/activation.go index 517b464727..3695ad06e7 100644 --- a/activation/activation.go +++ b/activation/activation.go @@ -32,7 +32,7 @@ import ( ) var ( - ErrNotFound = errors.New("not found") + errNotFound = errors.New("not found") errNilVrfNonce = errors.New("nil VRF nonce") ) @@ -429,7 +429,7 @@ func (b *Builder) run(ctx context.Context, sig *signing.EdSigner) { eg.Go(func() error { _, err := poet.Certify(ctx, sig.NodeID()) switch { - case errors.Is(err, ErrCertificatesNotSupported): + case errors.Is(err, errCertificatesNotSupported): b.logger.Debug("not certifying (not supported in poet)", log.ZShortStringer("smesherID", sig.NodeID()), zap.String("poet", poet.Address()), @@ -454,7 +454,7 @@ func (b *Builder) run(ctx context.Context, sig *signing.EdSigner) { poetErr := &PoetSvcUnstableError{} switch { - case errors.Is(err, ErrATXChallengeExpired): + case errors.Is(err, errATXChallengeExpired): b.logger.Debug("retrying with new challenge after waiting for a layer") if err := b.nipostBuilder.ResetState(sig.NodeID()); err != nil { b.logger.Error("failed to reset nipost builder state", zap.Error(err)) @@ -829,7 +829,7 @@ func (b *Builder) createAtx( // initial NIPoST challenge is not discarded; don't return ErrATXChallengeExpired return nil, errors.New("atx publish epoch has passed during nipost construction") } - return nil, fmt.Errorf("%w: atx publish epoch has passed during nipost construction", ErrATXChallengeExpired) + return nil, fmt.Errorf("%w: atx publish epoch has passed during nipost construction", errATXChallengeExpired) } switch version { @@ -1086,7 +1086,7 @@ func findFullyValidHighTickAtx( } if found == nil { - return types.ATXID{}, ErrNotFound + return types.ATXID{}, errNotFound } return *found, nil diff --git a/activation/activation_errors.go b/activation/activation_errors.go index e2e2215e5f..9540cc8833 100644 --- a/activation/activation_errors.go +++ b/activation/activation_errors.go @@ -7,10 +7,10 @@ import ( ) var ( - // ErrATXChallengeExpired is returned when atx missed its publication window and needs to be regenerated. - ErrATXChallengeExpired = errors.New("builder: atx expired") - // ErrPoetProofNotReceived is returned when no poet proof was received. - ErrPoetProofNotReceived = errors.New("builder: didn't receive any poet proof") + // errATXChallengeExpired is returned when atx missed its publication window and needs to be regenerated. + errATXChallengeExpired = errors.New("builder: atx expired") + // errPoetProofNotReceived is returned when no poet proof was received. + errPoetProofNotReceived = errors.New("builder: didn't receive any poet proof") ) // PoetSvcUnstableError means there was a problem communicating diff --git a/activation/activation_test.go b/activation/activation_test.go index ba1c6dd7ea..bf5085647b 100644 --- a/activation/activation_test.go +++ b/activation/activation_test.go @@ -404,7 +404,7 @@ func TestBuilder_Loop_WaitsOnStaleChallenge(t *testing.T) { tab.mnipost.EXPECT(). BuildNIPost(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(nil, ErrATXChallengeExpired) + Return(nil, errATXChallengeExpired) tab.mnipost.EXPECT().ResetState(sig.NodeID()).Return(nil) ctx, cancel := context.WithCancel(context.Background()) @@ -803,7 +803,7 @@ func TestBuilder_PublishActivationTx_NoPrevATX_PublishFails_InitialPost_preserve }).AnyTimes() tab.mnipost.EXPECT(). BuildNIPost(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). - Return(nil, ErrATXChallengeExpired) + Return(nil, errATXChallengeExpired) tab.mnipost.EXPECT().ResetState(sig.NodeID()).Return(nil) ch := make(chan struct{}) tab.mclock.EXPECT().AwaitLayer(currLayer.Add(1)).Do(func(got types.LayerID) <-chan struct{} { diff --git a/activation/nipost.go b/activation/nipost.go index 6d87393a17..22d8d62f1b 100644 --- a/activation/nipost.go +++ b/activation/nipost.go @@ -262,7 +262,7 @@ func (nb *NIPostBuilder) BuildNIPost( if poetProofDeadline.Before(now) { return nil, fmt.Errorf( "%w: deadline to query poet proof for pub epoch %d exceeded (deadline: %s, now: %s)", - ErrATXChallengeExpired, + errATXChallengeExpired, postChallenge.PublishEpoch, poetProofDeadline, now, @@ -276,7 +276,7 @@ func (nb *NIPostBuilder) BuildNIPost( return nil, &PoetSvcUnstableError{msg: "getBestProof failed", source: err} } if poetProofRef == types.EmptyPoetProofRef { - return nil, &PoetSvcUnstableError{source: ErrPoetProofNotReceived} + return nil, &PoetSvcUnstableError{source: errPoetProofNotReceived} } if err := nipost.UpdatePoetProofRef(nb.localDB, signer.NodeID(), poetProofRef, membership); err != nil { nb.logger.Warn("cannot persist poet proof ref", zap.Error(err)) @@ -295,7 +295,7 @@ func (nb *NIPostBuilder) BuildNIPost( if publishEpochEnd.Before(now) { return nil, fmt.Errorf( "%w: deadline to publish ATX for pub epoch %d exceeded (deadline: %s, now: %s)", - ErrATXChallengeExpired, + errATXChallengeExpired, postChallenge.PublishEpoch, publishEpochEnd, now, @@ -446,7 +446,7 @@ func (nb *NIPostBuilder) submitPoetChallenges( // no existing registration at all, drop current registration challenge return nil, fmt.Errorf( "%w: poet round has already started at %s (now: %s)", - ErrATXChallengeExpired, + errATXChallengeExpired, curPoetRoundStartDeadline, now, ) @@ -499,7 +499,7 @@ func (nb *NIPostBuilder) submitPoetChallenges( if len(existingRegistrations) == 0 { if curPoetRoundStartDeadline.Before(time.Now()) { - return nil, ErrATXChallengeExpired + return nil, errATXChallengeExpired } return nil, &PoetSvcUnstableError{msg: "failed to submit challenge to any PoET", source: ctx.Err()} } @@ -616,7 +616,7 @@ func (nb *NIPostBuilder) getBestProof( return ref, bestProof.membership, nil } - return types.PoetProofRef{}, nil, ErrPoetProofNotReceived + return types.PoetProofRef{}, nil, errPoetProofNotReceived } func constructMerkleProof(challenge types.Hash32, members []types.Hash32) (*types.MerkleProof, error) { diff --git a/activation/nipost_test.go b/activation/nipost_test.go index e406f84cd1..446e66b551 100644 --- a/activation/nipost_test.go +++ b/activation/nipost_test.go @@ -762,7 +762,7 @@ func TestNIPSTBuilder_PoetUnstable(t *testing.T) { challenge, &types.NIPostChallenge{PublishEpoch: postGenesisEpoch + 2}, ) - require.ErrorIs(t, err, ErrATXChallengeExpired) + require.ErrorIs(t, err, errATXChallengeExpired) require.Nil(t, nipst) }) t.Run("GetProof fails", func(t *testing.T) { @@ -786,7 +786,7 @@ func TestNIPSTBuilder_PoetUnstable(t *testing.T) { nipst, err := nb.BuildNIPost(context.Background(), sig, challenge, &types.NIPostChallenge{PublishEpoch: postGenesisEpoch + 2}) - require.ErrorIs(t, err, ErrPoetProofNotReceived) + require.ErrorIs(t, err, errPoetProofNotReceived) require.Nil(t, nipst) }) t.Run("Challenge is not included in proof members", func(t *testing.T) { @@ -812,7 +812,7 @@ func TestNIPSTBuilder_PoetUnstable(t *testing.T) { nipst, err := nb.BuildNIPost(context.Background(), sig, challenge, &types.NIPostChallenge{PublishEpoch: postGenesisEpoch + 2}) - require.ErrorIs(t, err, ErrPoetProofNotReceived) + require.ErrorIs(t, err, errPoetProofNotReceived) require.Nil(t, nipst) }) } @@ -1152,7 +1152,7 @@ func TestNIPoSTBuilder_StaleChallenge(t *testing.T) { nipost, err := nb.BuildNIPost(context.Background(), sig, types.RandomHash(), &types.NIPostChallenge{PublishEpoch: currLayer.GetEpoch()}) - require.ErrorIs(t, err, ErrATXChallengeExpired) + require.ErrorIs(t, err, errATXChallengeExpired) require.ErrorContains(t, err, "poet round has already started") require.Nil(t, nipost) }) @@ -1194,7 +1194,7 @@ func TestNIPoSTBuilder_StaleChallenge(t *testing.T) { require.NoError(t, err) nipost, err := nb.BuildNIPost(context.Background(), sig, challengeHash, challenge) - require.ErrorIs(t, err, ErrATXChallengeExpired) + require.ErrorIs(t, err, errATXChallengeExpired) require.ErrorContains(t, err, "poet proof for pub epoch") require.Nil(t, nipost) }) @@ -1240,7 +1240,7 @@ func TestNIPoSTBuilder_StaleChallenge(t *testing.T) { require.NoError(t, err) nipost, err := nb.BuildNIPost(context.Background(), sig, challengeHash, challenge) - require.ErrorIs(t, err, ErrATXChallengeExpired) + require.ErrorIs(t, err, errATXChallengeExpired) require.ErrorContains(t, err, "deadline to publish ATX for pub epoch") require.Nil(t, nipost) }) diff --git a/activation/poet.go b/activation/poet.go index 3174d0c19e..3d158a71d7 100644 --- a/activation/poet.go +++ b/activation/poet.go @@ -33,9 +33,9 @@ import ( var ( ErrInvalidRequest = errors.New("invalid request") ErrUnauthorized = errors.New("unauthorized") - ErrCertificatesNotSupported = errors.New("poet doesn't support certificates") - ErrIncompatiblePhaseShift = errors.New("fetched poet phase_shift is incompatible with configured phase_shift") - ErrCertifierNotConfigured = errors.New("certifier service not configured") + errCertificatesNotSupported = errors.New("poet doesn't support certificates") + errIncompatiblePhaseShift = errors.New("fetched poet phase_shift is incompatible with configured phase_shift") + errCertifierNotConfigured = errors.New("certifier service not configured") ) type PoetPowParams struct { @@ -464,7 +464,7 @@ func NewPoetServiceWithClient( err := service.verifyPhaseShiftConfiguration(context.Background()) switch { - case errors.Is(err, ErrIncompatiblePhaseShift): + case errors.Is(err, errIncompatiblePhaseShift): logger.Fatal("failed to create poet service", zap.String("poet", client.Address())) return nil case err != nil: @@ -487,7 +487,7 @@ func (c *poetService) verifyPhaseShiftConfiguration(ctx context.Context) error { } if info.PhaseShift != c.expectedPhaseShift { - return ErrIncompatiblePhaseShift + return errIncompatiblePhaseShift } return nil @@ -508,7 +508,7 @@ func (c *poetService) authorize( switch { case err == nil: return &PoetAuth{PoetCert: cert}, nil - case errors.Is(err, ErrCertificatesNotSupported): + case errors.Is(err, errCertificatesNotSupported): logger.Debug("poet doesn't support certificates") default: logger.Warn("failed to certify", zap.Error(err)) @@ -574,7 +574,7 @@ func (c *poetService) Submit( err := c.verifyPhaseShiftConfiguration(ctx) switch { - case errors.Is(err, ErrIncompatiblePhaseShift): + case errors.Is(err, errIncompatiblePhaseShift): logger.Fatal("failed to submit challenge", zap.String("poet", c.client.Address())) return nil, err case err != nil: @@ -639,7 +639,7 @@ func (c *poetService) Proof(ctx context.Context, roundID string) (*types.PoetPro func (c *poetService) Certify(ctx context.Context, id types.NodeID) (*certifier.PoetCert, error) { if c.certifier == nil { - return nil, ErrCertifierNotConfigured + return nil, errCertifierNotConfigured } info, err := c.getInfo(ctx) @@ -648,7 +648,7 @@ func (c *poetService) Certify(ctx context.Context, id types.NodeID) (*certifier. } if info.Certifier == nil { - return nil, ErrCertificatesNotSupported + return nil, errCertificatesNotSupported } return c.certifier.Certificate(ctx, id, info.Certifier.Url, info.Certifier.Pubkey) } diff --git a/activation/poet_client_test.go b/activation/poet_client_test.go index a668b97643..301b0cd26f 100644 --- a/activation/poet_client_test.go +++ b/activation/poet_client_test.go @@ -336,7 +336,7 @@ func TestPoetClient_Certify(t *testing.T) { poet := NewPoetServiceWithClient( nil, client, cfg, zaptest.NewLogger(t), testTickSize, WithCertifier(mCertifier)) _, err = poet.Certify(context.Background(), sig.NodeID()) - require.ErrorIs(t, err, ErrCertificatesNotSupported) + require.ErrorIs(t, err, errCertificatesNotSupported) }) } diff --git a/activation/post.go b/activation/post.go index 7e1664df89..c31b5b5d43 100644 --- a/activation/post.go +++ b/activation/post.go @@ -424,7 +424,7 @@ func (mgr *PostSetupManager) findCommitmentAtx(ctx context.Context) (types.ATXID VerifyChainOpts.WithLogger(mgr.logger), ) switch { - case errors.Is(err, ErrNotFound): + case errors.Is(err, errNotFound): mgr.logger.Info("using golden atx as commitment atx") return mgr.goldenATXID, nil case err != nil: diff --git a/activation/wire/malfeasance_invalid_post.go b/activation/wire/malfeasance_invalid_post.go index ddb792c9f0..cb380ba88d 100644 --- a/activation/wire/malfeasance_invalid_post.go +++ b/activation/wire/malfeasance_invalid_post.go @@ -271,7 +271,7 @@ func (p InvalidPostProof) Valid( p.NumUnits, int(p.ValidPostIndex), ); err != nil { - return errors.New("Commitment ATX is not valid") + return errors.New("commitment ATX is not valid") } if err := malValidator.PostIndex( diff --git a/activation/wire/malfeasance_invalid_post_test.go b/activation/wire/malfeasance_invalid_post_test.go index c0bea896a8..bed03b25eb 100644 --- a/activation/wire/malfeasance_invalid_post_test.go +++ b/activation/wire/malfeasance_invalid_post_test.go @@ -312,7 +312,7 @@ func Test_InvalidPostProof(t *testing.T) { ).Return(errors.New("invalid post")) id, err := proof.Valid(context.Background(), verifier) - require.EqualError(t, err, "invalid invalid post proof: Commitment ATX is not valid") + require.EqualError(t, err, "invalid invalid post proof: commitment ATX is not valid") require.Equal(t, types.EmptyNodeID, id) }) diff --git a/cmd/bootstrapper/bootstrapper.go b/cmd/bootstrapper/bootstrapper.go index af6bf53e17..3bf67f8c93 100644 --- a/cmd/bootstrapper/bootstrapper.go +++ b/cmd/bootstrapper/bootstrapper.go @@ -254,7 +254,7 @@ func queryNetworkParams(ctx context.Context, endpoint string) (*NetworkParam, er func main() { if err := cmd.Execute(); err != nil { - _, _ = fmt.Fprintln(os.Stderr, err) + fmt.Fprintln(os.Stderr, err) os.Exit(1) } } diff --git a/common/types/address.go b/common/types/address.go index 9c3be93389..bc631e77cc 100644 --- a/common/types/address.go +++ b/common/types/address.go @@ -115,7 +115,7 @@ func (a Address) String() string { // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, // without going through the stringer interface used for logging. func (a Address) Format(s fmt.State, c rune) { - _, _ = fmt.Fprintf(s, "%"+string(c), a[:]) + fmt.Fprintf(s, "%"+string(c), a[:]) } // EncodeScale implements scale codec interface. diff --git a/common/types/hashes.go b/common/types/hashes.go index 7cb9339701..179f1384c0 100644 --- a/common/types/hashes.go +++ b/common/types/hashes.go @@ -47,7 +47,7 @@ func (h Hash20) ShortString() string { // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, // without going through the stringer interface used for logging. func (h Hash20) Format(s fmt.State, c rune) { - _, _ = fmt.Fprintf(s, "%"+string(c), h[:]) + fmt.Fprintf(s, "%"+string(c), h[:]) } // UnmarshalText parses a hash in hex syntax. @@ -69,7 +69,10 @@ func (h *Hash20) UnmarshalJSON(input []byte) error { // MarshalText returns the hex representation of h. func (h Hash20) MarshalText() ([]byte, error) { - return util.Bytes(h[:]).MarshalText() + result := make([]byte, len(h)*2+2) + copy(result, `0x`) + hex.Encode(result[2:], h[:]) + return result, nil } // SetBytes sets the hash to the value of b. @@ -163,7 +166,7 @@ func (h Hash32) ShortString() string { // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, // without going through the stringer interface used for logging. func (h Hash32) Format(s fmt.State, c rune) { - _, _ = fmt.Fprintf(s, "%"+string(c), h[:]) + fmt.Fprintf(s, "%"+string(c), h[:]) } // UnmarshalText parses a hash in hex syntax. @@ -186,7 +189,10 @@ func (h *Hash32) UnmarshalJSON(input []byte) error { // MarshalText returns the hex representation of h. func (h Hash32) MarshalText() ([]byte, error) { - return util.Bytes(h[:]).MarshalText() + result := make([]byte, len(h)*2+2) + copy(result, `0x`) + hex.Encode(result[2:], h[:]) + return result, nil } // SetBytes sets the hash to the value of b. diff --git a/common/types/testutil.go b/common/types/testutil.go index 9018dbabb6..50d11d481f 100644 --- a/common/types/testutil.go +++ b/common/types/testutil.go @@ -102,7 +102,7 @@ func RandomTransactionID() TransactionID { // RandomBallot generates a Ballot with random content for testing. func RandomBallot() *Ballot { var vrf VrfSignature - _, _ = rand.Read(vrf[:]) + rand.Read(vrf[:]) return &Ballot{ InnerBallot: InnerBallot{ diff --git a/common/util/bytes.go b/common/util/bytes.go deleted file mode 100644 index f67f9a3072..0000000000 --- a/common/util/bytes.go +++ /dev/null @@ -1,14 +0,0 @@ -// Package util provides common utility functions. -package util - -import ( - "encoding/binary" -) - -// Uint64ToBytesBigEndian returns the byte representation of a uint64, using big endian encoding (which is not the -// default for spacemesh). -func Uint64ToBytesBigEndian(i uint64) []byte { - a := make([]byte, 8) - binary.BigEndian.PutUint64(a, i) - return a -} diff --git a/common/util/hexutil.go b/common/util/hexutil.go index 13ab31eaf3..3e31cbc3f6 100644 --- a/common/util/hexutil.go +++ b/common/util/hexutil.go @@ -35,20 +35,12 @@ import ( // Errors. var ( - ErrSyntax = errors.New("invalid hex string") - ErrMissingPrefix = errors.New("hex string without 0x prefix") - ErrOddLength = errors.New("hex string of odd length") - ErrUint64Range = errors.New("hex number > 64 bits") + errSyntax = errors.New("invalid hex string") + errMissingPrefix = errors.New("hex string without 0x prefix") + errOddLength = errors.New("hex string of odd length") + errUint64Range = errors.New("hex number > 64 bits") ) -// Encode encodes b as a hex string with 0x prefix. -func Encode(b []byte) string { - enc := make([]byte, len(b)*2+2) - copy(enc, "0x") - hex.Encode(enc[2:], b) - return string(enc) -} - // FromHex returns the bytes represented by the hexadecimal string s. // Parameter s may be prefixed with "0x". func FromHex(s string) []byte { diff --git a/common/util/hexutil_test.go b/common/util/hexutil_test.go deleted file mode 100644 index 393e9ee0c0..0000000000 --- a/common/util/hexutil_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2016 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package util - -import ( - "testing" -) - -type marshalTest struct { - input any - want string -} - -type unmarshalTest struct { - input string - want any - wantErr error // if set, decoding must fail on any platform -} - -var encodeBytesTests = []marshalTest{ - {[]byte{}, "0x"}, - {[]byte{0}, "0x00"}, - {[]byte{0, 0, 1, 2}, "0x00000102"}, -} - -func TestEncode(t *testing.T) { - for _, test := range encodeBytesTests { - enc := Encode(test.input.([]byte)) - if enc != test.want { - t.Errorf("input %x: wrong encoding %s", test.input, enc) - } - } -} diff --git a/common/util/json.go b/common/util/json.go index feb428e58e..8a5a1c0d1b 100644 --- a/common/util/json.go +++ b/common/util/json.go @@ -23,57 +23,14 @@ import ( "errors" "fmt" "reflect" - "strconv" ) -var bytesT = reflect.TypeOf(Bytes(nil)) - -// Bytes marshals/unmarshals as a JSON string with 0x prefix. -// The empty slice marshals as "0x". -type Bytes []byte - -// MarshalText implements encoding.TextMarshaler. -func (b Bytes) MarshalText() ([]byte, error) { - result := make([]byte, len(b)*2+2) - copy(result, `0x`) - hex.Encode(result[2:], b) - return result, nil -} - -// UnmarshalJSON implements json.Unmarshaler. -func (b *Bytes) UnmarshalJSON(input []byte) error { - if !isString(input) { - return errNonString(bytesT) - } - return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bytesT) -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (b *Bytes) UnmarshalText(input []byte) error { - raw, err := checkText(input, true) - if err != nil { - return err - } - dec := make([]byte, len(raw)/2) - if _, err = hex.Decode(dec, raw); err != nil { - err = mapError(err) - } else { - *b = dec - } - return err -} - -// String returns the hex encoding of b. -func (b Bytes) String() string { - return Encode(b) -} - // UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out // determines the required input length. This function is commonly used to implement the // UnmarshalJSON method for fixed-size types. func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error { - if !isString(input) { - return errNonString(typ) + if len(input) < 2 || input[0] != '"' || input[len(input)-1] != '"' { // check for quoted string + return &json.UnmarshalTypeError{Value: "non-string", Type: typ} } return wrapTypeError(UnmarshalFixedText(typ.String(), input[1:len(input)-1], out), typ) } @@ -92,17 +49,13 @@ func UnmarshalFixedText(typename string, input, out []byte) error { // Pre-verify syntax before modifying out. for _, b := range raw { if decodeNibble(b) == badNibble { - return ErrSyntax + return errSyntax } } hex.Decode(out, raw) return nil } -func isString(input []byte) bool { - return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' -} - func bytesHave0xPrefix(input []byte) bool { return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') } @@ -114,33 +67,29 @@ func checkText(input []byte, wantPrefix bool) ([]byte, error) { if bytesHave0xPrefix(input) { input = input[2:] } else if wantPrefix { - return nil, ErrMissingPrefix + return nil, errMissingPrefix } if len(input)%2 != 0 { - return nil, ErrOddLength + return nil, errOddLength } return input, nil } func wrapTypeError(err error, typ reflect.Type) error { switch { - case errors.Is(err, ErrSyntax): + case errors.Is(err, errSyntax): return &json.UnmarshalTypeError{Value: err.Error(), Type: typ} - case errors.Is(err, ErrMissingPrefix): + case errors.Is(err, errMissingPrefix): return &json.UnmarshalTypeError{Value: err.Error(), Type: typ} - case errors.Is(err, ErrOddLength): + case errors.Is(err, errOddLength): return &json.UnmarshalTypeError{Value: err.Error(), Type: typ} - case errors.Is(err, ErrUint64Range): + case errors.Is(err, errUint64Range): return &json.UnmarshalTypeError{Value: err.Error(), Type: typ} default: return err } } -func errNonString(typ reflect.Type) error { - return &json.UnmarshalTypeError{Value: "non-string", Type: typ} -} - const badNibble = ^uint64(0) func decodeNibble(in byte) uint64 { @@ -156,26 +105,6 @@ func decodeNibble(in byte) uint64 { } } -func mapError(err error) error { - var numErr *strconv.NumError - if errors.As(err, &numErr) { - switch numErr.Err { - case strconv.ErrRange: - return ErrUint64Range - case strconv.ErrSyntax: - return ErrSyntax - } - } - var syntaxErr hex.InvalidByteError - if errors.As(err, &syntaxErr) { - return ErrSyntax - } - if errors.Is(err, hex.ErrLength) { - return ErrOddLength - } - return err -} - func Base64Encode(src []byte) []byte { n := base64.StdEncoding.EncodedLen(len(src)) dst := make([]byte, n) diff --git a/common/util/json_test.go b/common/util/json_test.go deleted file mode 100644 index b8d3ef8a51..0000000000 --- a/common/util/json_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2016 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package util - -import ( - "encoding/hex" - "encoding/json" - "errors" - "strconv" - "testing" - - "github.com/stretchr/testify/require" -) - -func referenceBytes(s string) []byte { - b, err := hex.DecodeString(s) - if err != nil { - panic(err) - } - return b -} - -var unmarshalBytesErrorTests = []unmarshalTest{ - // invalid encoding - {input: "", wantErr: errors.New("unexpected end of JSON input")}, - {input: "null", wantErr: errNonString(bytesT)}, - {input: "10", wantErr: errNonString(bytesT)}, - {input: `"0"`, wantErr: wrapTypeError(ErrMissingPrefix, bytesT)}, - {input: `"0x0"`, wantErr: wrapTypeError(ErrOddLength, bytesT)}, - {input: `"0xxx"`, wantErr: wrapTypeError(ErrSyntax, bytesT)}, - {input: `"0x01zz01"`, wantErr: wrapTypeError(ErrSyntax, bytesT)}, -} - -var unmarshalBytesTests = []unmarshalTest{ - // valid encoding - {input: `""`, want: referenceBytes("")}, - {input: `"0x"`, want: referenceBytes("")}, - {input: `"0x02"`, want: referenceBytes("02")}, - {input: `"0X02"`, want: referenceBytes("02")}, - {input: `"0xffffffffff"`, want: referenceBytes("ffffffffff")}, - { - input: `"0xffffffffffffffffffffffffffffffffffff"`, - want: referenceBytes("ffffffffffffffffffffffffffffffffffff"), - }, -} - -func TestUnmarshalBytes(t *testing.T) { - for _, test := range unmarshalBytesErrorTests { - var v Bytes - err := json.Unmarshal([]byte(test.input), &v) - require.EqualError(t, err, test.wantErr.Error()) - } - - for _, test := range unmarshalBytesTests { - var v Bytes - err := json.Unmarshal([]byte(test.input), &v) - require.NoError(t, err) - require.Equal(t, test.want.([]byte), []byte(v)) - } -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - input := []byte(`"0x123456789abcdef123456789abcdef"`) - for i := 0; i < b.N; i++ { - var v Bytes - if err := v.UnmarshalJSON(input); err != nil { - b.Fatal(err) - } - } -} - -func TestMarshalBytes(t *testing.T) { - for _, test := range encodeBytesTests { - in := test.input.([]byte) - out, err := json.Marshal(Bytes(in)) - require.NoError(t, err) - require.Equal(t, strconv.Quote(test.want), string(out)) - require.Equal(t, test.want, Bytes(in).String()) - } -} diff --git a/fetch/fetch.go b/fetch/fetch.go index 396342a4bb..7517dcc01a 100644 --- a/fetch/fetch.go +++ b/fetch/fetch.go @@ -450,7 +450,7 @@ func (f *Fetch) Stop() { } f.mu.Unlock() - _ = f.eg.Wait() + f.eg.Wait() f.logger.Debug("stopped fetch") } diff --git a/genvm/vm_test.go b/genvm/vm_test.go index 4f8992b4a3..54e2943e13 100644 --- a/genvm/vm_test.go +++ b/genvm/vm_test.go @@ -2492,7 +2492,7 @@ func FuzzParse(f *testing.F) { req := tt.VM.Validation(types.NewRawTx(buf.Bytes())) _, err = req.Parse() if err == nil { - _ = req.Verify() + req.Verify() } }) } diff --git a/hare3/types_test.go b/hare3/types_test.go index ded67b1c6a..0fd158450d 100644 --- a/hare3/types_test.go +++ b/hare3/types_test.go @@ -35,7 +35,7 @@ func FuzzMessageDecode(f *testing.F) { f.Fuzz(func(t *testing.T, buf []byte) { var msg Message if err := codec.Decode(buf, &msg); err == nil { - _ = msg.Validate() + msg.Validate() } }) } diff --git a/hare4/types_test.go b/hare4/types_test.go index 91cf9ffe4f..17a7e80df7 100644 --- a/hare4/types_test.go +++ b/hare4/types_test.go @@ -35,7 +35,7 @@ func FuzzMessageDecode(f *testing.F) { f.Fuzz(func(t *testing.T, buf []byte) { var msg Message if err := codec.Decode(buf, &msg); err == nil { - _ = msg.Validate() + msg.Validate() } }) } diff --git a/mesh/mesh_test.go b/mesh/mesh_test.go index fb3e2907b5..78ef3e9768 100644 --- a/mesh/mesh_test.go +++ b/mesh/mesh_test.go @@ -790,7 +790,7 @@ func ensuresDatabaseConsistent(tb testing.TB, db sql.Executor, results []result. if !rst.Data { continue } - _ = blocks.Add(db, types.NewExistingBlock(rst.Header.ID, types.InnerBlock{ + blocks.Add(db, types.NewExistingBlock(rst.Header.ID, types.InnerBlock{ LayerIndex: layer.Layer, })) } diff --git a/p2p/server/deadline_adjuster.go b/p2p/server/deadline_adjuster.go index 89dc35c18f..634e638272 100644 --- a/p2p/server/deadline_adjuster.go +++ b/p2p/server/deadline_adjuster.go @@ -91,7 +91,7 @@ func (dadj *deadlineAdjuster) augmentError(what string, err error) error { // Close closes the stream. This method is safe to call multiple times. func (dadj *deadlineAdjuster) Close() error { // FIXME: unsure if this is really needed (inherited from the older Server code) - _ = dadj.peerStream.SetDeadline(time.Time{}) + dadj.peerStream.SetDeadline(time.Time{}) return dadj.peerStream.Close() } @@ -120,9 +120,9 @@ func (dadj *deadlineAdjuster) adjust() error { // doesn't work for mock hosts deadline := now.Add(dadj.timeout) if deadline.After(dadj.hardDeadline) { - _ = dadj.SetDeadline(dadj.hardDeadline) + dadj.SetDeadline(dadj.hardDeadline) } else { - _ = dadj.SetDeadline(deadline) + dadj.SetDeadline(deadline) } } diff --git a/p2p/server/server.go b/p2p/server/server.go index 8506af70f3..3a3925735c 100644 --- a/p2p/server/server.go +++ b/p2p/server/server.go @@ -32,12 +32,8 @@ type DecayingTagSpec struct { Cap int `mapstructure:"cap"` } -var ( - // ErrNotConnected is returned when peer is not connected. - ErrNotConnected = errors.New("peer is not connected") - // ErrPeerResponseFailed raised if peer responded with an error. - ErrPeerResponseFailed = errors.New("peer response failed") -) +// ErrNotConnected is returned when peer is not connected. +var ErrNotConnected = errors.New("peer is not connected") // Opt is a type to configure a server. type Opt func(s *Server) @@ -390,7 +386,7 @@ func (s *Server) StreamRequest( return fmt.Errorf("request length (%d) is longer than limit %d", len(req), s.requestLimit) } if s.h.Network().Connectedness(pid) != network.Connected { - return fmt.Errorf("%w: %s", ErrNotConnected, pid) + return ErrNotConnected } ctx, cancel := context.WithTimeout(ctx, s.hardTimeout) diff --git a/proposals/handler_test.go b/proposals/handler_test.go index 354738745e..d000b10018 100644 --- a/proposals/handler_test.go +++ b/proposals/handler_test.go @@ -1071,7 +1071,7 @@ func TestProposal_ProposalGossip_Concurrent(t *testing.T) { th.mv.EXPECT().CheckEligibility(gomock.Any(), &p.Ballot, gomock.Any()).Return(nil).MinTimes(1).MaxTimes(2) th.mm.EXPECT().AddBallot(context.Background(), &p.Ballot).DoAndReturn( func(_ context.Context, got *types.Ballot) (*wire.MalfeasanceProof, error) { - _ = ballots.Add(th.db, got) + ballots.Add(th.db, got) return nil, nil }).MinTimes(1).MaxTimes(2) th.mf.EXPECT().GetProposalTxs(gomock.Any(), p.TxIDs).Return(nil).MinTimes(1).MaxTimes(2) @@ -1142,7 +1142,7 @@ func TestProposal_BroadcastMaliciousGossip(t *testing.T) { th.mm.EXPECT().AddBallot(context.Background(), &pMal.Ballot).DoAndReturn( func(_ context.Context, got *types.Ballot) (*wire.MalfeasanceProof, error) { got.SetMalicious() - _ = ballots.Add(th.db, got) + ballots.Add(th.db, got) return proof, nil }) th.mf.EXPECT().GetProposalTxs(gomock.Any(), pMal.TxIDs).Return(nil) diff --git a/sql/transactions/transactions.go b/sql/transactions/transactions.go index cfab44aadf..82945ba34c 100644 --- a/sql/transactions/transactions.go +++ b/sql/transactions/transactions.go @@ -8,7 +8,6 @@ import ( "github.com/spacemeshos/go-spacemesh/codec" "github.com/spacemeshos/go-spacemesh/common/types" - "github.com/spacemeshos/go-spacemesh/common/util" "github.com/spacemeshos/go-spacemesh/sql" "github.com/spacemeshos/go-spacemesh/sql/builder" ) @@ -37,7 +36,10 @@ func Add(db sql.Executor, tx *types.Transaction, received time.Time) error { if header != nil { stmt.BindBytes(3, header) stmt.BindBytes(4, tx.Principal[:]) - stmt.BindBytes(5, util.Uint64ToBytesBigEndian(tx.Nonce)) + + nonceBytes := make([]byte, 8) + binary.BigEndian.PutUint64(nonceBytes, tx.Nonce) + stmt.BindBytes(5, nonceBytes) } stmt.BindInt64(6, received.UnixNano()) }, nil); err != nil { @@ -302,7 +304,10 @@ func GetAcctPendingFromNonce(db sql.Executor, address types.Address, from uint64 order by nonce asc, timestamp asc`, func(stmt *sql.Statement) { stmt.BindBytes(1, address.Bytes()) - stmt.BindBytes(2, util.Uint64ToBytesBigEndian(from)) + + fromBytes := make([]byte, 8) + binary.BigEndian.PutUint64(fromBytes, from) + stmt.BindBytes(2, fromBytes) }, "get acct pending from nonce") } @@ -314,7 +319,10 @@ func GetAcctPendingToNonce(db sql.Executor, address types.Address, to uint64) ([ order by nonce asc, timestamp asc;`, func(stmt *sql.Statement) { stmt.BindBytes(1, address.Bytes()) - stmt.BindBytes(2, util.Uint64ToBytesBigEndian(to)) + + toBytes := make([]byte, 8) + binary.BigEndian.PutUint64(toBytes, to) + stmt.BindBytes(2, toBytes) }, func(stmt *sql.Statement) bool { id := types.TransactionID{} stmt.ColumnBytes(0, id[:]) diff --git a/sync2/rangesync/combine_seqs_test.go b/sync2/rangesync/combine_seqs_test.go index ec1fbc8849..ae2bbff2b7 100644 --- a/sync2/rangesync/combine_seqs_test.go +++ b/sync2/rangesync/combine_seqs_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" ) -var seqTestErr = errors.New("test error") +var errSeqTest = errors.New("test error") type fakeSeqItem struct { k string @@ -19,7 +19,7 @@ type fakeSeqItem struct { func mkFakeSeqItem(s string) fakeSeqItem { switch s { case "!": - return fakeSeqItem{err: seqTestErr} + return fakeSeqItem{err: errSeqTest} case "$": return fakeSeqItem{stop: true} default: @@ -98,7 +98,7 @@ func seqToStr(t *testing.T, sr SeqResult) string { sb.Write(k) } if err := sr.Error(); err != nil { - require.Equal(t, seqTestErr, err) + require.Equal(t, errSeqTest, err) sb.WriteString("!") // error return sb.String() } diff --git a/timesync/peersync/sync.go b/timesync/peersync/sync.go index 80f6f14083..c413a65ad4 100644 --- a/timesync/peersync/sync.go +++ b/timesync/peersync/sync.go @@ -145,7 +145,7 @@ type Sync struct { func (s *Sync) streamHandler(stream network.Stream) { defer stream.Close() - _ = stream.SetDeadline(s.time.Now().Add(s.config.RoundTimeout)) + stream.SetDeadline(s.time.Now().Add(s.config.RoundTimeout)) defer stream.SetDeadline(time.Time{}) var request Request if _, err := codec.DecodeFrom(stream, &request); err != nil { @@ -267,7 +267,7 @@ func (s *Sync) GetOffset(ctx context.Context, id uint64, prs []p2p.Peer) (time.D return } defer stream.Close() - _ = stream.SetDeadline(s.time.Now().Add(s.config.RoundTimeout)) + stream.SetDeadline(s.time.Now().Add(s.config.RoundTimeout)) defer stream.SetDeadline(time.Time{}) if _, err := stream.Write(buf); err != nil { s.log.Debug("failed to send a request", zap.Error(err), zap.Stringer("pid", pid)) diff --git a/timesync/peersync/sync_test.go b/timesync/peersync/sync_test.go index 5e87ff6384..11ad013e27 100644 --- a/timesync/peersync/sync_test.go +++ b/timesync/peersync/sync_test.go @@ -8,6 +8,7 @@ import ( mocknet "github.com/libp2p/go-libp2p/p2p/net/mock" "github.com/spacemeshos/go-scale/tester" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" @@ -47,7 +48,7 @@ func TestSyncGetOffset(t *testing.T) { tm.EXPECT().Now().Return(responseReceive).AnyTimes() for _, h := range mesh.Hosts()[1:] { peers = append(peers, h.ID()) - _ = New(h, nil, WithTime(adjustedTime(peerResponse))) + require.NotNil(t, New(h, nil, WithTime(adjustedTime(peerResponse)))) } sync := New(mesh.Hosts()[0], nil, WithTime(tm)) offset, err := sync.GetOffset(context.TODO(), 0, peers) @@ -106,7 +107,7 @@ func TestSyncTerminateOnError(t *testing.T) { peers := []p2p.Peer{} for _, h := range mesh.Hosts()[1:] { peers = append(peers, h.ID()) - _ = New(h, nil, WithTime(adjustedTime(peerResponse))) + require.NotNil(t, New(h, nil, WithTime(adjustedTime(peerResponse)))) } getter.EXPECT().GetPeers().Return(peers) @@ -139,7 +140,7 @@ func TestSyncSimulateMultiple(t *testing.T) { for _, h := range mesh.Hosts() { fh, err := p2p.Upgrade(h) require.NoError(t, err) - t.Cleanup(func() { _ = fh.Stop() }) + t.Cleanup(func() { assert.NoError(t, fh.Stop()) }) hosts = append(hosts, fh) } require.NoError(t, mesh.ConnectAllButSelf()) diff --git a/txs/conservative_state.go b/txs/conservative_state.go index 7be6f38f07..2b674d7a05 100644 --- a/txs/conservative_state.go +++ b/txs/conservative_state.go @@ -272,7 +272,7 @@ func ShuffleWithNonceOrder( } logger.Debug("packed txs", zap.Array("ranges", zapcore.ArrayMarshalerFunc(func(encoder zapcore.ArrayEncoder) error { for addr, nonces := range packed { - _ = encoder.AppendObject(zapcore.ObjectMarshalerFunc(func(encoder zapcore.ObjectEncoder) error { + encoder.AppendObject(zapcore.ObjectMarshalerFunc(func(encoder zapcore.ObjectEncoder) error { encoder.AddString("addr", addr.String()) encoder.AddUint64("from", nonces[0]) encoder.AddUint64("to", nonces[1]) diff --git a/txs/mempool_iterator.go b/txs/mempool_iterator.go index 4c98bf7b1f..89f6a8bdfa 100644 --- a/txs/mempool_iterator.go +++ b/txs/mempool_iterator.go @@ -152,7 +152,7 @@ func (mi *mempoolIterator) pop() *NanoTX { zap.Uint64("gas_left", mi.gasRemaining), zap.Time("received", top.Received), ) - _ = heap.Pop(&mi.pq) + heap.Pop(&mi.pq) // remove all txs for this principal since we cannot fulfill the lowest nonce for this principal delete(mi.txs, top.Principal) top = nil @@ -174,7 +174,7 @@ func (mi *mempoolIterator) pop() *NanoTX { next := mi.getNext(ntx.Principal) if next == nil { mi.logger.Debug("addr txs exhausted", zap.Stringer("address", ntx.Principal)) - _ = heap.Pop(&mi.pq) + heap.Pop(&mi.pq) } else { mi.logger.Debug("added tx for addr", zap.Stringer("tx_id", next.ID),