From f3c42e3d9c7951333b9f5b9da098144c617998f9 Mon Sep 17 00:00:00 2001 From: yukionfire Date: Thu, 18 Jul 2024 13:14:05 +0800 Subject: [PATCH] chore(all): use `errors.New` to replace `fmt.Errorf` with no parameters --- .../internal/logic/event_update.go | 4 ++-- bridge-history-api/internal/utils/utils.go | 2 +- common/testcontainers/testcontainers.go | 9 +++++---- common/utils/keystore.go | 3 ++- coordinator/internal/controller/api/auth.go | 3 ++- coordinator/internal/controller/api/get_task.go | 9 +++++---- .../logic/provertask/chunk_prover_task.go | 3 ++- .../internal/logic/provertask/prover_task.go | 17 +++++++++-------- .../logic/submitproof/proof_receiver.go | 10 +++++----- coordinator/internal/orm/challenge.go | 3 ++- coordinator/test/api_test.go | 16 ++++++++-------- .../internal/controller/relayer/l1_relayer.go | 3 ++- .../internal/controller/relayer/l2_relayer.go | 9 +++++---- .../internal/controller/sender/estimategas.go | 4 ++-- .../internal/controller/sender/sender_test.go | 6 +++--- 15 files changed, 55 insertions(+), 46 deletions(-) diff --git a/bridge-history-api/internal/logic/event_update.go b/bridge-history-api/internal/logic/event_update.go index 00c93a0f6b..ce8f9a855d 100644 --- a/bridge-history-api/internal/logic/event_update.go +++ b/bridge-history-api/internal/logic/event_update.go @@ -2,7 +2,7 @@ package logic import ( "context" - "fmt" + "errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -153,7 +153,7 @@ func (b *EventUpdateLogic) updateL2WithdrawMessageInfos(ctx context.Context, bat if withdrawTrie.NextMessageNonce != l2WithdrawMessages[0].MessageNonce { log.Error("nonce mismatch", "expected next message nonce", withdrawTrie.NextMessageNonce, "actual next message nonce", l2WithdrawMessages[0].MessageNonce) - return fmt.Errorf("nonce mismatch") + return errors.New("nonce mismatch") } messageHashes := make([]common.Hash, len(l2WithdrawMessages)) diff --git a/bridge-history-api/internal/utils/utils.go b/bridge-history-api/internal/utils/utils.go index 971b9e23be..09cd91c79b 100644 --- a/bridge-history-api/internal/utils/utils.go +++ b/bridge-history-api/internal/utils/utils.go @@ -38,7 +38,7 @@ func GetBlockNumber(ctx context.Context, client *ethclient.Client, confirmations // @todo: add unit test. func UnpackLog(c *abi.ABI, out interface{}, event string, log types.Log) error { if log.Topics[0] != c.Events[event].ID { - return fmt.Errorf("event signature mismatch") + return errors.New("event signature mismatch") } if len(log.Data) > 0 { if err := c.UnpackIntoInterface(out, event, log.Data); err != nil { diff --git a/common/testcontainers/testcontainers.go b/common/testcontainers/testcontainers.go index aa60990350..3a042a9c6f 100644 --- a/common/testcontainers/testcontainers.go +++ b/common/testcontainers/testcontainers.go @@ -2,6 +2,7 @@ package testcontainers import ( "context" + "errors" "fmt" "log" "os" @@ -114,7 +115,7 @@ func (t *TestcontainerApps) StartPoSL1Container() error { // GetPoSL1EndPoint returns the endpoint of the running PoS L1 endpoint func (t *TestcontainerApps) GetPoSL1EndPoint() (string, error) { if t.poSL1Container == nil { - return "", fmt.Errorf("PoS L1 container is not running") + return "", errors.New("PoS L1 container is not running") } contrainer, err := t.poSL1Container.ServiceContainer(context.Background(), "geth") if err != nil { @@ -135,7 +136,7 @@ func (t *TestcontainerApps) GetPoSL1Client() (*ethclient.Client, error) { // GetDBEndPoint returns the endpoint of the running postgres container func (t *TestcontainerApps) GetDBEndPoint() (string, error) { if t.postgresContainer == nil || !t.postgresContainer.IsRunning() { - return "", fmt.Errorf("postgres is not running") + return "", errors.New("postgres is not running") } return t.postgresContainer.ConnectionString(context.Background(), "sslmode=disable") } @@ -143,7 +144,7 @@ func (t *TestcontainerApps) GetDBEndPoint() (string, error) { // GetL2GethEndPoint returns the endpoint of the running L2Geth container func (t *TestcontainerApps) GetL2GethEndPoint() (string, error) { if t.l2GethContainer == nil || !t.l2GethContainer.IsRunning() { - return "", fmt.Errorf("l2 geth is not running") + return "", errors.New("l2 geth is not running") } endpoint, err := t.l2GethContainer.PortEndpoint(context.Background(), "8546/tcp", "ws") if err != nil { @@ -217,7 +218,7 @@ func findProjectRootDir() (string, error) { parentDir := filepath.Dir(currentDir) if parentDir == currentDir { - return "", fmt.Errorf("go.work file not found in any parent directory") + return "", errors.New("go.work file not found in any parent directory") } currentDir = parentDir diff --git a/common/utils/keystore.go b/common/utils/keystore.go index e458dd7adf..32696a1a2a 100644 --- a/common/utils/keystore.go +++ b/common/utils/keystore.go @@ -2,6 +2,7 @@ package utils import ( "crypto/ecdsa" + "errors" "fmt" "os" "path/filepath" @@ -28,7 +29,7 @@ func LoadOrCreateKey(keystorePath string, keystorePassword string) (*ecdsa.Priva } else if err != nil { return nil, err } else if fi.IsDir() { - return nil, fmt.Errorf("keystorePath cannot be a dir") + return nil, errors.New("keystorePath cannot be a dir") } keyjson, err := os.ReadFile(filepath.Clean(keystorePath)) diff --git a/coordinator/internal/controller/api/auth.go b/coordinator/internal/controller/api/auth.go index a071b53213..56f8518d28 100644 --- a/coordinator/internal/controller/api/auth.go +++ b/coordinator/internal/controller/api/auth.go @@ -1,6 +1,7 @@ package api import ( + "errors" "fmt" jwt "github.com/appleboy/gin-jwt/v2" @@ -36,7 +37,7 @@ func (a *AuthController) Login(c *gin.Context) (interface{}, error) { // if not exist, the jwt token will intercept it brearToken := c.GetHeader("Authorization") if brearToken != "Bearer "+login.Message.Challenge { - return "", fmt.Errorf("check challenge failure for the not equal challenge string") + return "", errors.New("check challenge failure for the not equal challenge string") } // check the challenge is used, if used, return failure diff --git a/coordinator/internal/controller/api/get_task.go b/coordinator/internal/controller/api/get_task.go index e9276c6b16..45ddd0c694 100644 --- a/coordinator/internal/controller/api/get_task.go +++ b/coordinator/internal/controller/api/get_task.go @@ -1,6 +1,7 @@ package api import ( + "errors" "fmt" "math/rand" @@ -49,15 +50,15 @@ func NewGetTaskController(cfg *config.Config, chainCfg *params.ChainConfig, db * func (ptc *GetTaskController) incGetTaskAccessCounter(ctx *gin.Context) error { publicKey, publicKeyExist := ctx.Get(coordinatorType.PublicKey) if !publicKeyExist { - return fmt.Errorf("get public key from context failed") + return errors.New("get public key from context failed") } proverName, proverNameExist := ctx.Get(coordinatorType.ProverName) if !proverNameExist { - return fmt.Errorf("get prover name from context failed") + return errors.New("get prover name from context failed") } proverVersion, proverVersionExist := ctx.Get(coordinatorType.ProverVersion) if !proverVersionExist { - return fmt.Errorf("get prover version from context failed") + return errors.New("get prover version from context failed") } ptc.getTaskAccessCounter.With(prometheus.Labels{ @@ -97,7 +98,7 @@ func (ptc *GetTaskController) GetTasks(ctx *gin.Context) { } if result == nil { - nerr := fmt.Errorf("get empty prover task") + nerr := errors.New("get empty prover task") types.RenderFailure(ctx, types.ErrCoordinatorEmptyProofData, nerr) return } diff --git a/coordinator/internal/logic/provertask/chunk_prover_task.go b/coordinator/internal/logic/provertask/chunk_prover_task.go index c15a047a9d..78bbbe61a5 100644 --- a/coordinator/internal/logic/provertask/chunk_prover_task.go +++ b/coordinator/internal/logic/provertask/chunk_prover_task.go @@ -3,6 +3,7 @@ package provertask import ( "context" "encoding/json" + "errors" "fmt" "time" @@ -225,7 +226,7 @@ func (r *blockRange) merge(o blockRange) (*blockRange, error) { } else if r.to == o.from { return &blockRange{r.from, o.to}, nil } - return nil, fmt.Errorf("two ranges are not adjacent") + return nil, errors.New("two ranges are not adjacent") } func (r *blockRange) contains(start, end uint64) bool { diff --git a/coordinator/internal/logic/provertask/prover_task.go b/coordinator/internal/logic/provertask/prover_task.go index 4710365089..10da144847 100644 --- a/coordinator/internal/logic/provertask/prover_task.go +++ b/coordinator/internal/logic/provertask/prover_task.go @@ -1,6 +1,7 @@ package provertask import ( + "errors" "fmt" "sync" @@ -19,9 +20,9 @@ import ( var ( // ErrCoordinatorInternalFailure coordinator internal db failure - ErrCoordinatorInternalFailure = fmt.Errorf("coordinator internal error") + ErrCoordinatorInternalFailure = errors.New("coordinator internal error") // ErrHardForkName indicates client request with the wrong hard fork name - ErrHardForkName = fmt.Errorf("wrong hard fork name") + ErrHardForkName = errors.New("wrong hard fork name") ) // ProverTask the interface of a collector who send data to prover @@ -71,19 +72,19 @@ func (b *BaseProverTask) checkParameter(ctx *gin.Context, getTaskParameter *coor publicKey, publicKeyExist := ctx.Get(coordinatorType.PublicKey) if !publicKeyExist { - return nil, fmt.Errorf("get public key from context failed") + return nil, errors.New("get public key from context failed") } ptc.PublicKey = publicKey.(string) proverName, proverNameExist := ctx.Get(coordinatorType.ProverName) if !proverNameExist { - return nil, fmt.Errorf("get prover name from context failed") + return nil, errors.New("get prover name from context failed") } ptc.ProverName = proverName.(string) proverVersion, proverVersionExist := ctx.Get(coordinatorType.ProverVersion) if !proverVersionExist { - return nil, fmt.Errorf("get prover version from context failed") + return nil, errors.New("get prover version from context failed") } ptc.ProverVersion = proverVersion.(string) @@ -94,7 +95,7 @@ func (b *BaseProverTask) checkParameter(ctx *gin.Context, getTaskParameter *coor // signals that the prover is multi-circuits version if len(getTaskParameter.VKs) > 0 { if len(getTaskParameter.VKs) != 2 { - return nil, fmt.Errorf("parameter vks length must be 2") + return nil, errors.New("parameter vks length must be 2") } for _, vk := range getTaskParameter.VKs { if _, exists := b.reverseVkMap[vk]; !exists { @@ -104,7 +105,7 @@ func (b *BaseProverTask) checkParameter(ctx *gin.Context, getTaskParameter *coor } else { hardForkName, hardForkNameExist := ctx.Get(coordinatorType.HardForkName) if !hardForkNameExist { - return nil, fmt.Errorf("get hard fork name from context failed") + return nil, errors.New("get hard fork name from context failed") } ptc.HardForkName = hardForkName.(string) @@ -121,7 +122,7 @@ func (b *BaseProverTask) checkParameter(ctx *gin.Context, getTaskParameter *coor return nil, fmt.Errorf("incompatible prover version. please upgrade your prover, expect version: %s, actual version: %s", version.Version, proverVersion.(string)) } // if the prover reports a same prover version - return nil, fmt.Errorf("incompatible vk. please check your params files or config files") + return nil, errors.New("incompatible vk. please check your params files or config files") } } diff --git a/coordinator/internal/logic/submitproof/proof_receiver.go b/coordinator/internal/logic/submitproof/proof_receiver.go index dc21ff582b..e4e562c17c 100644 --- a/coordinator/internal/logic/submitproof/proof_receiver.go +++ b/coordinator/internal/logic/submitproof/proof_receiver.go @@ -35,11 +35,11 @@ var ( // ErrValidatorFailureTaskHaveVerifiedSuccess have proved success and verified success ErrValidatorFailureTaskHaveVerifiedSuccess = errors.New("validator failure chunk/batch have proved and verified success") // ErrValidatorFailureVerifiedFailed failed to verify and the verifier returns error - ErrValidatorFailureVerifiedFailed = fmt.Errorf("verification failed, verifier returns error") + ErrValidatorFailureVerifiedFailed = errors.New("verification failed, verifier returns error") // ErrValidatorSuccessInvalidProof successful verified and the proof is invalid - ErrValidatorSuccessInvalidProof = fmt.Errorf("verification succeeded, it's an invalid proof") + ErrValidatorSuccessInvalidProof = errors.New("verification succeeded, it's an invalid proof") // ErrCoordinatorInternalFailure coordinator internal db failure - ErrCoordinatorInternalFailure = fmt.Errorf("coordinator internal error") + ErrCoordinatorInternalFailure = errors.New("coordinator internal error") ) // ProofReceiverLogic the proof receiver logic @@ -128,11 +128,11 @@ func (m *ProofReceiverLogic) HandleZkProof(ctx *gin.Context, proofMsg *message.P m.proofReceivedTotal.Inc() pk := ctx.GetString(coordinatorType.PublicKey) if len(pk) == 0 { - return fmt.Errorf("get public key from context failed") + return errors.New("get public key from context failed") } pv := ctx.GetString(coordinatorType.ProverVersion) if len(pv) == 0 { - return fmt.Errorf("get ProverVersion from context failed") + return errors.New("get ProverVersion from context failed") } // use hard_fork_name from parameter first // if prover support multi hard_forks, the real hard_fork_name is not set to the gin context diff --git a/coordinator/internal/orm/challenge.go b/coordinator/internal/orm/challenge.go index 17d051d257..cf1fba9819 100644 --- a/coordinator/internal/orm/challenge.go +++ b/coordinator/internal/orm/challenge.go @@ -2,6 +2,7 @@ package orm import ( "context" + "errors" "fmt" "time" @@ -53,7 +54,7 @@ func (r *Challenge) InsertChallenge(ctx context.Context, challengeString string) return fmt.Errorf("the challenge string:%s have been used", challengeString) } - return fmt.Errorf("insert challenge string affected rows more than 1") + return errors.New("insert challenge string affected rows more than 1") } // DeleteExpireChallenge delete the expire challenge diff --git a/coordinator/test/api_test.go b/coordinator/test/api_test.go index c0dbea7260..06af3a7dc8 100644 --- a/coordinator/test/api_test.go +++ b/coordinator/test/api_test.go @@ -263,12 +263,12 @@ func testGetTaskBlocked(t *testing.T) { expectedErr := fmt.Errorf("return prover task err:check prover task parameter failed, error:public key %s is blocked from fetching tasks. ProverName: %s, ProverVersion: %s", chunkProver.publicKey(), chunkProver.proverName, chunkProver.proverVersion) code, errMsg := chunkProver.tryGetProverTask(t, message.ProofTypeChunk, "homestead") assert.Equal(t, types.ErrCoordinatorGetTaskFailure, code) - assert.Equal(t, expectedErr, fmt.Errorf(errMsg)) + assert.Equal(t, expectedErr, errors.New(errMsg)) - expectedErr = fmt.Errorf("get empty prover task") + expectedErr = errors.New("get empty prover task") code, errMsg = batchProver.tryGetProverTask(t, message.ProofTypeBatch, "homestead") assert.Equal(t, types.ErrCoordinatorEmptyProofData, code) - assert.Equal(t, expectedErr, fmt.Errorf(errMsg)) + assert.Equal(t, expectedErr, errors.New(errMsg)) err = proverBlockListOrm.InsertProverPublicKey(context.Background(), batchProver.proverName, batchProver.publicKey()) assert.NoError(t, err) @@ -276,15 +276,15 @@ func testGetTaskBlocked(t *testing.T) { err = proverBlockListOrm.DeleteProverPublicKey(context.Background(), chunkProver.publicKey()) assert.NoError(t, err) - expectedErr = fmt.Errorf("get empty prover task") + expectedErr = errors.New("get empty prover task") code, errMsg = chunkProver.tryGetProverTask(t, message.ProofTypeChunk, "homestead") assert.Equal(t, types.ErrCoordinatorEmptyProofData, code) - assert.Equal(t, expectedErr, fmt.Errorf(errMsg)) + assert.Equal(t, expectedErr, errors.New(errMsg)) expectedErr = fmt.Errorf("return prover task err:check prover task parameter failed, error:public key %s is blocked from fetching tasks. ProverName: %s, ProverVersion: %s", batchProver.publicKey(), batchProver.proverName, batchProver.proverVersion) code, errMsg = batchProver.tryGetProverTask(t, message.ProofTypeBatch, "homestead") assert.Equal(t, types.ErrCoordinatorGetTaskFailure, code) - assert.Equal(t, expectedErr, fmt.Errorf(errMsg)) + assert.Equal(t, expectedErr, errors.New(errMsg)) } func testOutdatedProverVersion(t *testing.T) { @@ -304,12 +304,12 @@ func testOutdatedProverVersion(t *testing.T) { expectedErr := fmt.Errorf("return prover task err:check prover task parameter failed, error:incompatible prover version. please upgrade your prover, minimum allowed version: %s, actual version: %s", version.Version, chunkProver.proverVersion) code, errMsg := chunkProver.tryGetProverTask(t, message.ProofTypeChunk, "homestead") assert.Equal(t, types.ErrCoordinatorGetTaskFailure, code) - assert.Equal(t, expectedErr, fmt.Errorf(errMsg)) + assert.Equal(t, expectedErr, errors.New(errMsg)) expectedErr = fmt.Errorf("return prover task err:check prover task parameter failed, error:incompatible prover version. please upgrade your prover, minimum allowed version: %s, actual version: %s", version.Version, batchProver.proverVersion) code, errMsg = batchProver.tryGetProverTask(t, message.ProofTypeBatch, "homestead") assert.Equal(t, types.ErrCoordinatorGetTaskFailure, code) - assert.Equal(t, expectedErr, fmt.Errorf(errMsg)) + assert.Equal(t, expectedErr, errors.New(errMsg)) } func testHardForkAssignTask(t *testing.T) { diff --git a/rollup/internal/controller/relayer/l1_relayer.go b/rollup/internal/controller/relayer/l1_relayer.go index df28475c46..6981dcda2f 100644 --- a/rollup/internal/controller/relayer/l1_relayer.go +++ b/rollup/internal/controller/relayer/l1_relayer.go @@ -2,6 +2,7 @@ package relayer import ( "context" + "errors" "fmt" "math" "math/big" @@ -61,7 +62,7 @@ func NewLayer1Relayer(ctx context.Context, db *gorm.DB, cfg *config.RelayerConfi // Ensure test features aren't enabled on the scroll mainnet. if gasOracleSender.GetChainID().Cmp(big.NewInt(534352)) == 0 && cfg.EnableTestEnvBypassFeatures { - return nil, fmt.Errorf("cannot enable test env features in mainnet") + return nil, errors.New("cannot enable test env features in mainnet") } default: return nil, fmt.Errorf("invalid service type for l1_relayer: %v", serviceType) diff --git a/rollup/internal/controller/relayer/l2_relayer.go b/rollup/internal/controller/relayer/l2_relayer.go index eacb11f8aa..02368f73c4 100644 --- a/rollup/internal/controller/relayer/l2_relayer.go +++ b/rollup/internal/controller/relayer/l2_relayer.go @@ -2,6 +2,7 @@ package relayer import ( "context" + "errors" "fmt" "math/big" "sort" @@ -83,7 +84,7 @@ func NewLayer2Relayer(ctx context.Context, l2Client *ethclient.Client, db *gorm. // Ensure test features aren't enabled on the ethereum mainnet. if gasOracleSender.GetChainID().Cmp(big.NewInt(1)) == 0 && cfg.EnableTestEnvBypassFeatures { - return nil, fmt.Errorf("cannot enable test env features in mainnet") + return nil, errors.New("cannot enable test env features in mainnet") } case ServiceTypeL2RollupRelayer: @@ -101,7 +102,7 @@ func NewLayer2Relayer(ctx context.Context, l2Client *ethclient.Client, db *gorm. // Ensure test features aren't enabled on the ethereum mainnet. if commitSender.GetChainID().Cmp(big.NewInt(1)) == 0 && cfg.EnableTestEnvBypassFeatures { - return nil, fmt.Errorf("cannot enable test env features in mainnet") + return nil, errors.New("cannot enable test env features in mainnet") } default: @@ -278,7 +279,7 @@ func (r *Layer2Relayer) commitGenesisBatch(batchHash string, batchHeader []byte, return fmt.Errorf("unexpected import genesis confirmation id, expected: %v, got: %v", batchHash, confirmation.ContextID) } if !confirmation.IsSuccessful { - return fmt.Errorf("import genesis batch tx failed") + return errors.New("import genesis batch tx failed") } log.Info("Successfully committed genesis batch on L1", "txHash", confirmation.TxHash.String()) return nil @@ -514,7 +515,7 @@ func (r *Layer2Relayer) finalizeBatch(dbBatch *orm.Batch, withProof bool) error } if dbBatch.Index == 0 { - return fmt.Errorf("invalid args: batch index is 0, should only happen in finalizing genesis batch") + return errors.New("invalid args: batch index is 0, should only happen in finalizing genesis batch") } dbParentBatch, getErr := r.batchOrm.GetBatchByIndex(r.ctx, dbBatch.Index-1) diff --git a/rollup/internal/controller/sender/estimategas.go b/rollup/internal/controller/sender/estimategas.go index 883e516eb2..b1e3682373 100644 --- a/rollup/internal/controller/sender/estimategas.go +++ b/rollup/internal/controller/sender/estimategas.go @@ -1,7 +1,7 @@ package sender import ( - "fmt" + "errors" "math/big" "github.com/scroll-tech/go-ethereum" @@ -150,7 +150,7 @@ func (s *Sender) estimateGasLimit(to *common.Address, data []byte, sidecar *geth } if errStr != "" { log.Error("CreateAccessList reported error", "error", errStr) - return gasLimitWithoutAccessList, nil, fmt.Errorf(errStr) + return gasLimitWithoutAccessList, nil, errors.New(errStr) } // Fine-tune accessList because 'to' address is automatically included in the access list by the Ethereum protocol: https://github.com/ethereum/go-ethereum/blob/v1.13.10/core/state/statedb.go#L1322 diff --git a/rollup/internal/controller/sender/sender_test.go b/rollup/internal/controller/sender/sender_test.go index b9491af314..d4b2968898 100644 --- a/rollup/internal/controller/sender/sender_test.go +++ b/rollup/internal/controller/sender/sender_test.go @@ -585,7 +585,7 @@ func testCheckPendingTransactionResubmitTxConfirmed(t *testing.T) { patchGuard2 := gomonkey.ApplyMethodFunc(s.client, "TransactionReceipt", func(_ context.Context, hash common.Hash) (*gethTypes.Receipt, error) { if hash == originTxHash { - return nil, fmt.Errorf("simulated transaction receipt error") + return nil, errors.New("simulated transaction receipt error") } return &gethTypes.Receipt{TxHash: hash, BlockNumber: big.NewInt(0), Status: gethTypes.ReceiptStatusSuccessful}, nil }) @@ -657,7 +657,7 @@ func testCheckPendingTransactionReplacedTxConfirmed(t *testing.T) { Status: gethTypes.ReceiptStatusSuccessful, }, nil } - return nil, fmt.Errorf("simulated transaction receipt error") + return nil, errors.New("simulated transaction receipt error") }) // Attempt to resubmit the transaction. @@ -714,7 +714,7 @@ func testCheckPendingTransactionTxMultipleTimesWithOnlyOneTxPending(t *testing.T assert.Equal(t, types.SenderTypeCommitBatch, txs[0].SenderType) patchGuard2 := gomonkey.ApplyMethodFunc(s.client, "TransactionReceipt", func(_ context.Context, hash common.Hash) (*gethTypes.Receipt, error) { - return nil, fmt.Errorf("simulated transaction receipt error") + return nil, errors.New("simulated transaction receipt error") }) for i := 1; i <= 6; i++ {