Skip to content

Commit

Permalink
chore(all): use errors.New to replace fmt.Errorf with no parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
yukionfire committed Jul 18, 2024
1 parent 61ab085 commit f3c42e3
Show file tree
Hide file tree
Showing 15 changed files with 55 additions and 46 deletions.
4 changes: 2 additions & 2 deletions bridge-history-api/internal/logic/event_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package logic

import (
"context"
"fmt"
"errors"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion bridge-history-api/internal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 5 additions & 4 deletions common/testcontainers/testcontainers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package testcontainers

import (
"context"
"errors"
"fmt"
"log"
"os"
Expand Down Expand Up @@ -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 {
Expand All @@ -135,15 +136,15 @@ 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")
}

// 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 {
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion common/utils/keystore.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"crypto/ecdsa"
"errors"
"fmt"
"os"
"path/filepath"
Expand All @@ -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))
Expand Down
3 changes: 2 additions & 1 deletion coordinator/internal/controller/api/auth.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"errors"
"fmt"

jwt "github.com/appleboy/gin-jwt/v2"
Expand Down Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions coordinator/internal/controller/api/get_task.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"errors"
"fmt"
"math/rand"

Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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
}
Expand Down
3 changes: 2 additions & 1 deletion coordinator/internal/logic/provertask/chunk_prover_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package provertask
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"

Expand Down Expand Up @@ -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 {
Expand Down
17 changes: 9 additions & 8 deletions coordinator/internal/logic/provertask/prover_task.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package provertask

import (
"errors"
"fmt"
"sync"

Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand All @@ -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 {
Expand All @@ -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)

Expand All @@ -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")
}
}

Expand Down
10 changes: 5 additions & 5 deletions coordinator/internal/logic/submitproof/proof_receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion coordinator/internal/orm/challenge.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package orm

import (
"context"
"errors"
"fmt"
"time"

Expand Down Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions coordinator/test/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,28 +263,28 @@ 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)

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) {
Expand All @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion rollup/internal/controller/relayer/l1_relayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package relayer

import (
"context"
"errors"
"fmt"
"math"
"math/big"
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 5 additions & 4 deletions rollup/internal/controller/relayer/l2_relayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package relayer

import (
"context"
"errors"
"fmt"
"math/big"
"sort"
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading

0 comments on commit f3c42e3

Please sign in to comment.