Skip to content

Commit

Permalink
all: use errors.New() when there is no param rather than fmt.Errorf() (
Browse files Browse the repository at this point in the history
  • Loading branch information
yasyzb authored Mar 11, 2024
1 parent 4051c34 commit 6386172
Show file tree
Hide file tree
Showing 38 changed files with 94 additions and 80 deletions.
7 changes: 4 additions & 3 deletions cmd/extradump/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package main
import (
"bytes"
"encoding/hex"
"errors"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -78,7 +79,7 @@ func parseExtra(hexData string) (*Extra, error) {
// decode hex into bytes
data, err := hex.DecodeString(strings.TrimPrefix(hexData, "0x"))
if err != nil {
return nil, fmt.Errorf("invalid hex data")
return nil, errors.New("invalid hex data")
}

// parse ExtraVanity and ExtraSeal
Expand All @@ -99,7 +100,7 @@ func parseExtra(hexData string) (*Extra, error) {
validatorNum := int(data[0])
validatorBytesTotalLength := validatorNumberSize + validatorNum*validatorBytesLength
if dataLength < validatorBytesTotalLength {
return nil, fmt.Errorf("parse validators failed")
return nil, errors.New("parse validators failed")
}
extra.ValidatorSize = uint8(validatorNum)
data = data[validatorNumberSize:]
Expand All @@ -117,7 +118,7 @@ func parseExtra(hexData string) (*Extra, error) {
// parse Vote Attestation
if dataLength > 0 {
if err := rlp.Decode(bytes.NewReader(data), &extra.VoteAttestation); err != nil {
return nil, fmt.Errorf("parse voteAttestation failed")
return nil, errors.New("parse voteAttestation failed")
}
if extra.ValidatorSize > 0 {
validatorsBitSet := bitset.From([]uint64{uint64(extra.VoteAddressSet)})
Expand Down
2 changes: 1 addition & 1 deletion cmd/geth/chaincmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ func parseDumpConfig(ctx *cli.Context, stack *node.Node) (*state.DumpConfig, eth
if stateRoot := triedb.Head(); stateRoot != (common.Hash{}) {
header.Root = stateRoot
} else {
return nil, nil, common.Hash{}, fmt.Errorf("no top state root hash in path db")
return nil, nil, common.Hash{}, errors.New("no top state root hash in path db")
}
} else {
header = rawdb.ReadHeadHeader(db)
Expand Down
7 changes: 4 additions & 3 deletions cmd/geth/dbcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package main

import (
"bytes"
"errors"
"fmt"
"math"
"os"
Expand Down Expand Up @@ -410,7 +411,7 @@ func inspectTrie(ctx *cli.Context) error {
if blockNumber != math.MaxUint64 {
headerBlockHash = rawdb.ReadCanonicalHash(db, blockNumber)
if headerBlockHash == (common.Hash{}) {
return fmt.Errorf("ReadHeadBlockHash empry hash")
return errors.New("ReadHeadBlockHash empry hash")
}
blockHeader := rawdb.ReadHeader(db, headerBlockHash, blockNumber)
trieRootHash = blockHeader.Root
Expand Down Expand Up @@ -1151,15 +1152,15 @@ func hbss2pbss(ctx *cli.Context) error {
if *blockNumber != math.MaxUint64 {
headerBlockHash = rawdb.ReadCanonicalHash(db, *blockNumber)
if headerBlockHash == (common.Hash{}) {
return fmt.Errorf("ReadHeadBlockHash empty hash")
return errors.New("ReadHeadBlockHash empty hash")
}
blockHeader := rawdb.ReadHeader(db, headerBlockHash, *blockNumber)
trieRootHash = blockHeader.Root
fmt.Println("Canonical Hash: ", headerBlockHash.String(), ", TrieRootHash: ", trieRootHash.String())
}
if (trieRootHash == common.Hash{}) {
log.Error("Empty root hash")
return fmt.Errorf("Empty root hash.")
return errors.New("Empty root hash.")
}

id := trie.StateTrieID(trieRootHash)
Expand Down
Binary file added cmd/geth/geth
Binary file not shown.
4 changes: 2 additions & 2 deletions consensus/parlia/feynmanfork.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package parlia
import (
"container/heap"
"context"
"fmt"
"errors"
"math"
"math/big"

Expand Down Expand Up @@ -159,7 +159,7 @@ func (p *Parlia) getValidatorElectionInfo(blockNr rpc.BlockNumberOrHash) ([]Vali
return nil, err
}
if totalLength.Int64() != int64(len(validators)) || totalLength.Int64() != int64(len(votingPowers)) || totalLength.Int64() != int64(len(voteAddrs)) {
return nil, fmt.Errorf("validator length not match")
return nil, errors.New("validator length not match")
}

validatorItems := make([]ValidatorItem, len(validators))
Expand Down
28 changes: 14 additions & 14 deletions consensus/parlia/parlia.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header
return nil
}
if attestation.Data == nil {
return fmt.Errorf("invalid attestation, vote data is nil")
return errors.New("invalid attestation, vote data is nil")
}
if len(attestation.Extra) > types.MaxAttestationExtraLength {
return fmt.Errorf("invalid attestation, too large extra length: %d", len(attestation.Extra))
Expand Down Expand Up @@ -464,7 +464,7 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header
}
justifiedBlockNumber, justifiedBlockHash, err := p.GetJustifiedNumberAndHash(chain, headers)
if err != nil {
return fmt.Errorf("unexpected error when getting the highest justified number and hash")
return errors.New("unexpected error when getting the highest justified number and hash")
}
if sourceNumber != justifiedBlockNumber || sourceHash != justifiedBlockHash {
return fmt.Errorf("invalid attestation, source mismatch, expected block: %d, hash: %s; real block: %d, hash: %s",
Expand All @@ -486,7 +486,7 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header
validators := snap.validators()
validatorsBitSet := bitset.From([]uint64{uint64(attestation.VoteAddressSet)})
if validatorsBitSet.Count() > uint(len(validators)) {
return fmt.Errorf("invalid attestation, vote number larger than validators number")
return errors.New("invalid attestation, vote number larger than validators number")
}
votedAddrs := make([]bls.PublicKey, 0, validatorsBitSet.Count())
for index, val := range validators {
Expand All @@ -503,7 +503,7 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header

// The valid voted validators should be no less than 2/3 validators.
if len(votedAddrs) < cmath.CeilDiv(len(snap.Validators)*2, 3) {
return fmt.Errorf("invalid attestation, not enough validators voted")
return errors.New("invalid attestation, not enough validators voted")
}

// Verify the aggregated signature.
Expand All @@ -512,7 +512,7 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header
return fmt.Errorf("BLS signature converts failed: %v", err)
}
if !aggSig.FastAggregateVerify(votedAddrs, attestation.Data.Hash()) {
return fmt.Errorf("invalid attestation, signature verify failed")
return errors.New("invalid attestation, signature verify failed")
}

return nil
Expand Down Expand Up @@ -892,7 +892,7 @@ func (p *Parlia) assembleVoteAttestation(chain consensus.ChainHeaderReader, head
// Prepare vote data
justifiedBlockNumber, justifiedBlockHash, err := p.GetJustifiedNumberAndHash(chain, []*types.Header{parent})
if err != nil {
return fmt.Errorf("unexpected error when getting the highest justified number and hash")
return errors.New("unexpected error when getting the highest justified number and hash")
}
attestation := &types.VoteAttestation{
Data: &types.VoteData{
Expand Down Expand Up @@ -929,7 +929,7 @@ func (p *Parlia) assembleVoteAttestation(chain consensus.ChainHeaderReader, head
validatorsBitSet := bitset.From([]uint64{uint64(attestation.VoteAddressSet)})
if validatorsBitSet.Count() < uint(len(signatures)) {
log.Warn(fmt.Sprintf("assembleVoteAttestation, check VoteAddress Set failed, expected:%d, real:%d", len(signatures), validatorsBitSet.Count()))
return fmt.Errorf("invalid attestation, check VoteAddress Set failed")
return errors.New("invalid attestation, check VoteAddress Set failed")
}

// Append attestation to header extra field.
Expand Down Expand Up @@ -1342,27 +1342,27 @@ func (p *Parlia) VerifyVote(chain consensus.ChainHeaderReader, vote *types.VoteE
header := chain.GetHeaderByHash(targetHash)
if header == nil {
log.Warn("BlockHeader at current voteBlockNumber is nil", "targetNumber", targetNumber, "targetHash", targetHash)
return fmt.Errorf("BlockHeader at current voteBlockNumber is nil")
return errors.New("BlockHeader at current voteBlockNumber is nil")
}
if header.Number.Uint64() != targetNumber {
log.Warn("unexpected target number", "expect", header.Number.Uint64(), "real", targetNumber)
return fmt.Errorf("target number mismatch")
return errors.New("target number mismatch")
}

justifiedBlockNumber, justifiedBlockHash, err := p.GetJustifiedNumberAndHash(chain, []*types.Header{header})
if err != nil {
log.Error("failed to get the highest justified number and hash", "headerNumber", header.Number, "headerHash", header.Hash())
return fmt.Errorf("unexpected error when getting the highest justified number and hash")
return errors.New("unexpected error when getting the highest justified number and hash")
}
if vote.Data.SourceNumber != justifiedBlockNumber || vote.Data.SourceHash != justifiedBlockHash {
return fmt.Errorf("vote source block mismatch")
return errors.New("vote source block mismatch")
}

number := header.Number.Uint64()
snap, err := p.snapshot(chain, number-1, header.ParentHash, nil)
if err != nil {
log.Error("failed to get the snapshot from consensus", "error", err)
return fmt.Errorf("failed to get the snapshot from consensus")
return errors.New("failed to get the snapshot from consensus")
}

validators := snap.Validators
Expand All @@ -1377,7 +1377,7 @@ func (p *Parlia) VerifyVote(chain consensus.ChainHeaderReader, vote *types.VoteE
}
}

return fmt.Errorf("vote verification failed")
return errors.New("vote verification failed")
}

// Authorize injects a private key into the consensus engine to mint new blocks
Expand Down Expand Up @@ -1836,7 +1836,7 @@ func (p *Parlia) applyTransaction(
// within the branch including `headers` and utilizing the latest element as the head.
func (p *Parlia) GetJustifiedNumberAndHash(chain consensus.ChainHeaderReader, headers []*types.Header) (uint64, common.Hash, error) {
if chain == nil || len(headers) == 0 || headers[len(headers)-1] == nil {
return 0, common.Hash{}, fmt.Errorf("illegal chain or header")
return 0, common.Hash{}, errors.New("illegal chain or header")
}
head := headers[len(headers)-1]
snap, err := p.snapshot(chain, head.Number.Uint64(), head.Hash(), headers)
Expand Down
2 changes: 1 addition & 1 deletion core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -2952,7 +2952,7 @@ func (bc *BlockChain) GetTrustedDiffLayer(blockHash common.Hash) *types.DiffLaye

func CalculateDiffHash(d *types.DiffLayer) (common.Hash, error) {
if d == nil {
return common.Hash{}, fmt.Errorf("nil diff layer")
return common.Hash{}, errors.New("nil diff layer")
}

diff := &types.ExtDiffLayer{
Expand Down
2 changes: 1 addition & 1 deletion core/rawdb/freezer_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -1004,7 +1004,7 @@ func (t *freezerTable) ResetItemsOffset(virtualTail uint64) error {
}

if stat.Size() == 0 {
return fmt.Errorf("Stat size is zero when ResetVirtualTail.")
return errors.New("Stat size is zero when ResetVirtualTail.")
}

var firstIndex indexEntry
Expand Down
4 changes: 2 additions & 2 deletions core/state/statedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,7 @@ func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
if s.trie == nil {
tr, err := s.db.OpenTrie(s.originalRoot)
if err != nil {
s.setError(fmt.Errorf("failed to open trie tree"))
s.setError(errors.New("failed to open trie tree"))

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / unit-test (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / golang-lint (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / golang-lint (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / golang-lint (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / unit-test (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / Build Release (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 750 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / Build Release (1.21.x, macos-latest)

undefined: errors
return nil
}
s.trie = tr
Expand Down Expand Up @@ -1003,7 +1003,7 @@ func (s *StateDB) WaitPipeVerification() error {
// Need to wait for the parent trie to commit
if s.snap != nil {
if valid := s.snap.WaitAndGetVerifyRes(); !valid {
return fmt.Errorf("verification on parent snap failed")
return errors.New("verification on parent snap failed")

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / unit-test (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / golang-lint (1.21.x, ubuntu-latest)

undefined: errors) (typecheck)

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / golang-lint (1.21.x, ubuntu-latest)

undefined: errors) (typecheck)

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / golang-lint (1.21.x, ubuntu-latest)

undefined: errors) (typecheck)

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / unit-test (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / Build Release (1.21.x, ubuntu-latest)

undefined: errors

Check failure on line 1006 in core/state/statedb.go

View workflow job for this annotation

GitHub Actions / Build Release (1.21.x, macos-latest)

undefined: errors
}
}
return nil
Expand Down
2 changes: 1 addition & 1 deletion core/state_prefetcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func CheckNoGoroutines(key, value string) error {
var pb bytes.Buffer
profiler := pprof.Lookup("goroutine")
if profiler == nil {
return fmt.Errorf("unable to find profile")
return errors.New("unable to find profile")
}
err := profiler.WriteTo(&pb, 0)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg

lastBlock := p.bc.GetBlockByHash(block.ParentHash())
if lastBlock == nil {
return statedb, nil, nil, 0, fmt.Errorf("could not get parent block")
return statedb, nil, nil, 0, errors.New("could not get parent block")
}
if !p.config.IsFeynman(block.Number(), block.Time()) {
// Handle upgrade build-in system contract code
Expand Down
4 changes: 2 additions & 2 deletions core/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,10 +397,10 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
if st.evm.ChainConfig().IsNano(st.evm.Context.BlockNumber) {
for _, blackListAddr := range types.NanoBlackList {
if blackListAddr == msg.From {
return nil, fmt.Errorf("block blacklist account")
return nil, errors.New("block blacklist account")
}
if msg.To != nil && *msg.To == blackListAddr {
return nil, fmt.Errorf("block blacklist account")
return nil, errors.New("block blacklist account")
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion core/txpool/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package txpool

import (
"crypto/sha256"
"errors"
"fmt"
"math/big"

Expand Down Expand Up @@ -118,7 +119,7 @@ func ValidateTransaction(tx *types.Transaction, head *types.Header, signer types
// data match up before doing any expensive validations
hashes := tx.BlobHashes()
if len(hashes) == 0 {
return fmt.Errorf("blobless blob transaction")
return errors.New("blobless blob transaction")
}
if len(hashes) > params.MaxBlobGasPerBlock/params.BlobTxBlobGasPerBlob {
return fmt.Errorf("too many blobs in transaction: have %d, permitted %d", len(hashes), params.MaxBlobGasPerBlock/params.BlobTxBlobGasPerBlob)
Expand Down
13 changes: 7 additions & 6 deletions core/vm/contracts_lightclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package vm

import (
"encoding/binary"
"errors"
"fmt"
"net/url"
"strings"
Expand Down Expand Up @@ -68,7 +69,7 @@ func (c *tmHeaderValidate) Run(input []byte) (result []byte, err error) {
}()

if uint64(len(input)) <= precompileContractInputMetaDataLength {
return nil, fmt.Errorf("invalid input")
return nil, errors.New("invalid input")
}

payloadLength := binary.BigEndian.Uint64(input[precompileContractInputMetaDataLength-uint64TypeLength : precompileContractInputMetaDataLength])
Expand Down Expand Up @@ -132,7 +133,7 @@ func (c *tmHeaderValidateNano) RequiredGas(input []byte) uint64 {
}

func (c *tmHeaderValidateNano) Run(input []byte) (result []byte, err error) {
return nil, fmt.Errorf("suspend")
return nil, errors.New("suspend")
}

type iavlMerkleProofValidateNano struct{}
Expand All @@ -142,7 +143,7 @@ func (c *iavlMerkleProofValidateNano) RequiredGas(_ []byte) uint64 {
}

func (c *iavlMerkleProofValidateNano) Run(_ []byte) (result []byte, err error) {
return nil, fmt.Errorf("suspend")
return nil, errors.New("suspend")
}

// ------------------------------------------------------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -250,7 +251,7 @@ func (c *basicIavlMerkleProofValidate) Run(input []byte) (result []byte, err err

valid := kvmp.Validate()
if !valid {
return nil, fmt.Errorf("invalid merkle proof")
return nil, errors.New("invalid merkle proof")
}

return successfulMerkleResult(), nil
Expand Down Expand Up @@ -418,7 +419,7 @@ const (
// | 33 bytes | 64 bytes | 32 bytes |
func (c *secp256k1SignatureRecover) Run(input []byte) (result []byte, err error) {
if len(input) != int(secp256k1PubKeyLength)+int(secp256k1SignatureLength)+int(secp256k1SignatureMsgHashLength) {
return nil, fmt.Errorf("invalid input")
return nil, errors.New("invalid input")
}

return c.runTMSecp256k1Signature(
Expand All @@ -432,7 +433,7 @@ func (c *secp256k1SignatureRecover) runTMSecp256k1Signature(pubkey, signatureStr
tmPubKey := secp256k1.PubKeySecp256k1(pubkey)
ok := tmPubKey.VerifyBytesWithMsgHash(msgHash, signatureStr)
if !ok {
return nil, fmt.Errorf("invalid signature")
return nil, errors.New("invalid signature")
}
return tmPubKey.Address().Bytes(), nil
}
3 changes: 2 additions & 1 deletion core/vm/lightclient/v1/ics23_proof.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package v1

import (
"errors"
"fmt"

"github.com/bnb-chain/ics23"
Expand Down Expand Up @@ -71,7 +72,7 @@ func (op CommitmentOp) GetKey() []byte {
// in the CommitmentOp and return the CommitmentRoot of the proof.
func (op CommitmentOp) Run(args [][]byte) ([][]byte, error) {
if _, ok := op.Proof.Proof.(*ics23.CommitmentProof_Exist); !ok {
return nil, fmt.Errorf("only exist proof supported")
return nil, errors.New("only exist proof supported")
}

// calculate root from proof
Expand Down
Loading

0 comments on commit 6386172

Please sign in to comment.