all: replace fmt.Errorf with errors.New (#32286)

The errors.new function does not require string formatting, so its
performance is better than that of fmt.Errorf.
This commit is contained in:
ericxtheodore 2025-07-28 16:13:18 +08:00 committed by GitHub
parent a7aed7bd6f
commit 32d537cd58
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 31 additions and 28 deletions

View file

@ -129,7 +129,7 @@ func (c *Conn) Write(proto Proto, code uint64, msg any) error {
return err return err
} }
var errDisc error = fmt.Errorf("disconnect") var errDisc error = errors.New("disconnect")
// ReadEth reads an Eth sub-protocol wire message. // ReadEth reads an Eth sub-protocol wire message.
func (c *Conn) ReadEth() (any, error) { func (c *Conn) ReadEth() (any, error) {

View file

@ -19,6 +19,7 @@ package ethtest
import ( import (
"context" "context"
"crypto/rand" "crypto/rand"
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sync" "sync"
@ -1092,7 +1093,7 @@ func (s *Suite) testBadBlobTx(t *utesting.T, tx *types.Transaction, badTx *types
return return
} }
if !readUntilDisconnect(conn) { if !readUntilDisconnect(conn) {
errc <- fmt.Errorf("expected bad peer to be disconnected") errc <- errors.New("expected bad peer to be disconnected")
return return
} }
stage3.Done() stage3.Done()
@ -1139,7 +1140,7 @@ func (s *Suite) testBadBlobTx(t *utesting.T, tx *types.Transaction, badTx *types
} }
if req.GetPooledTransactionsRequest[0] != tx.Hash() { if req.GetPooledTransactionsRequest[0] != tx.Hash() {
errc <- fmt.Errorf("requested unknown tx hash") errc <- errors.New("requested unknown tx hash")
return return
} }
@ -1149,7 +1150,7 @@ func (s *Suite) testBadBlobTx(t *utesting.T, tx *types.Transaction, badTx *types
return return
} }
if readUntilDisconnect(conn) { if readUntilDisconnect(conn) {
errc <- fmt.Errorf("unexpected disconnect") errc <- errors.New("unexpected disconnect")
return return
} }
close(errc) close(errc)

View file

@ -716,7 +716,7 @@ func downloadEra(ctx *cli.Context) error {
case ctx.IsSet(utils.SepoliaFlag.Name): case ctx.IsSet(utils.SepoliaFlag.Name):
network = "sepolia" network = "sepolia"
default: default:
return fmt.Errorf("unsupported network, no known era1 checksums") return errors.New("unsupported network, no known era1 checksums")
} }
} }

View file

@ -18,7 +18,7 @@ package main
import ( import (
"embed" "embed"
"fmt" "errors"
"io/fs" "io/fs"
"os" "os"
@ -97,7 +97,7 @@ type testConfig struct {
traceTestFile string traceTestFile string
} }
var errPrunedHistory = fmt.Errorf("attempt to access pruned history") var errPrunedHistory = errors.New("attempt to access pruned history")
// validateHistoryPruneErr checks whether the given error is caused by access // validateHistoryPruneErr checks whether the given error is caused by access
// to history before the pruning threshold block (it is an rpc.Error with code 4444). // to history before the pruning threshold block (it is an rpc.Error with code 4444).
@ -109,7 +109,7 @@ func validateHistoryPruneErr(err error, blockNum uint64, historyPruneBlock *uint
if err != nil { if err != nil {
if rpcErr, ok := err.(rpc.Error); ok && rpcErr.ErrorCode() == 4444 { if rpcErr, ok := err.(rpc.Error); ok && rpcErr.ErrorCode() == 4444 {
if historyPruneBlock != nil && blockNum > *historyPruneBlock { if historyPruneBlock != nil && blockNum > *historyPruneBlock {
return fmt.Errorf("pruned history error returned after pruning threshold") return errors.New("pruned history error returned after pruning threshold")
} }
return errPrunedHistory return errPrunedHistory
} }

View file

@ -350,7 +350,7 @@ func iterateJournal(db ethdb.KeyValueReader, callback journalCallback) error {
} }
if len(destructs) > 0 { if len(destructs) > 0 {
log.Warn("Incompatible legacy journal detected", "version", journalV0) log.Warn("Incompatible legacy journal detected", "version", journalV0)
return fmt.Errorf("incompatible legacy journal detected") return errors.New("incompatible legacy journal detected")
} }
} }
if err := r.Decode(&accounts); err != nil { if err := r.Decode(&accounts); err != nil {

View file

@ -17,7 +17,7 @@
package tracing package tracing
import ( import (
"fmt" "errors"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -39,14 +39,14 @@ type entry interface {
// WrapWithJournal wraps the given tracer with a journaling layer. // WrapWithJournal wraps the given tracer with a journaling layer.
func WrapWithJournal(hooks *Hooks) (*Hooks, error) { func WrapWithJournal(hooks *Hooks) (*Hooks, error) {
if hooks == nil { if hooks == nil {
return nil, fmt.Errorf("wrapping nil tracer") return nil, errors.New("wrapping nil tracer")
} }
// No state change to journal, return the wrapped hooks as is // No state change to journal, return the wrapped hooks as is
if hooks.OnBalanceChange == nil && hooks.OnNonceChange == nil && hooks.OnNonceChangeV2 == nil && hooks.OnCodeChange == nil && hooks.OnStorageChange == nil { if hooks.OnBalanceChange == nil && hooks.OnNonceChange == nil && hooks.OnNonceChangeV2 == nil && hooks.OnCodeChange == nil && hooks.OnStorageChange == nil {
return hooks, nil return hooks, nil
} }
if hooks.OnNonceChange != nil && hooks.OnNonceChangeV2 != nil { if hooks.OnNonceChange != nil && hooks.OnNonceChangeV2 != nil {
return nil, fmt.Errorf("cannot have both OnNonceChange and OnNonceChangeV2") return nil, errors.New("cannot have both OnNonceChange and OnNonceChangeV2")
} }
// Create a new Hooks instance and copy all hooks // Create a new Hooks instance and copy all hooks

View file

@ -145,7 +145,7 @@ func ValidateTransaction(tx *types.Transaction, head *types.Header, signer types
} }
if tx.Type() == types.SetCodeTxType { if tx.Type() == types.SetCodeTxType {
if len(tx.SetCodeAuthorizations()) == 0 { if len(tx.SetCodeAuthorizations()) == 0 {
return fmt.Errorf("set code tx must have at least one authorization tuple") return errors.New("set code tx must have at least one authorization tuple")
} }
} }
return nil return nil

View file

@ -169,7 +169,7 @@ func (e *AccountAccess) validate() error {
// Convert code change // Convert code change
if len(e.Code) == 1 { if len(e.Code) == 1 {
if len(e.Code[0].Code) > params.MaxCodeSize { if len(e.Code[0].Code) > params.MaxCodeSize {
return fmt.Errorf("code change contained oversized code") return errors.New("code change contained oversized code")
} }
} }
return nil return nil

View file

@ -1497,7 +1497,7 @@ func checkEqualBody(a *types.Body, b *engine.ExecutionPayloadBody) error {
} }
} }
if !reflect.DeepEqual(a.Withdrawals, b.Withdrawals) { if !reflect.DeepEqual(a.Withdrawals, b.Withdrawals) {
return fmt.Errorf("withdrawals mismatch") return errors.New("withdrawals mismatch")
} }
return nil return nil
} }

View file

@ -18,7 +18,7 @@
package ethconfig package ethconfig
import ( import (
"fmt" "errors"
"time" "time"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -171,7 +171,7 @@ type Config struct {
func CreateConsensusEngine(config *params.ChainConfig, db ethdb.Database) (consensus.Engine, error) { func CreateConsensusEngine(config *params.ChainConfig, db ethdb.Database) (consensus.Engine, error) {
if config.TerminalTotalDifficulty == nil { if config.TerminalTotalDifficulty == nil {
log.Error("Geth only supports PoS networks. Please transition legacy networks using Geth v1.13.x.") log.Error("Geth only supports PoS networks. Please transition legacy networks using Geth v1.13.x.")
return nil, fmt.Errorf("'terminalTotalDifficulty' is not set in genesis block") return nil, errors.New("'terminalTotalDifficulty' is not set in genesis block")
} }
// Wrap previously supported consensus engines into their post-merge counterpart // Wrap previously supported consensus engines into their post-merge counterpart
if config.Clique != nil { if config.Clique != nil {

View file

@ -22,6 +22,7 @@ package leveldb
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"sync" "sync"
"time" "time"
@ -31,7 +32,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/metrics"
"github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/errors" lerrors "github.com/syndtr/goleveldb/leveldb/errors"
"github.com/syndtr/goleveldb/leveldb/filter" "github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/opt" "github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util" "github.com/syndtr/goleveldb/leveldb/util"
@ -120,7 +121,7 @@ func NewCustom(file string, namespace string, customize func(options *opt.Option
// Open the db and recover any potential corruptions // Open the db and recover any potential corruptions
db, err := leveldb.OpenFile(file, options) db, err := leveldb.OpenFile(file, options)
if _, corrupted := err.(*errors.ErrCorrupted); corrupted { if _, corrupted := err.(*lerrors.ErrCorrupted); corrupted {
db, err = leveldb.RecoverFile(file, nil) db, err = leveldb.RecoverFile(file, nil)
} }
if err != nil { if err != nil {
@ -548,7 +549,7 @@ func (r *replayer) DeleteRange(start, end []byte) {
if rangeDeleter, ok := r.writer.(ethdb.KeyValueRangeDeleter); ok { if rangeDeleter, ok := r.writer.(ethdb.KeyValueRangeDeleter); ok {
r.failure = rangeDeleter.DeleteRange(start, end) r.failure = rangeDeleter.DeleteRange(start, end)
} else { } else {
r.failure = fmt.Errorf("ethdb.KeyValueWriter does not implement DeleteRange") r.failure = errors.New("ethdb.KeyValueWriter does not implement DeleteRange")
} }
} }

View file

@ -20,7 +20,6 @@ package memorydb
import ( import (
"bytes" "bytes"
"errors" "errors"
"fmt"
"sort" "sort"
"strings" "strings"
"sync" "sync"
@ -327,7 +326,7 @@ func (b *batch) Replay(w ethdb.KeyValueWriter) error {
return err return err
} }
} else { } else {
return fmt.Errorf("ethdb.KeyValueWriter does not implement DeleteRange") return errors.New("ethdb.KeyValueWriter does not implement DeleteRange")
} }
} }
continue continue

View file

@ -18,6 +18,7 @@
package pebble package pebble
import ( import (
"errors"
"fmt" "fmt"
"runtime" "runtime"
"strings" "strings"
@ -705,7 +706,7 @@ func (b *batch) Replay(w ethdb.KeyValueWriter) error {
return err return err
} }
} else { } else {
return fmt.Errorf("ethdb.KeyValueWriter does not implement DeleteRange") return errors.New("ethdb.KeyValueWriter does not implement DeleteRange")
} }
} else { } else {
return fmt.Errorf("unhandled operation, keytype: %v", kind) return fmt.Errorf("unhandled operation, keytype: %v", kind)

View file

@ -151,7 +151,7 @@ func (args *SendTxArgs) ToTransaction() (*types.Transaction, error) {
al = *args.AccessList al = *args.AccessList
} }
if to == nil { if to == nil {
return nil, fmt.Errorf("transaction recipient must be set for blob transactions") return nil, errors.New("transaction recipient must be set for blob transactions")
} }
data = &types.BlobTx{ data = &types.BlobTx{
To: *to, To: *to,

View file

@ -17,6 +17,7 @@
package tests package tests
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
@ -43,7 +44,7 @@ type ttFork struct {
func (tt *TransactionTest) validate() error { func (tt *TransactionTest) validate() error {
if tt.Txbytes == nil { if tt.Txbytes == nil {
return fmt.Errorf("missing txbytes") return errors.New("missing txbytes")
} }
for name, fork := range tt.Result { for name, fork := range tt.Result {
if err := tt.validateFork(fork); err != nil { if err := tt.validateFork(fork); err != nil {
@ -58,10 +59,10 @@ func (tt *TransactionTest) validateFork(fork *ttFork) error {
return nil return nil
} }
if fork.Hash == nil && fork.Exception == nil { if fork.Hash == nil && fork.Exception == nil {
return fmt.Errorf("missing hash and exception") return errors.New("missing hash and exception")
} }
if fork.Hash != nil && fork.Sender == nil { if fork.Hash != nil && fork.Sender == nil {
return fmt.Errorf("missing sender") return errors.New("missing sender")
} }
return nil return nil
} }

View file

@ -353,7 +353,7 @@ func (d *indexDeleter) empty() bool {
// pop removes the last written element from the index writer. // pop removes the last written element from the index writer.
func (d *indexDeleter) pop(id uint64) error { func (d *indexDeleter) pop(id uint64) error {
if id == 0 { if id == 0 {
return fmt.Errorf("zero history ID is not valid") return errors.New("zero history ID is not valid")
} }
if id != d.lastID { if id != d.lastID {
return fmt.Errorf("pop element out of order, last: %d, this: %d", d.lastID, id) return fmt.Errorf("pop element out of order, last: %d, this: %d", d.lastID, id)