diff --git a/XDCxlending/lendingstate/lendingcontract.go b/XDCxlending/lendingstate/lendingcontract.go index fa2df7dc8491..eba5b1a06587 100644 --- a/XDCxlending/lendingstate/lendingcontract.go +++ b/XDCxlending/lendingstate/lendingcontract.go @@ -1,7 +1,7 @@ package lendingstate import ( - "fmt" + "errors" "math/big" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" @@ -273,10 +273,10 @@ func GetAllLendingBooks(statedb *state.StateDB) (mapLendingBook map[common.Hash] baseTokens := GetSupportedBaseToken(statedb) terms := GetSupportedTerms(statedb) if len(baseTokens) == 0 { - return nil, fmt.Errorf("GetAllLendingBooks: empty baseToken list") + return nil, errors.New("GetAllLendingBooks: empty baseToken list") } if len(terms) == 0 { - return nil, fmt.Errorf("GetAllLendingPairs: empty term list") + return nil, errors.New("GetAllLendingPairs: empty term list") } for _, baseToken := range baseTokens { for _, term := range terms { @@ -295,10 +295,10 @@ func GetAllLendingPairs(statedb *state.StateDB) (allPairs []LendingPair, err err baseTokens := GetSupportedBaseToken(statedb) collaterals := GetAllCollateral(statedb) if len(baseTokens) == 0 { - return allPairs, fmt.Errorf("GetAllLendingPairs: empty baseToken list") + return allPairs, errors.New("GetAllLendingPairs: empty baseToken list") } if len(collaterals) == 0 { - return allPairs, fmt.Errorf("GetAllLendingPairs: empty collateral list") + return allPairs, errors.New("GetAllLendingPairs: empty collateral list") } for _, baseToken := range baseTokens { for _, collateral := range collaterals { diff --git a/XDCxlending/lendingstate/lendingitem.go b/XDCxlending/lendingstate/lendingitem.go index 67469b651ce0..dd4553ab8793 100644 --- a/XDCxlending/lendingstate/lendingitem.go +++ b/XDCxlending/lendingstate/lendingitem.go @@ -1,6 +1,7 @@ package lendingstate import ( + "errors" "fmt" "math/big" "strconv" @@ -359,7 +360,7 @@ func (l *LendingItem) VerifyLendingSignature() error { tx.ImportSignature(V, R, S) from, _ := types.LendingSender(types.LendingTxSigner{}, tx) if from != tx.UserAddress() { - return fmt.Errorf("verify lending item: invalid signature") + return errors.New("verify lending item: invalid signature") } return nil } @@ -473,10 +474,10 @@ func VerifyBalance(isXDCXLendingFork bool, statedb *state.StateDB, lendingStateD } return nil default: - return fmt.Errorf("VerifyBalance: unknown lending side") + return errors.New("VerifyBalance: unknown lending side") } default: - return fmt.Errorf("VerifyBalance: unknown lending type") + return errors.New("VerifyBalance: unknown lending type") } return nil } diff --git a/XDCxlending/order_processor.go b/XDCxlending/order_processor.go index 15343de2a6e4..5af2d2771314 100644 --- a/XDCxlending/order_processor.go +++ b/XDCxlending/order_processor.go @@ -2,6 +2,7 @@ package XDCxlending import ( "encoding/json" + "errors" "fmt" "math/big" @@ -264,7 +265,7 @@ func (l *Lending) processOrderList(header *types.Header, coinbase common.Address borrowFee = lendingstate.GetFee(statedb, oldestOrder.Relayer) } if collateralToken.IsZero() { - return nil, nil, nil, fmt.Errorf("empty collateral") + return nil, nil, nil, errors.New("empty collateral") } depositRate, liquidationRate, recallRate := lendingstate.GetCollateralDetail(statedb, collateralToken) if depositRate == nil || depositRate.Sign() <= 0 { @@ -282,10 +283,10 @@ func (l *Lending) processOrderList(header *types.Header, coinbase common.Address return nil, nil, nil, err } if lendTokenXDCPrice == nil || lendTokenXDCPrice.Sign() <= 0 { - return nil, nil, nil, fmt.Errorf("invalid lendToken price") + return nil, nil, nil, errors.New("invalid lendToken price") } if collateralPrice == nil || collateralPrice.Sign() <= 0 { - return nil, nil, nil, fmt.Errorf("invalid collateral price") + return nil, nil, nil, errors.New("invalid collateral price") } tradedQuantity, collateralLockedAmount, rejectMaker, settleBalanceResult, err := l.getLendQuantity(lendTokenXDCPrice, collateralPrice, depositRate, borrowFee, coinbase, chain, header, statedb, order, &oldestOrder, maxTradedQuantity) if err != nil && err == lendingstate.ErrQuantityTradeTooSmall && tradedQuantity != nil && tradedQuantity.Sign() >= 0 { diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index e3687968a5bd..0ca97525cd2b 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -79,19 +79,19 @@ func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { // Unpack output in v according to the abi specification func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) { if len(output) == 0 { - return fmt.Errorf("abi: unmarshalling empty output") + return errors.New("abi: unmarshalling empty output") } // since there can't be naming collisions with contracts and events, // we need to decide whether we're calling a method or an event if method, ok := abi.Methods[name]; ok { if len(output)%32 != 0 { - return fmt.Errorf("abi: improperly formatted output") + return errors.New("abi: improperly formatted output") } return method.Outputs.Unpack(v, output) } else if event, ok := abi.Events[name]; ok { return event.Inputs.Unpack(v, output) } - return fmt.Errorf("abi: could not locate named method or event") + return errors.New("abi: could not locate named method or event") } // UnmarshalJSON implements json.Unmarshaler interface diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index 1b5c71701cef..d0e2d1c3930b 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -335,7 +335,7 @@ func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) return errNoEventSignature } if log.Topics[0] != c.abi.Events[event].Id() { - return fmt.Errorf("event signature mismatch") + return errors.New("event signature mismatch") } if len(log.Data) > 0 { if err := c.abi.Unpack(out, event, log.Data); err != nil { diff --git a/accounts/abi/bind/util.go b/accounts/abi/bind/util.go index 7943884f075a..dec604a801fd 100644 --- a/accounts/abi/bind/util.go +++ b/accounts/abi/bind/util.go @@ -18,7 +18,7 @@ package bind import ( "context" - "fmt" + "errors" "time" "github.com/XinFinOrg/XDPoSChain/common" @@ -56,14 +56,14 @@ func WaitMined(ctx context.Context, b DeployBackend, tx *types.Transaction) (*ty // contract address when it is mined. It stops waiting when ctx is canceled. func WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) (common.Address, error) { if tx.To() != nil { - return common.Address{}, fmt.Errorf("tx is not contract creation") + return common.Address{}, errors.New("tx is not contract creation") } receipt, err := WaitMined(ctx, b, tx) if err != nil { return common.Address{}, err } if receipt.ContractAddress == (common.Address{}) { - return common.Address{}, fmt.Errorf("zero address") + return common.Address{}, errors.New("zero address") } // Check that code has indeed been deployed at the address. // This matters on pre-Homestead chains: OOG in the constructor diff --git a/accounts/abi/reflect.go b/accounts/abi/reflect.go index 2e6bf7098f2c..c1d411ac9560 100644 --- a/accounts/abi/reflect.go +++ b/accounts/abi/reflect.go @@ -17,6 +17,7 @@ package abi import ( + "errors" "fmt" "reflect" ) @@ -117,7 +118,7 @@ func requireUniqueStructFieldNames(args Arguments) error { for _, arg := range args { field := capitalise(arg.Name) if field == "" { - return fmt.Errorf("abi: purely underscored output cannot unpack to struct") + return errors.New("abi: purely underscored output cannot unpack to struct") } if exists[field] { return fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", field) diff --git a/accounts/abi/type.go b/accounts/abi/type.go index cec1ce8f5653..355ac3ac77a8 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -17,6 +17,7 @@ package abi import ( + "errors" "fmt" "reflect" "regexp" @@ -61,7 +62,7 @@ var ( func NewType(t string) (typ Type, err error) { // check that array brackets are equal if they exist if strings.Count(t, "[") != strings.Count(t, "]") { - return Type{}, fmt.Errorf("invalid arg type in abi") + return Type{}, errors.New("invalid arg type in abi") } typ.stringKind = t @@ -98,7 +99,7 @@ func NewType(t string) (typ Type, err error) { } typ.Type = reflect.ArrayOf(typ.Size, embeddedType.Type) } else { - return Type{}, fmt.Errorf("invalid formatting of array type") + return Type{}, errors.New("invalid formatting of array type") } return typ, err } diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index 9f0bccf75b13..ff2bacebbcf8 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -18,6 +18,7 @@ package abi import ( "encoding/binary" + "errors" "fmt" "math/big" "reflect" @@ -70,7 +71,7 @@ func readBool(word []byte) (bool, error) { // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes) func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { if t.T != FunctionTy { - return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array") + return [24]byte{}, errors.New("abi: invalid type in call to make function type byte array") } if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 { err = fmt.Errorf("abi: got improperly encoded function type, got %v", word) @@ -83,7 +84,7 @@ func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { // through reflection, creates a fixed array to be read from func readFixedBytes(t Type, word []byte) (interface{}, error) { if t.T != FixedBytesTy { - return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array") + return nil, errors.New("abi: invalid type in call to make fixed byte array") } // convert array := reflect.New(t.Type).Elem() @@ -123,7 +124,7 @@ func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) // declare our array refSlice = reflect.New(t.Type).Elem() } else { - return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage") + return nil, errors.New("abi: invalid type in array/slice unpacking stage") } // Arrays have packed elements, resulting in longer unpack steps. diff --git a/accounts/keystore/account_cache_test.go b/accounts/keystore/account_cache_test.go index e2436f416095..aa1636efc8a8 100644 --- a/accounts/keystore/account_cache_test.go +++ b/accounts/keystore/account_cache_test.go @@ -17,6 +17,7 @@ package keystore import ( + "errors" "fmt" "math/rand" "os" @@ -305,7 +306,7 @@ func waitForAccounts(wantAccounts []accounts.Account, ks *KeyStore) error { select { case <-ks.changes: default: - return fmt.Errorf("wasn't notified of new accounts") + return errors.New("wasn't notified of new accounts") } return nil } diff --git a/accounts/keystore/keystore.go b/accounts/keystore/keystore.go index 45a3be3036d7..80ac1102d3f0 100644 --- a/accounts/keystore/keystore.go +++ b/accounts/keystore/keystore.go @@ -24,7 +24,6 @@ import ( "crypto/ecdsa" crand "crypto/rand" "errors" - "fmt" "math/big" "os" "path/filepath" @@ -455,7 +454,7 @@ func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (ac func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) { key := newKeyFromECDSA(priv) if ks.cache.hasAddress(key.Address) { - return accounts.Account{}, fmt.Errorf("account already exists") + return accounts.Account{}, errors.New("account already exists") } return ks.importKey(key, passphrase) } diff --git a/bmt/bmt_test.go b/bmt/bmt_test.go index 7a479637006f..ac762993c5e1 100644 --- a/bmt/bmt_test.go +++ b/bmt/bmt_test.go @@ -19,6 +19,7 @@ package bmt import ( "bytes" crand "crypto/rand" + "errors" "fmt" "hash" "io" @@ -288,7 +289,7 @@ func TestHasherConcurrency(t *testing.T) { var err error select { case <-time.NewTimer(5 * time.Second).C: - err = fmt.Errorf("timed out") + err = errors.New("timed out") case err = <-errc: } if err != nil { @@ -321,7 +322,7 @@ func testHasherCorrectness(bmt hash.Hash, hasher BaseHasher, d []byte, n, count }() select { case <-timeout.C: - err = fmt.Errorf("BMT hash calculation timed out") + err = errors.New("BMT hash calculation timed out") case err = <-c: } return err diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 161a65a417f6..0e736b95e0b3 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -19,6 +19,7 @@ package utils import ( "compress/gzip" + "errors" "fmt" "io" "os" @@ -130,7 +131,7 @@ func ImportChain(chain *core.BlockChain, fn string) error { for batch := 0; ; batch++ { // Load a batch of RLP blocks. if checkInterrupt() { - return fmt.Errorf("interrupted") + return errors.New("interrupted") } i := 0 for ; i < importBatchSize; i++ { @@ -153,7 +154,7 @@ func ImportChain(chain *core.BlockChain, fn string) error { } // Import the batch. if checkInterrupt() { - return fmt.Errorf("interrupted") + return errors.New("interrupted") } missing := missingBlocks(chain, blocks[:i]) if len(missing) == 0 { diff --git a/common/countdown/countdown_test.go b/common/countdown/countdown_test.go index fb5356dfc94f..6f1b0e10225e 100644 --- a/common/countdown/countdown_test.go +++ b/common/countdown/countdown_test.go @@ -1,7 +1,7 @@ package countdown import ( - "fmt" + "errors" "testing" "time" @@ -76,7 +76,7 @@ func TestCountdownShouldResetEvenIfErrored(t *testing.T) { called := make(chan int) OnTimeoutFn := func(time.Time, interface{}) error { called <- 1 - return fmt.Errorf("ERROR!") + return errors.New("ERROR!") } countdown := NewCountDown(5000 * time.Millisecond) diff --git a/consensus/XDPoS/XDPoS.go b/consensus/XDPoS/XDPoS.go index 6d5477a1ee61..fc7b3418946d 100644 --- a/consensus/XDPoS/XDPoS.go +++ b/consensus/XDPoS/XDPoS.go @@ -17,6 +17,7 @@ package XDPoS import ( + "errors" "fmt" "math/big" @@ -438,7 +439,7 @@ func (x *XDPoS) CalculateMissingRounds(chain consensus.ChainReader, header *type case params.ConsensusEngineVersion2: return x.EngineV2.CalculateMissingRounds(chain, header) default: // Default "v1" - return nil, fmt.Errorf("Not supported in the v1 consensus") + return nil, errors.New("Not supported in the v1 consensus") } } diff --git a/consensus/XDPoS/engines/engine_v1/engine.go b/consensus/XDPoS/engines/engine_v1/engine.go index 7a862370c8e0..6317200fa2e9 100644 --- a/consensus/XDPoS/engines/engine_v1/engine.go +++ b/consensus/XDPoS/engines/engine_v1/engine.go @@ -686,7 +686,7 @@ func (x *XDPoS_v1) GetValidator(creator common.Address, chain consensus.ChainRea if no%epoch == 0 { cpHeader = header } else { - return common.Address{}, fmt.Errorf("couldn't find checkpoint header") + return common.Address{}, errors.New("couldn't find checkpoint header") } } m, err := getM1M2FromCheckpointHeader(cpHeader, header, chain.Config()) diff --git a/consensus/XDPoS/engines/engine_v2/engine.go b/consensus/XDPoS/engines/engine_v2/engine.go index 9cc25d7fab76..c2235f5d32a9 100644 --- a/consensus/XDPoS/engines/engine_v2/engine.go +++ b/consensus/XDPoS/engines/engine_v2/engine.go @@ -661,7 +661,7 @@ func (x *XDPoS_v2) VerifyTimeoutMessage(chain consensus.ChainReader, timeoutMsg } if len(snap.NextEpochCandidates) == 0 { log.Error("[VerifyTimeoutMessage] cannot find NextEpochCandidates from snapshot", "messageGapNumber", timeoutMsg.GapNumber) - return false, fmt.Errorf("Empty master node lists from snapshot") + return false, errors.New("Empty master node lists from snapshot") } verified, signer, err := x.verifyMsgSignature(types.TimeoutSigHash(&types.TimeoutForSign{ @@ -748,7 +748,7 @@ func (x *XDPoS_v2) VerifyBlockInfo(blockChainReader consensus.ChainReader, block // If blockHeader present, then its value shall consistent with what's provided in the blockInfo if blockHeader.Hash() != blockInfo.Hash { log.Warn("[VerifyBlockInfo] BlockHeader and blockInfo mismatch", "BlockInfoHash", blockInfo.Hash.Hex(), "BlockHeaderHash", blockHeader.Hash()) - return fmt.Errorf("[VerifyBlockInfo] Provided blockheader does not match what's in the blockInfo") + return errors.New("[VerifyBlockInfo] Provided blockheader does not match what's in the blockInfo") } } @@ -761,7 +761,7 @@ func (x *XDPoS_v2) VerifyBlockInfo(blockChainReader consensus.ChainReader, block if blockInfo.Number.Cmp(x.config.V2.SwitchBlock) == 0 { if blockInfo.Round != 0 { log.Error("[VerifyBlockInfo] Switch block round is not 0", "BlockInfoHash", blockInfo.Hash.Hex(), "BlockInfoNum", blockInfo.Number, "BlockInfoRound", blockInfo.Round, "blockHeaderNum", blockHeader.Number) - return fmt.Errorf("[VerifyBlockInfo] switch block round have to be 0") + return errors.New("[VerifyBlockInfo] switch block round have to be 0") } return nil } @@ -789,7 +789,7 @@ func (x *XDPoS_v2) verifyQC(blockChainReader consensus.ChainReader, quorumCert * epochInfo, err := x.getEpochSwitchInfo(blockChainReader, parentHeader, quorumCert.ProposedBlockInfo.Hash) if err != nil { log.Error("[verifyQC] Error when getting epoch switch Info to verify QC", "Error", err) - return fmt.Errorf("Fail to verify QC due to failure in getting epoch switch info") + return errors.New("Fail to verify QC due to failure in getting epoch switch info") } signatures, duplicates := UniqueSignatures(quorumCert.Signatures) @@ -821,12 +821,12 @@ func (x *XDPoS_v2) verifyQC(blockChainReader consensus.ChainReader, quorumCert * }), sig, epochInfo.Masternodes) if err != nil { log.Error("[verifyQC] Error while verfying QC message signatures", "Error", err) - haveError = fmt.Errorf("Error while verfying QC message signatures") + haveError = errors.New("Error while verfying QC message signatures") return } if !verified { log.Warn("[verifyQC] Signature not verified doing QC verification", "QC", quorumCert) - haveError = fmt.Errorf("Fail to verify QC due to signature mis-match") + haveError = errors.New("Fail to verify QC due to signature mis-match") return } }(signature) diff --git a/consensus/XDPoS/engines/engine_v2/forensics.go b/consensus/XDPoS/engines/engine_v2/forensics.go index 1c4542ab0e81..45f88097d6b3 100644 --- a/consensus/XDPoS/engines/engine_v2/forensics.go +++ b/consensus/XDPoS/engines/engine_v2/forensics.go @@ -2,6 +2,7 @@ package engine_v2 import ( "encoding/json" + "errors" "fmt" "math/big" "reflect" @@ -49,7 +50,7 @@ func (f *Forensics) SetCommittedQCs(headers []types.Header, incomingQC types.Quo // highestCommitQCs is an array, assign the parentBlockQc and its child as well as its grandchild QC into this array for forensics purposes. if len(headers) != NUM_OF_FORENSICS_QC-1 { log.Error("[SetCommittedQcs] Received input length not equal to 2", len(headers)) - return fmt.Errorf("received headers length not equal to 2 ") + return errors.New("received headers length not equal to 2 ") } var committedQCs []types.QuorumCert @@ -64,11 +65,11 @@ func (f *Forensics) SetCommittedQCs(headers []types.Header, incomingQC types.Quo if i != 0 { if decodedExtraField.QuorumCert.ProposedBlockInfo.Hash != headers[i-1].Hash() { log.Error("[SetCommittedQCs] Headers shall be on the same chain and in the right order", "parentHash", h.ParentHash.Hex(), "headers[i-1].Hash()", headers[i-1].Hash().Hex()) - return fmt.Errorf("headers shall be on the same chain and in the right order") + return errors.New("headers shall be on the same chain and in the right order") } else if i == len(headers)-1 { // The last header shall be pointed by the incoming QC if incomingQC.ProposedBlockInfo.Hash != h.Hash() { log.Error("[SetCommittedQCs] incomingQc is not pointing at the last header received", "hash", h.Hash().Hex(), "incomingQC.ProposedBlockInfo.Hash", incomingQC.ProposedBlockInfo.Hash.Hex()) - return fmt.Errorf("incomingQc is not pointing at the last header received") + return errors.New("incomingQc is not pointing at the last header received") } } } @@ -91,7 +92,7 @@ func (f *Forensics) ProcessForensics(chain consensus.ChainReader, engine *XDPoS_ highestCommittedQCs := f.HighestCommittedQCs if len(highestCommittedQCs) != NUM_OF_FORENSICS_QC { log.Error("[ProcessForensics] HighestCommittedQCs value not set", "incomingQcProposedBlockHash", incomingQC.ProposedBlockInfo.Hash, "incomingQcProposedBlockNumber", incomingQC.ProposedBlockInfo.Number.Uint64(), "incomingQcProposedBlockRound", incomingQC.ProposedBlockInfo.Round) - return fmt.Errorf("HighestCommittedQCs value not set") + return errors.New("HighestCommittedQCs value not set") } // Find the QC1 and QC2. We only care 2 parents in front of the incomingQC. The returned value contains QC1, QC2 and QC3(the incomingQC) incomingQuorunCerts, err := f.findAncestorQCs(chain, incomingQC, 2) @@ -163,7 +164,7 @@ func (f *Forensics) SendForensicProof(chain consensus.ChainReader, engine *XDPoS if ancestorBlock == nil { log.Error("[SendForensicProof] Unable to find the ancestor block by its hash", "Hash", ancestorHash) - return fmt.Errorf("Can't find ancestor block via hash") + return errors.New("Can't find ancestor block via hash") } content, err := json.Marshal(&types.ForensicsContent{ @@ -209,7 +210,7 @@ func (f *Forensics) findAncestorQCs(chain consensus.ChainReader, currentQc types parentHeader := chain.GetHeaderByHash(parentHash) if parentHeader == nil { log.Error("[findAncestorQCs] Forensics findAncestorQCs unable to find its parent block header", "BlockNum", parentHeader.Number.Int64(), "ParentHash", parentHash.Hex()) - return nil, fmt.Errorf("unable to find parent block header in forensics") + return nil, errors.New("unable to find parent block header in forensics") } var decodedExtraField types.ExtraFields_v2 err := utils.DecodeBytesExtraFields(parentHeader.Extra, &decodedExtraField) @@ -318,7 +319,7 @@ func (f *Forensics) findAncestorQcThroughRound(chain consensus.ChainReader, high } ancestorQC = *decodedExtraField.QuorumCert } - return ancestorQC, lowerRoundQCs, higherRoundQCs, fmt.Errorf("[findAncestorQcThroughRound] Could not find ancestor QC") + return ancestorQC, lowerRoundQCs, higherRoundQCs, errors.New("[findAncestorQcThroughRound] Could not find ancestor QC") } func (f *Forensics) FindAncestorBlockHash(chain consensus.ChainReader, firstBlockInfo *types.BlockInfo, secondBlockInfo *types.BlockInfo) (common.Hash, []string, []string, error) { @@ -398,7 +399,7 @@ func (f *Forensics) ProcessVoteEquivocation(chain consensus.ChainReader, engine highestCommittedQCs := f.HighestCommittedQCs if len(highestCommittedQCs) != NUM_OF_FORENSICS_QC { log.Error("[ProcessVoteEquivocation] HighestCommittedQCs value not set", "incomingVoteProposedBlockHash", incomingVote.ProposedBlockInfo.Hash, "incomingVoteProposedBlockNumber", incomingVote.ProposedBlockInfo.Number.Uint64(), "incomingVoteProposedBlockRound", incomingVote.ProposedBlockInfo.Round) - return fmt.Errorf("HighestCommittedQCs value not set") + return errors.New("HighestCommittedQCs value not set") } if incomingVote.ProposedBlockInfo.Round < highestCommittedQCs[NUM_OF_FORENSICS_QC-1].ProposedBlockInfo.Round { log.Debug("Received a too old vote in forensics", "vote", incomingVote) diff --git a/consensus/XDPoS/engines/engine_v2/timeout.go b/consensus/XDPoS/engines/engine_v2/timeout.go index 39d8100b2402..2f077b2a0018 100644 --- a/consensus/XDPoS/engines/engine_v2/timeout.go +++ b/consensus/XDPoS/engines/engine_v2/timeout.go @@ -1,6 +1,7 @@ package engine_v2 import ( + "errors" "fmt" "strconv" "strings" @@ -99,7 +100,7 @@ func (x *XDPoS_v2) verifyTC(chain consensus.ChainReader, timeoutCert *types.Time } if snap == nil || len(snap.NextEpochCandidates) == 0 { log.Error("[verifyTC] Something wrong with the snapshot from gapNumber", "messageGapNumber", timeoutCert.GapNumber, "snapshot", snap) - return fmt.Errorf("empty master node lists from snapshot") + return errors.New("empty master node lists from snapshot") } signatures, duplicates := UniqueSignatures(timeoutCert.Signatures) @@ -145,7 +146,7 @@ func (x *XDPoS_v2) verifyTC(chain consensus.ChainReader, timeoutCert *types.Time haveError = fmt.Errorf("error while verifying TC message signatures, %s", err) } else { log.Warn("[verifyTC] Signature not verified doing TC verification", "timeoutCert.Round", timeoutCert.Round, "timeoutCert.GapNumber", timeoutCert.GapNumber, "Signatures len", len(signatures)) - haveError = fmt.Errorf("fail to verify TC due to signature mis-match") + haveError = errors.New("fail to verify TC due to signature mis-match") } } mutex.Unlock() // Unlock after modifying haveError diff --git a/consensus/XDPoS/engines/engine_v2/utils.go b/consensus/XDPoS/engines/engine_v2/utils.go index e8006951ea14..20198816280b 100644 --- a/consensus/XDPoS/engines/engine_v2/utils.go +++ b/consensus/XDPoS/engines/engine_v2/utils.go @@ -1,6 +1,7 @@ package engine_v2 import ( + "errors" "fmt" "github.com/XinFinOrg/XDPoSChain/accounts" @@ -105,7 +106,7 @@ func (x *XDPoS_v2) signSignature(signingHash common.Hash) (types.Signature, erro func (x *XDPoS_v2) verifyMsgSignature(signedHashToBeVerified common.Hash, signature types.Signature, masternodes []common.Address) (bool, common.Address, error) { var signerAddress common.Address if len(masternodes) == 0 { - return false, signerAddress, fmt.Errorf("Empty masternode list detected when verifying message signatures") + return false, signerAddress, errors.New("Empty masternode list detected when verifying message signatures") } // Recover the public key and the Ethereum address pubkey, err := crypto.Ecrecover(signedHashToBeVerified.Bytes(), signature) diff --git a/consensus/XDPoS/engines/engine_v2/vote.go b/consensus/XDPoS/engines/engine_v2/vote.go index 1ec2d4b24e42..de79585297af 100644 --- a/consensus/XDPoS/engines/engine_v2/vote.go +++ b/consensus/XDPoS/engines/engine_v2/vote.go @@ -1,6 +1,7 @@ package engine_v2 import ( + "errors" "fmt" "math/big" "strconv" @@ -78,7 +79,7 @@ func (x *XDPoS_v2) voteHandler(chain consensus.ChainReader, voteMsg *types.Vote) epochInfo, err := x.getEpochSwitchInfo(chain, chain.CurrentHeader(), chain.CurrentHeader().Hash()) if err != nil { log.Error("[voteHandler] Error when getting epoch switch Info", "error", err) - return fmt.Errorf("Fail on voteHandler due to failure in getting epoch switch info") + return errors.New("Fail on voteHandler due to failure in getting epoch switch info") } certThreshold := x.config.V2.Config(uint64(voteMsg.ProposedBlockInfo.Round)).CertThreshold @@ -177,7 +178,7 @@ func (x *XDPoS_v2) onVotePoolThresholdReached(chain consensus.ChainReader, poole epochInfo, err := x.getEpochSwitchInfo(chain, chain.CurrentHeader(), chain.CurrentHeader().Hash()) if err != nil { log.Error("[voteHandler] Error when getting epoch switch Info", "error", err) - return fmt.Errorf("Fail on voteHandler due to failure in getting epoch switch info") + return errors.New("Fail on voteHandler due to failure in getting epoch switch info") } // Skip and wait for the next vote to process again if valid votes is less than what we required diff --git a/consensus/XDPoS/utils/utils.go b/consensus/XDPoS/utils/utils.go index 1b4e816dd1f8..62b394c836d3 100644 --- a/consensus/XDPoS/utils/utils.go +++ b/consensus/XDPoS/utils/utils.go @@ -2,6 +2,7 @@ package utils import ( "bytes" + "errors" "fmt" "reflect" "sort" @@ -79,7 +80,7 @@ func CompareSignersLists(list1 []common.Address, list2 []common.Address) bool { // Decode extra fields for consensus version >= 2 (XDPoS 2.0 and future versions) func DecodeBytesExtraFields(b []byte, val interface{}) error { if len(b) == 0 { - return fmt.Errorf("extra field is 0 length") + return errors.New("extra field is 0 length") } switch b[0] { case 2: diff --git a/consensus/tests/engine_v1_tests/helper.go b/consensus/tests/engine_v1_tests/helper.go index fb9bb79d8911..52baa648e00b 100644 --- a/consensus/tests/engine_v1_tests/helper.go +++ b/consensus/tests/engine_v1_tests/helper.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/hex" + "errors" "fmt" "math/big" "math/rand" @@ -178,7 +179,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err amountInt := new(big.Int) amount, ok := amountInt.SetString("60000", 10) if !ok { - return nil, fmt.Errorf("big int init failed") + return nil, errors.New("big int init failed") } to := common.MasternodeVotingSMCBinary tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) @@ -321,7 +322,7 @@ func CreateBlock(blockchain *BlockChain, chainConfig *params.ChainConfig, starti // Sign all the things for v1 block use v1 sigHash function sighash, err := signFn(accounts.Account{Address: signer}, blockchain.Engine().(*XDPoS.XDPoS).SigHash(header).Bytes()) if err != nil { - panic(fmt.Errorf("Error when sign last v1 block hash during test block creation")) + panic(errors.New("Error when sign last v1 block hash during test block creation")) } copy(header.Extra[len(header.Extra)-utils.ExtraSeal:], sighash) } diff --git a/consensus/tests/engine_v2_tests/helper.go b/consensus/tests/engine_v2_tests/helper.go index 041aaf7831cd..454f482d7172 100644 --- a/consensus/tests/engine_v2_tests/helper.go +++ b/consensus/tests/engine_v2_tests/helper.go @@ -5,6 +5,7 @@ import ( "context" "crypto/ecdsa" "encoding/hex" + "errors" "fmt" "math/big" "math/rand" @@ -103,7 +104,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err amountInt := new(big.Int) amount, ok := amountInt.SetString("60000", 10) if !ok { - return nil, fmt.Errorf("big int init failed") + return nil, errors.New("big int init failed") } to := common.MasternodeVotingSMCBinary tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) @@ -633,7 +634,7 @@ func CreateBlock(blockchain *BlockChain, chainConfig *params.ChainConfig, starti // Sign all the things for v1 block use v1 sigHash function sighash, err := signFn(accounts.Account{Address: signer}, blockchain.Engine().(*XDPoS.XDPoS).SigHash(header).Bytes()) if err != nil { - panic(fmt.Errorf("Error when sign last v1 block hash during test block creation")) + panic(errors.New("Error when sign last v1 block hash during test block creation")) } copy(header.Extra[len(header.Extra)-utils.ExtraSeal:], sighash) } @@ -737,7 +738,7 @@ func findSignerAndSignFn(bc *BlockChain, header *types.Header, signer common.Add var decodedExtraField types.ExtraFields_v2 err := utils.DecodeBytesExtraFields(header.Extra, &decodedExtraField) if err != nil { - panic(fmt.Errorf("fail to seal header for v2 block")) + panic(errors.New("fail to seal header for v2 block")) } round := decodedExtraField.Round masterNodes := getMasternodesList(signer) @@ -757,7 +758,7 @@ func findSignerAndSignFn(bc *BlockChain, header *types.Header, signer common.Add } addressedSignFn = signFn if err != nil { - panic(fmt.Errorf("Error trying to use one of the pre-defined private key to sign")) + panic(errors.New("Error trying to use one of the pre-defined private key to sign")) } } diff --git a/console/bridge.go b/console/bridge.go index 80606a687862..80f809533678 100644 --- a/console/bridge.go +++ b/console/bridge.go @@ -18,6 +18,7 @@ package console import ( "encoding/json" + "errors" "fmt" "io" "reflect" @@ -75,18 +76,18 @@ func (b *bridge) NewAccount(call jsre.Call) (goja.Value, error) { return nil, err } if password != confirm { - return nil, fmt.Errorf("passwords don't match!") + return nil, errors.New("passwords don't match!") } // A single string password was specified, use that case len(call.Arguments) == 1 && call.Argument(0).ToString() != nil: password = call.Argument(0).ToString().String() default: - return nil, fmt.Errorf("expected 0 or 1 string argument") + return nil, errors.New("expected 0 or 1 string argument") } // Password acquired, execute the call and return newAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("newAccount")) if !callable { - return nil, fmt.Errorf("jeth.newAccount is not callable") + return nil, errors.New("jeth.newAccount is not callable") } ret, err := newAccount(goja.Null(), call.VM.ToValue(password)) if err != nil { @@ -100,7 +101,7 @@ func (b *bridge) NewAccount(call jsre.Call) (goja.Value, error) { func (b *bridge) OpenWallet(call jsre.Call) (goja.Value, error) { // Make sure we have a wallet specified to open if call.Argument(0).ToObject(call.VM).ClassName() != "String" { - return nil, fmt.Errorf("first argument must be the wallet URL to open") + return nil, errors.New("first argument must be the wallet URL to open") } wallet := call.Argument(0) @@ -113,7 +114,7 @@ func (b *bridge) OpenWallet(call jsre.Call) (goja.Value, error) { // Open the wallet and return if successful in itself openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet")) if !callable { - return nil, fmt.Errorf("jeth.openWallet is not callable") + return nil, errors.New("jeth.openWallet is not callable") } val, err := openWallet(goja.Null(), wallet, passwd) if err == nil { @@ -147,7 +148,7 @@ func (b *bridge) readPassphraseAndReopenWallet(call jsre.Call) (goja.Value, erro } openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet")) if !callable { - return nil, fmt.Errorf("jeth.openWallet is not callable") + return nil, errors.New("jeth.openWallet is not callable") } return openWallet(goja.Null(), wallet, call.VM.ToValue(input)) } @@ -168,7 +169,7 @@ func (b *bridge) readPinAndReopenWallet(call jsre.Call) (goja.Value, error) { } openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet")) if !callable { - return nil, fmt.Errorf("jeth.openWallet is not callable") + return nil, errors.New("jeth.openWallet is not callable") } return openWallet(goja.Null(), wallet, call.VM.ToValue(input)) } @@ -180,7 +181,7 @@ func (b *bridge) readPinAndReopenWallet(call jsre.Call) (goja.Value, error) { func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) { // Make sure we have an account specified to unlock. if call.Argument(0).ExportType().Kind() != reflect.String { - return nil, fmt.Errorf("first argument must be the account to unlock") + return nil, errors.New("first argument must be the account to unlock") } account := call.Argument(0) @@ -195,7 +196,7 @@ func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) { passwd = call.VM.ToValue(input) } else { if call.Argument(1).ExportType().Kind() != reflect.String { - return nil, fmt.Errorf("password must be a string") + return nil, errors.New("password must be a string") } passwd = call.Argument(1) } @@ -204,7 +205,7 @@ func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) { duration := goja.Null() if !goja.IsUndefined(call.Argument(2)) && !goja.IsNull(call.Argument(2)) { if !isNumber(call.Argument(2)) { - return nil, fmt.Errorf("unlock duration must be a number") + return nil, errors.New("unlock duration must be a number") } duration = call.Argument(2) } @@ -212,7 +213,7 @@ func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) { // Send the request to the backend and return. unlockAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount")) if !callable { - return nil, fmt.Errorf("jeth.unlockAccount is not callable") + return nil, errors.New("jeth.unlockAccount is not callable") } return unlockAccount(goja.Null(), account, passwd, duration) } @@ -228,10 +229,10 @@ func (b *bridge) Sign(call jsre.Call) (goja.Value, error) { ) if message.ExportType().Kind() != reflect.String { - return nil, fmt.Errorf("first argument must be the message to sign") + return nil, errors.New("first argument must be the message to sign") } if account.ExportType().Kind() != reflect.String { - return nil, fmt.Errorf("second argument must be the account to sign with") + return nil, errors.New("second argument must be the account to sign with") } // if the password is not given or null ask the user and ensure password is a string @@ -243,13 +244,13 @@ func (b *bridge) Sign(call jsre.Call) (goja.Value, error) { } passwd = call.VM.ToValue(input) } else if passwd.ExportType().Kind() != reflect.String { - return nil, fmt.Errorf("third argument must be the password to unlock the account") + return nil, errors.New("third argument must be the password to unlock the account") } // Send the request to the backend and return sign, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount")) if !callable { - return nil, fmt.Errorf("jeth.unlockAccount is not callable") + return nil, errors.New("jeth.unlockAccount is not callable") } return sign(goja.Null(), message, account, passwd) } @@ -257,7 +258,7 @@ func (b *bridge) Sign(call jsre.Call) (goja.Value, error) { // Sleep will block the console for the specified number of seconds. func (b *bridge) Sleep(call jsre.Call) (goja.Value, error) { if !isNumber(call.Argument(0)) { - return nil, fmt.Errorf("usage: sleep()") + return nil, errors.New("usage: sleep()") } sleep := call.Argument(0).ToFloat() time.Sleep(time.Duration(sleep * float64(time.Second))) @@ -274,17 +275,17 @@ func (b *bridge) SleepBlocks(call jsre.Call) (goja.Value, error) { ) nArgs := len(call.Arguments) if nArgs == 0 { - return nil, fmt.Errorf("usage: sleepBlocks([, max sleep in seconds])") + return nil, errors.New("usage: sleepBlocks([, max sleep in seconds])") } if nArgs >= 1 { if !isNumber(call.Argument(0)) { - return nil, fmt.Errorf("expected number as first argument") + return nil, errors.New("expected number as first argument") } blocks = call.Argument(0).ToInteger() } if nArgs >= 2 { if isNumber(call.Argument(1)) { - return nil, fmt.Errorf("expected number as second argument") + return nil, errors.New("expected number as second argument") } sleep = call.Argument(1).ToInteger() } @@ -361,7 +362,7 @@ func (b *bridge) Send(call jsre.Call) (goja.Value, error) { JSON := call.VM.Get("JSON").ToObject(call.VM) parse, callable := goja.AssertFunction(JSON.Get("parse")) if !callable { - return nil, fmt.Errorf("JSON.parse is not a function") + return nil, errors.New("JSON.parse is not a function") } resultVal, err := parse(goja.Null(), call.VM.ToValue(string(result))) if err != nil { diff --git a/contracts/chequebook/cheque.go b/contracts/chequebook/cheque.go index 8917d6ab5a82..b8f31078deab 100644 --- a/contracts/chequebook/cheque.go +++ b/contracts/chequebook/cheque.go @@ -29,6 +29,7 @@ import ( "context" "crypto/ecdsa" "encoding/json" + "errors" "fmt" "math/big" "os" @@ -446,7 +447,7 @@ type Inbox struct { // from blockchain when first cheque is received. func NewInbox(prvKey *ecdsa.PrivateKey, contractAddr, beneficiary common.Address, signer *ecdsa.PublicKey, abigen bind.ContractBackend) (self *Inbox, err error) { if signer == nil { - return nil, fmt.Errorf("signer is null") + return nil, errors.New("signer is null") } chbook, err := contract.NewChequebook(contractAddr, abigen) if err != nil { @@ -583,7 +584,7 @@ func (self *Inbox) Receive(promise swap.Promise) (*big.Int, error) { func (self *Cheque) Verify(signerKey *ecdsa.PublicKey, contract, beneficiary common.Address, sum *big.Int) (*big.Int, error) { log.Trace("Verifying chequebook cheque", "cheque", self, "sum", sum) if sum == nil { - return nil, fmt.Errorf("invalid amount") + return nil, errors.New("invalid amount") } if self.Beneficiary != beneficiary { diff --git a/core/block_validator.go b/core/block_validator.go index a4144aa495e9..e713342d9c62 100644 --- a/core/block_validator.go +++ b/core/block_validator.go @@ -17,6 +17,7 @@ package core import ( + "errors" "fmt" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" @@ -113,7 +114,7 @@ func (v *BlockValidator) ValidateTradingOrder(statedb *state.StateDB, XDCxStated } XDCXService := XDPoSEngine.GetXDCXService() if XDCXService == nil { - return fmt.Errorf("XDCx not found") + return errors.New("XDCx not found") } log.Debug("verify matching transaction found a TxMatches Batch", "numTxMatches", len(txMatchBatch.Data)) tradingResult := map[common.Hash]tradingstate.MatchingResult{} @@ -149,11 +150,11 @@ func (v *BlockValidator) ValidateLendingOrder(statedb *state.StateDB, lendingSta } XDCXService := XDPoSEngine.GetXDCXService() if XDCXService == nil { - return fmt.Errorf("XDCx not found") + return errors.New("XDCx not found") } lendingService := XDPoSEngine.GetLendingService() if lendingService == nil { - return fmt.Errorf("lendingService not found") + return errors.New("lendingService not found") } log.Debug("verify lendingItem ", "numItems", len(batch.Data)) lendingResult := map[common.Hash]lendingstate.MatchingResult{} diff --git a/core/blockchain.go b/core/blockchain.go index ce31a6bc2780..927e4628df1a 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -2197,10 +2197,10 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error { } } if oldBlock == nil { - return fmt.Errorf("Invalid old chain") + return errors.New("Invalid old chain") } if newBlock == nil { - return fmt.Errorf("Invalid new chain") + return errors.New("Invalid new chain") } for { @@ -2216,10 +2216,10 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error { oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) if oldBlock == nil { - return fmt.Errorf("Invalid old chain") + return errors.New("Invalid old chain") } if newBlock == nil { - return fmt.Errorf("Invalid new chain") + return errors.New("Invalid new chain") } } // Ensure XDPoS engine committed block will be not reverted diff --git a/core/chain_indexer.go b/core/chain_indexer.go index 7be107be85b4..dd6466ab3770 100644 --- a/core/chain_indexer.go +++ b/core/chain_indexer.go @@ -18,6 +18,7 @@ package core import ( "encoding/binary" + "errors" "fmt" "sync" "sync/atomic" @@ -357,7 +358,7 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com if header == nil { return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4]) } else if header.ParentHash != lastHead { - return common.Hash{}, fmt.Errorf("chain reorged during section processing") + return common.Hash{}, errors.New("chain reorged during section processing") } c.backend.Process(header) lastHead = header.Hash() diff --git a/core/genesis.go b/core/genesis.go index 79a73f34dbac..205074b7141f 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -141,10 +141,10 @@ func (e *GenesisMismatchError) Error() string { // SetupGenesisBlock writes or updates the genesis block in db. // The block that will be used is: // -// genesis == nil genesis != nil -// +------------------------------------------ -// db has no genesis | main-net default | genesis -// db has genesis | from DB | genesis (if compatible) +// genesis == nil genesis != nil +// +------------------------------------------ +// db has no genesis | main-net default | genesis +// db has genesis | from DB | genesis (if compatible) // // The stored chain configuration will be updated if it is compatible (i.e. does not // specify a fork block below the local head block). In case of a conflict, the @@ -200,7 +200,7 @@ func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig // are returned to the caller unless we're already at block zero. height := GetBlockNumber(db, GetHeadHeaderHash(db)) if height == missingNumber { - return newcfg, stored, fmt.Errorf("missing block number for head header hash") + return newcfg, stored, errors.New("missing block number for head header hash") } compatErr := storedcfg.CheckCompatible(newcfg, height) if compatErr != nil && height != 0 && compatErr.RewindTo != 0 { @@ -275,7 +275,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) { block := g.ToBlock(db) if block.Number().Sign() != 0 { - return nil, fmt.Errorf("can't commit genesis block with number > 0") + return nil, errors.New("can't commit genesis block with number > 0") } if err := WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty); err != nil { return nil, err diff --git a/core/lending_pool.go b/core/lending_pool.go index d4f570f66e35..89aac0665f36 100644 --- a/core/lending_pool.go +++ b/core/lending_pool.go @@ -519,7 +519,7 @@ func (pool *LendingPool) validateBalance(cloneStateDb *state.StateDB, cloneLendi XDCXServ := XDPoSEngine.GetXDCXService() lendingServ := XDPoSEngine.GetLendingService() if XDCXServ == nil { - return fmt.Errorf("XDCx not found in order validation") + return errors.New("XDCx not found in order validation") } lendingTokenDecimal, err := XDCXServ.GetTokenDecimal(pool.chain, cloneStateDb, tx.LendingToken()) if err != nil { diff --git a/core/order_pool.go b/core/order_pool.go index c8708149b89c..dfade0ecd448 100644 --- a/core/order_pool.go +++ b/core/order_pool.go @@ -468,7 +468,7 @@ func (pool *OrderPool) validateOrder(tx *types.OrderTransaction) error { } XDCXServ := XDPoSEngine.GetXDCXService() if XDCXServ == nil { - return fmt.Errorf("XDCx not found in order validation") + return errors.New("XDCx not found in order validation") } baseDecimal, err := XDCXServ.GetTokenDecimal(pool.chain, cloneStateDb, tx.BaseToken()) if err != nil { diff --git a/core/types/consensus_v2_test.go b/core/types/consensus_v2_test.go index 55687f150b5b..890dcba628d4 100644 --- a/core/types/consensus_v2_test.go +++ b/core/types/consensus_v2_test.go @@ -1,6 +1,7 @@ package types import ( + "errors" "fmt" "math/big" "reflect" @@ -15,11 +16,11 @@ import ( // Decode extra fields for consensus version >= 2 (XDPoS 2.0 and future versions) func DecodeBytesExtraFields(b []byte, val interface{}) error { if len(b) == 0 { - return fmt.Errorf("extra field is 0 length") + return errors.New("extra field is 0 length") } switch b[0] { case 1: - return fmt.Errorf("consensus version 1 is not applicable for decoding extra fields") + return errors.New("consensus version 1 is not applicable for decoding extra fields") case 2: return rlp.DecodeBytes(b[1:], val) default: diff --git a/core/types/log_test.go b/core/types/log_test.go index b6ab7810b766..fbd26f72ff83 100644 --- a/core/types/log_test.go +++ b/core/types/log_test.go @@ -18,7 +18,7 @@ package types import ( "encoding/json" - "fmt" + "errors" "reflect" "testing" @@ -97,7 +97,7 @@ var unmarshalLogTests = map[string]struct { }, "missing data": { input: `{"address":"0xecf8f87f810ecf450940c9f60066b4a7a501d6a7","blockHash":"0x656c34545f90a730a19008c0e7a7cd4fb3895064b48d6d69761bd5abad681056","blockNumber":"0x1ecfa4","logIndex":"0x2","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef","0x00000000000000000000000080b2c9d7cbbf30a1b0fc8983c647d754c6525615","0x000000000000000000000000f9dff387dcb5cc4cca5b91adb07a95f54e9f1bb6"],"transactionHash":"0x3b198bfd5d2907285af009e9ae84a0ecd63677110d89d7e030251acb87f6487e","transactionIndex":"0x3"}`, - wantError: fmt.Errorf("missing required field 'data' for Log"), + wantError: errors.New("missing required field 'data' for Log"), }, } diff --git a/core/types/transaction_test.go b/core/types/transaction_test.go index 500dec7227f9..b5b84be08ce9 100644 --- a/core/types/transaction_test.go +++ b/core/types/transaction_test.go @@ -540,7 +540,7 @@ func assertEqual(orig *Transaction, cpy *Transaction) error { } if orig.AccessList() != nil { if !reflect.DeepEqual(orig.AccessList(), cpy.AccessList()) { - return fmt.Errorf("access list wrong!") + return errors.New("access list wrong!") } } return nil diff --git a/crypto/crypto.go b/crypto/crypto.go index 2872bb098bfe..f8387cb73317 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -142,11 +142,11 @@ func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) { // The priv.D must < N if priv.D.Cmp(secp256k1N) >= 0 { - return nil, fmt.Errorf("invalid private key, >=N") + return nil, errors.New("invalid private key, >=N") } // The priv.D must not be zero or negative. if priv.D.Sign() <= 0 { - return nil, fmt.Errorf("invalid private key, zero or negative") + return nil, errors.New("invalid private key, zero or negative") } priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d) @@ -205,7 +205,7 @@ func LoadECDSA(file string) (*ecdsa.PrivateKey, error) { if err != nil { return nil, err } else if n != len(buf) { - return nil, fmt.Errorf("key file too short, want 64 hex characters") + return nil, errors.New("key file too short, want 64 hex characters") } if err := checkKeyFileEnd(r); err != nil { return nil, err diff --git a/crypto/ecies/ecies.go b/crypto/ecies/ecies.go index 1474181482b6..bb1c8d2ff4ac 100644 --- a/crypto/ecies/ecies.go +++ b/crypto/ecies/ecies.go @@ -35,6 +35,7 @@ import ( "crypto/elliptic" "crypto/hmac" "crypto/subtle" + "errors" "fmt" "hash" "io" @@ -42,12 +43,12 @@ import ( ) var ( - ErrImport = fmt.Errorf("ecies: failed to import key") - ErrInvalidCurve = fmt.Errorf("ecies: invalid elliptic curve") - ErrInvalidParams = fmt.Errorf("ecies: invalid ECIES parameters") - ErrInvalidPublicKey = fmt.Errorf("ecies: invalid public key") - ErrSharedKeyIsPointAtInfinity = fmt.Errorf("ecies: shared key is point at infinity") - ErrSharedKeyTooBig = fmt.Errorf("ecies: shared key params are too big") + ErrImport = errors.New("ecies: failed to import key") + ErrInvalidCurve = errors.New("ecies: invalid elliptic curve") + ErrInvalidParams = errors.New("ecies: invalid ECIES parameters") + ErrInvalidPublicKey = errors.New("ecies: invalid public key") + ErrSharedKeyIsPointAtInfinity = errors.New("ecies: shared key is point at infinity") + ErrSharedKeyTooBig = errors.New("ecies: shared key params are too big") ) // PublicKey is a representation of an elliptic curve public key. @@ -138,9 +139,9 @@ func (prv *PrivateKey) GenerateShared(pub *PublicKey, skLen, macLen int) (sk []b } var ( - ErrKeyDataTooLong = fmt.Errorf("ecies: can't supply requested key data") - ErrSharedTooLong = fmt.Errorf("ecies: shared secret is too long") - ErrInvalidMessage = fmt.Errorf("ecies: invalid message") + ErrKeyDataTooLong = errors.New("ecies: can't supply requested key data") + ErrSharedTooLong = errors.New("ecies: shared secret is too long") + ErrInvalidMessage = errors.New("ecies: invalid message") ) var ( diff --git a/crypto/ecies/ecies_test.go b/crypto/ecies/ecies_test.go index 15f5b392e568..0d3fb3bbaccc 100644 --- a/crypto/ecies/ecies_test.go +++ b/crypto/ecies/ecies_test.go @@ -35,6 +35,7 @@ import ( "crypto/rand" "crypto/sha256" "encoding/hex" + "errors" "fmt" "math/big" "testing" @@ -64,7 +65,7 @@ func TestKDF(t *testing.T) { } } -var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match") +var ErrBadSharedKeys = errors.New("ecies: shared keys don't match") // cmpParams compares a set of ECIES parameters. We assume, as per the // docs, that AES is the only supported symmetric encryption algorithm. diff --git a/crypto/ecies/params.go b/crypto/ecies/params.go index 969cc4a3bdba..bd5969f1a91d 100644 --- a/crypto/ecies/params.go +++ b/crypto/ecies/params.go @@ -39,7 +39,7 @@ import ( "crypto/elliptic" "crypto/sha256" "crypto/sha512" - "fmt" + "errors" "hash" ethcrypto "github.com/XinFinOrg/XDPoSChain/crypto" @@ -47,8 +47,8 @@ import ( var ( DefaultCurve = ethcrypto.S256() - ErrUnsupportedECDHAlgorithm = fmt.Errorf("ecies: unsupported ECDH algorithm") - ErrUnsupportedECIESParameters = fmt.Errorf("ecies: unsupported ECIES parameters") + ErrUnsupportedECDHAlgorithm = errors.New("ecies: unsupported ECDH algorithm") + ErrUnsupportedECIESParameters = errors.New("ecies: unsupported ECIES parameters") ) type ECIESParams struct { diff --git a/eth/backend.go b/eth/backend.go index 91c60d40d9ee..a572015b7786 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -447,7 +447,7 @@ func (s *Ethereum) Etherbase() (eb common.Address, err error) { return etherbase, nil } } - return common.Address{}, fmt.Errorf("etherbase must be explicitly specified") + return common.Address{}, errors.New("etherbase must be explicitly specified") } // set in js console via admin interface or wrapper from cli flags @@ -475,7 +475,7 @@ func (s *Ethereum) ValidateMasternode() (bool, error) { return false, nil } } else { - return false, fmt.Errorf("Only verify masternode permission in XDPoS protocol") + return false, errors.New("Only verify masternode permission in XDPoS protocol") } return true, nil } @@ -487,7 +487,7 @@ func (s *Ethereum) ValidateMasternodeTestnet() (bool, error) { return false, err } if s.chainConfig.XDPoS == nil { - return false, fmt.Errorf("Only verify masternode permission in XDPoS protocol") + return false, errors.New("Only verify masternode permission in XDPoS protocol") } masternodes := []common.Address{ common.HexToAddress("0x3Ea0A3555f9B1dE983572BfF6444aeb1899eC58C"), diff --git a/eth/bft/bft_handler_test.go b/eth/bft/bft_handler_test.go index 5426fc5699ac..11d052ba3f72 100644 --- a/eth/bft/bft_handler_test.go +++ b/eth/bft/bft_handler_test.go @@ -1,7 +1,7 @@ package bft import ( - "fmt" + "errors" "math/big" "sync/atomic" "testing" @@ -102,7 +102,7 @@ func TestNotBoardcastInvalidVote(t *testing.T) { targetVotes := 0 tester.bfter.consensus.verifyVote = func(chain consensus.ChainReader, vote *types.Vote) (bool, error) { - return false, fmt.Errorf("This is invalid vote") + return false, errors.New("This is invalid vote") } tester.bfter.consensus.voteHandler = func(chain consensus.ChainReader, vote *types.Vote) error { diff --git a/eth/filters/api.go b/eth/filters/api.go index 952598046d2c..04256a109620 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -387,7 +387,7 @@ func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*ty api.filtersMu.Unlock() if !found || f.typ != LogsSubscription { - return nil, fmt.Errorf("filter not found") + return nil, errors.New("filter not found") } var filter *Filter @@ -446,7 +446,7 @@ func (api *PublicFilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) { } } - return []interface{}{}, fmt.Errorf("filter not found") + return []interface{}{}, errors.New("filter not found") } // returnHashes is a helper that will return an empty hash array case the given hash array is nil, @@ -485,7 +485,7 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { if raw.BlockHash != nil { if raw.FromBlock != nil || raw.ToBlock != nil { // BlockHash is mutually exclusive with FromBlock/ToBlock criteria - return fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other") + return errors.New("cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other") } args.BlockHash = raw.BlockHash } else { @@ -558,11 +558,11 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { } args.Topics[i] = append(args.Topics[i], parsed) } else { - return fmt.Errorf("invalid topic(s)") + return errors.New("invalid topic(s)") } } default: - return fmt.Errorf("invalid topic(s)") + return errors.New("invalid topic(s)") } } } diff --git a/eth/filters/filter_system.go b/eth/filters/filter_system.go index 2d91b771ef9a..7bf7db629711 100644 --- a/eth/filters/filter_system.go +++ b/eth/filters/filter_system.go @@ -21,7 +21,6 @@ package filters import ( "context" "errors" - "fmt" "sync" "time" @@ -227,7 +226,7 @@ func (es *EventSystem) SubscribeLogs(crit ethereum.FilterQuery, logs chan []*typ if from >= 0 && to == rpc.LatestBlockNumber { return es.subscribeLogs(crit, logs), nil } - return nil, fmt.Errorf("invalid from and to block combination: from > to") + return nil, errors.New("invalid from and to block combination: from > to") } // subscribeMinedPendingLogs creates a subscription that returned mined and diff --git a/eth/hooks/engine_v2_hooks.go b/eth/hooks/engine_v2_hooks.go index 4047014a4d41..f356af27a74c 100644 --- a/eth/hooks/engine_v2_hooks.go +++ b/eth/hooks/engine_v2_hooks.go @@ -2,7 +2,6 @@ package hooks import ( "errors" - "fmt" "math/big" "time" @@ -41,7 +40,7 @@ func AttachConsensusV2Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf if timeout > 30 { // wait over 30s log.Error("[V2 Hook Penalty] parentHeader is nil, wait too long not writen in to disk", "parentNumber", parentNumber) - return []common.Address{}, fmt.Errorf("parentHeader is nil") + return []common.Address{}, errors.New("parentHeader is nil") } } diff --git a/eth/tracers/tracer.go b/eth/tracers/tracer.go index 6216bc48a8a7..cc4bac514715 100644 --- a/eth/tracers/tracer.go +++ b/eth/tracers/tracer.go @@ -427,17 +427,17 @@ func New(code string) (*Tracer, error) { tracer.tracerObject = 0 // yeah, nice, eval can't return the index itself if !tracer.vm.GetPropString(tracer.tracerObject, "step") { - return nil, fmt.Errorf("trace object must expose a function step()") + return nil, errors.New("trace object must expose a function step()") } tracer.vm.Pop() if !tracer.vm.GetPropString(tracer.tracerObject, "fault") { - return nil, fmt.Errorf("trace object must expose a function fault()") + return nil, errors.New("trace object must expose a function fault()") } tracer.vm.Pop() if !tracer.vm.GetPropString(tracer.tracerObject, "result") { - return nil, fmt.Errorf("trace object must expose a function result()") + return nil, errors.New("trace object must expose a function result()") } tracer.vm.Pop() @@ -548,7 +548,6 @@ func (jst *Tracer) CaptureStart(env *vm.EVM, from common.Address, to common.Addr jst.ctx["intrinsicGas"] = intrinsicGas } - // CaptureState implements the Tracer interface to trace a single step of VM execution. func (jst *Tracer) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) { if jst.err != nil { @@ -581,7 +580,6 @@ func (jst *Tracer) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost } } - // CaptureFault implements the Tracer interface to trace an execution fault func (jst *Tracer) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) { if jst.err != nil { diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index 22dc3a0fd852..592b7db35696 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -105,16 +105,16 @@ func (ec *Client) getBlock(ctx context.Context, method string, args ...interface } // Quick-verify transaction and uncle lists. This mostly helps with debugging the server. if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 { - return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles") + return nil, errors.New("server returned non-empty uncle list but block header indicates no uncles") } if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 { - return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles") + return nil, errors.New("server returned empty uncle list but block header indicates uncles") } if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 { - return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions") + return nil, errors.New("server returned non-empty transaction list but block header indicates no transactions") } if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 { - return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions") + return nil, errors.New("server returned empty transaction list but block header indicates transactions") } // Load uncles because they are not included in the block response. var uncles []*types.Header @@ -197,7 +197,7 @@ func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx * } else if json == nil { return nil, false, ethereum.NotFound } else if _, r, _ := json.tx.RawSignatureValues(); r == nil { - return nil, false, fmt.Errorf("server returned transaction without signature") + return nil, false, errors.New("server returned transaction without signature") } setSenderFromServer(json.tx, json.From, json.BlockHash) return json.tx, json.BlockNumber == nil, nil @@ -243,7 +243,7 @@ func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, if json == nil { return nil, ethereum.NotFound } else if _, r, _ := json.tx.RawSignatureValues(); r == nil { - return nil, fmt.Errorf("server returned transaction without signature") + return nil, errors.New("server returned transaction without signature") } } setSenderFromServer(json.tx, json.From, json.BlockHash) diff --git a/event/feed_test.go b/event/feed_test.go index a82c10303362..6c4c91b5b495 100644 --- a/event/feed_test.go +++ b/event/feed_test.go @@ -17,6 +17,7 @@ package event import ( + "errors" "fmt" "reflect" "sync" @@ -68,7 +69,7 @@ func checkPanic(want error, fn func()) (err error) { defer func() { panic := recover() if panic == nil { - err = fmt.Errorf("didn't panic") + err = errors.New("didn't panic") } else if !reflect.DeepEqual(panic, want) { err = fmt.Errorf("panicked with wrong error: got %q, want %q", panic, want) } diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 80ea1c1a317f..650135e06752 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -404,13 +404,13 @@ func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs // No need to obtain the noncelock mutex, since we won't be sending this // tx into the transaction pool, but right back to the user if args.Gas == nil { - return nil, fmt.Errorf("gas not specified") + return nil, errors.New("gas not specified") } if args.GasPrice == nil { - return nil, fmt.Errorf("gasPrice not specified") + return nil, errors.New("gasPrice not specified") } if args.Nonce == nil { - return nil, fmt.Errorf("nonce not specified") + return nil, errors.New("nonce not specified") } signed, err := s.signTransaction(ctx, args, passwd) if err != nil { @@ -478,7 +478,7 @@ func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Byt return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength) } if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 { - return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)") + return common.Address{}, errors.New("invalid Ethereum signature (V is not 27 or 28)") } sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1 @@ -915,7 +915,7 @@ func (s *PublicBlockChainAPI) GetCandidateStatus(ctx context.Context, coinbaseAd } maxMasternodes = s.b.ChainConfig().XDPoS.V2.Config(uint64(round)).MaxMasternodes } else { - return result, fmt.Errorf("undefined XDPoS consensus engine") + return result, errors.New("undefined XDPoS consensus engine") } } else if s.b.ChainConfig().IsTIPIncreaseMasternodes(block.Number()) { maxMasternodes = common.MaxMasternodesV2 @@ -1106,7 +1106,7 @@ func (s *PublicBlockChainAPI) GetCandidates(ctx context.Context, epoch rpc.Epoch } maxMasternodes = s.b.ChainConfig().XDPoS.V2.Config(uint64(round)).MaxMasternodes } else { - return result, fmt.Errorf("undefined XDPoS consensus engine") + return result, errors.New("undefined XDPoS consensus engine") } } else if s.b.ChainConfig().IsTIPIncreaseMasternodes(block.Number()) { maxMasternodes = common.MaxMasternodesV2 @@ -3348,13 +3348,13 @@ type SignTransactionResult struct { // the given from address and it needs to be unlocked. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) { if args.Gas == nil { - return nil, fmt.Errorf("gas not specified") + return nil, errors.New("gas not specified") } if args.GasPrice == nil { - return nil, fmt.Errorf("gasPrice not specified") + return nil, errors.New("gasPrice not specified") } if args.Nonce == nil { - return nil, fmt.Errorf("nonce not specified") + return nil, errors.New("nonce not specified") } if err := args.setDefaults(ctx, s.b); err != nil { return nil, err @@ -3397,7 +3397,7 @@ func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, err // the given transaction from the pool and reinsert it with the new gas price and limit. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { if sendArgs.Nonce == nil { - return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec") + return common.Hash{}, errors.New("missing transaction nonce in transaction spec") } if err := sendArgs.setDefaults(ctx, s.b); err != nil { return common.Hash{}, err @@ -3494,7 +3494,7 @@ func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { LDB() *leveldb.DB }) if !ok { - return "", fmt.Errorf("chaindbProperty does not work for memory databases") + return "", errors.New("chaindbProperty does not work for memory databases") } if property == "" { property = "leveldb.stats" @@ -3509,7 +3509,7 @@ func (api *PrivateDebugAPI) ChaindbCompact() error { LDB() *leveldb.DB }) if !ok { - return fmt.Errorf("chaindbCompact does not work for memory databases") + return errors.New("chaindbCompact does not work for memory databases") } for b := byte(0); b < 255; b++ { log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) diff --git a/internal/ethapi/trie_proof_test.go b/internal/ethapi/trie_proof_test.go index 10dd9988dbc5..34922b9c60ff 100644 --- a/internal/ethapi/trie_proof_test.go +++ b/internal/ethapi/trie_proof_test.go @@ -2,7 +2,7 @@ package ethapi import ( "bytes" - "fmt" + "errors" "math/big" "reflect" "testing" @@ -36,7 +36,7 @@ func (n *proofPairList) Get(key []byte) ([]byte, error) { return b, nil } } - return nil, fmt.Errorf("key not found") + return nil, errors.New("key not found") } func TestTransactionProof(t *testing.T) { diff --git a/les/backend.go b/les/backend.go index b172e8fc0022..a4b2074744db 100644 --- a/les/backend.go +++ b/les/backend.go @@ -18,7 +18,7 @@ package les import ( - "fmt" + "errors" "sync" "time" @@ -155,12 +155,12 @@ type LightDummyAPI struct{} // Etherbase is the address that mining rewards will be send to func (s *LightDummyAPI) Etherbase() (common.Address, error) { - return common.Address{}, fmt.Errorf("not supported") + return common.Address{}, errors.New("not supported") } // Coinbase is the address that mining rewards will be send to (alias for Etherbase) func (s *LightDummyAPI) Coinbase() (common.Address, error) { - return common.Address{}, fmt.Errorf("not supported") + return common.Address{}, errors.New("not supported") } // Hashrate returns the POW hashrate diff --git a/les/peer.go b/les/peer.go index ef635795bfcb..cbc7b9957020 100644 --- a/les/peer.go +++ b/les/peer.go @@ -291,7 +291,7 @@ func (p *peer) RequestHelperTrieProofs(reqID, cost uint64, reqs []HelperTrieReq) reqsV1 := make([]ChtReq, len(reqs)) for i, req := range reqs { if req.Type != htCanonical || req.AuxReq != auxHeader || len(req.Key) != 8 { - return fmt.Errorf("Request invalid in LES/1 mode") + return errors.New("Request invalid in LES/1 mode") } blockNum := binary.BigEndian.Uint64(req.Key) // convert HelperTrie request to old CHT request diff --git a/les/retrieve.go b/les/retrieve.go index 91014f1964ab..509b8a3e356c 100644 --- a/les/retrieve.go +++ b/les/retrieve.go @@ -22,7 +22,7 @@ import ( "context" "crypto/rand" "encoding/binary" - "fmt" + "errors" "sync" "time" @@ -119,7 +119,7 @@ func (rm *retrieveManager) retrieve(ctx context.Context, reqID uint64, req *dist case <-ctx.Done(): sentReq.stop(ctx.Err()) case <-shutdown: - sentReq.stop(fmt.Errorf("Client is shutting down")) + sentReq.stop(errors.New("Client is shutting down")) } return sentReq.getError() } diff --git a/light/trie_test.go b/light/trie_test.go index fb030af871a5..2332043d2611 100644 --- a/light/trie_test.go +++ b/light/trie_test.go @@ -19,10 +19,12 @@ package light import ( "bytes" "context" + "errors" "fmt" - "github.com/XinFinOrg/XDPoSChain/core/rawdb" "testing" + "github.com/XinFinOrg/XDPoSChain/core/rawdb" + "github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core/state" @@ -74,9 +76,9 @@ func diffTries(t1, t2 state.Trie) error { case i2.Err != nil: return fmt.Errorf("light trie iterator error: %v", i1.Err) case i1.Next(): - return fmt.Errorf("full trie iterator has more k/v pairs") + return errors.New("full trie iterator has more k/v pairs") case i2.Next(): - return fmt.Errorf("light trie iterator has more k/v pairs") + return errors.New("light trie iterator has more k/v pairs") } return nil } diff --git a/node/api.go b/node/api.go index e03f668b172c..8a3611524418 100644 --- a/node/api.go +++ b/node/api.go @@ -18,6 +18,7 @@ package node import ( "context" + "errors" "fmt" "strings" "time" @@ -169,7 +170,7 @@ func (api *PrivateAdminAPI) StopRPC() (bool, error) { defer api.node.lock.Unlock() if api.node.httpHandler == nil { - return false, fmt.Errorf("HTTP RPC not running") + return false, errors.New("HTTP RPC not running") } api.node.stopHTTP() return true, nil @@ -223,7 +224,7 @@ func (api *PrivateAdminAPI) StopWS() (bool, error) { defer api.node.lock.Unlock() if api.node.wsHandler == nil { - return false, fmt.Errorf("WebSocket RPC not running") + return false, errors.New("WebSocket RPC not running") } api.node.stopWS() return true, nil diff --git a/node/service_test.go b/node/service_test.go index 86fb1a6fbdd5..23dc80708411 100644 --- a/node/service_test.go +++ b/node/service_test.go @@ -17,6 +17,7 @@ package node import ( + "errors" "fmt" "os" "path/filepath" @@ -70,7 +71,7 @@ func TestContextServices(t *testing.T) { verifier := func(ctx *ServiceContext) (Service, error) { var objA *NoopServiceA if ctx.Service(&objA) != nil { - return nil, fmt.Errorf("former service not found") + return nil, errors.New("former service not found") } var objB *NoopServiceB if err := ctx.Service(&objB); err != ErrServiceUnknown { diff --git a/p2p/discv5/net.go b/p2p/discv5/net.go index c24823967c6a..097771553d28 100644 --- a/p2p/discv5/net.go +++ b/p2p/discv5/net.go @@ -1063,7 +1063,7 @@ func (net *Network) checkPacket(n *Node, ev nodeEvent, pkt *ingressPacket) error case pongPacket: if !bytes.Equal(pkt.data.(*pong).ReplyTok, n.pingEcho) { // fmt.Println("pong reply token mismatch") - return fmt.Errorf("pong reply token mismatch") + return errors.New("pong reply token mismatch") } n.pingEcho = nil } diff --git a/p2p/discv5/ticket.go b/p2p/discv5/ticket.go index 7c82d2db975b..2a6d40e244e1 100644 --- a/p2p/discv5/ticket.go +++ b/p2p/discv5/ticket.go @@ -19,6 +19,7 @@ package discv5 import ( "bytes" "encoding/binary" + "errors" "fmt" "math" "math/rand" @@ -95,7 +96,7 @@ func pongToTicket(localTime mclock.AbsTime, topics []Topic, node *Node, p *ingre return nil, fmt.Errorf("bad wait period list: got %d values, want %d", len(topics), len(wps)) } if rlpHash(topics) != p.data.(*pong).TopicHash { - return nil, fmt.Errorf("bad topic hash") + return nil, errors.New("bad topic hash") } t := &ticket{ issueTime: localTime, diff --git a/p2p/enr/enr.go b/p2p/enr/enr.go index 28c8e26da5b3..5aca3ab25a6c 100644 --- a/p2p/enr/enr.go +++ b/p2p/enr/enr.go @@ -275,7 +275,7 @@ func (r *Record) verifySignature() error { if err := r.Load(&entry); err != nil { return err } else if len(entry) != 33 { - return fmt.Errorf("invalid public key") + return errors.New("invalid public key") } // Verify the signature. diff --git a/p2p/nat/natpmp.go b/p2p/nat/natpmp.go index 577a424fbec1..df4764cc1074 100644 --- a/p2p/nat/natpmp.go +++ b/p2p/nat/natpmp.go @@ -17,12 +17,13 @@ package nat import ( + "errors" "fmt" "net" "strings" "time" - "github.com/jackpal/go-nat-pmp" + natpmp "github.com/jackpal/go-nat-pmp" ) // natPMPClient adapts the NAT-PMP protocol implementation so it conforms to @@ -46,7 +47,7 @@ func (n *pmp) ExternalIP() (net.IP, error) { func (n *pmp) AddMapping(protocol string, extport, intport int, name string, lifetime time.Duration) error { if lifetime <= 0 { - return fmt.Errorf("lifetime must not be <= 0") + return errors.New("lifetime must not be <= 0") } // Note order of port arguments is switched between our // AddMapping and the client's AddPortMapping. diff --git a/p2p/peer.go b/p2p/peer.go index a7eb05621f13..1d1cfc8906f6 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -17,6 +17,7 @@ package p2p import ( + "errors" "fmt" "io" "net" @@ -409,7 +410,7 @@ func (rw *protoRW) WriteMsg(msg Msg) (err error) { // as well but we don't want to rely on that. rw.werr <- err case <-rw.closed: - err = fmt.Errorf("shutting down") + err = errors.New("shutting down") } return err } diff --git a/p2p/protocols/protocol_test.go b/p2p/protocols/protocol_test.go index a4247917c76c..bcd3186f6ce3 100644 --- a/p2p/protocols/protocol_test.go +++ b/p2p/protocols/protocol_test.go @@ -43,7 +43,7 @@ type kill struct { type drop struct { } -/// protoHandshake represents module-independent aspects of the protocol and is +// / protoHandshake represents module-independent aspects of the protocol and is // the first message peers send and receive as part the initial exchange type protoHandshake struct { Version uint // local and remote peer should have identical version @@ -241,7 +241,7 @@ func runModuleHandshake(t *testing.T, resp uint, errs ...error) { } func TestModuleHandshakeError(t *testing.T) { - runModuleHandshake(t, 43, fmt.Errorf("handshake mismatch remote 43 > local 42")) + runModuleHandshake(t, 43, errors.New("handshake mismatch remote 43 > local 42")) } func TestModuleHandshakeSuccess(t *testing.T) { @@ -376,14 +376,14 @@ WAIT: func TestMultiplePeersDropSelf(t *testing.T) { runMultiplePeers(t, 0, - fmt.Errorf("subprotocol error"), - fmt.Errorf("Message handler error: (msg code 3): dropped"), + errors.New("subprotocol error"), + errors.New("Message handler error: (msg code 3): dropped"), ) } func TestMultiplePeersDropOther(t *testing.T) { runMultiplePeers(t, 1, - fmt.Errorf("Message handler error: (msg code 3): dropped"), - fmt.Errorf("subprotocol error"), + errors.New("Message handler error: (msg code 3): dropped"), + errors.New("subprotocol error"), ) } diff --git a/p2p/rlpx.go b/p2p/rlpx.go index ea26b2f2ec8c..5ceb897eae09 100644 --- a/p2p/rlpx.go +++ b/p2p/rlpx.go @@ -147,7 +147,7 @@ func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, return nil, err } if msg.Size > baseProtocolMaxMsgSize { - return nil, fmt.Errorf("message too big") + return nil, errors.New("message too big") } if msg.Code == discMsg { // Disconnect before protocol handshake is valid according to the diff --git a/p2p/server.go b/p2p/server.go index f20cba6ddea2..2ccb4cf17a84 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -20,7 +20,6 @@ package p2p import ( "crypto/ecdsa" "errors" - "fmt" "net" "sync" "time" @@ -365,7 +364,7 @@ type sharedUDPConn struct { func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { packet, ok := <-s.unhandled if !ok { - return 0, nil, fmt.Errorf("Connection was closed") + return 0, nil, errors.New("Connection was closed") } l := len(packet.Data) if l > len(b) { @@ -397,7 +396,7 @@ func (srv *Server) Start() (err error) { // static fields if srv.PrivateKey == nil { - return fmt.Errorf("Server.PrivateKey must be set to a non-nil key") + return errors.New("Server.PrivateKey must be set to a non-nil key") } if srv.newTransport == nil { srv.newTransport = newRLPX diff --git a/p2p/testing/protocolsession.go b/p2p/testing/protocolsession.go index da221189b912..2c0133b111b1 100644 --- a/p2p/testing/protocolsession.go +++ b/p2p/testing/protocolsession.go @@ -273,7 +273,7 @@ func (self *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error } delete(expects, event.Peer) case <-timeout: - return fmt.Errorf("timed out waiting for peers to disconnect") + return errors.New("timed out waiting for peers to disconnect") } } return nil diff --git a/rpc/types.go b/rpc/types.go index a48dd7a1f3d0..f3b50a259be6 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -19,7 +19,7 @@ package rpc import ( "context" "encoding/json" - "fmt" + "errors" "math" "strings" @@ -109,7 +109,7 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error { return err } if blckNum > math.MaxInt64 { - return fmt.Errorf("block number larger than int64") + return errors.New("block number larger than int64") } *bn = BlockNumber(blckNum) return nil @@ -131,7 +131,7 @@ func (e *EpochNumber) UnmarshalJSON(data []byte) error { return err } if eNum > math.MaxInt64 { - return fmt.Errorf("EpochNumber too high") + return errors.New("EpochNumber too high") } *e = EpochNumber(eNum) @@ -154,7 +154,7 @@ func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error { err := json.Unmarshal(data, &e) if err == nil { if e.BlockNumber != nil && e.BlockHash != nil { - return fmt.Errorf("cannot specify both BlockHash and BlockNumber, choose one or the other") + return errors.New("cannot specify both BlockHash and BlockNumber, choose one or the other") } bnh.BlockNumber = e.BlockNumber bnh.BlockHash = e.BlockHash @@ -198,7 +198,7 @@ func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error { return err } if blckNum > math.MaxInt64 { - return fmt.Errorf("blocknumber too high") + return errors.New("blocknumber too high") } bn := BlockNumber(blckNum) bnh.BlockNumber = &bn diff --git a/swarm/api/filesystem.go b/swarm/api/filesystem.go index ca5d2d46415a..644539ad734b 100644 --- a/swarm/api/filesystem.go +++ b/swarm/api/filesystem.go @@ -18,6 +18,7 @@ package api import ( "bufio" + "errors" "fmt" "io" "net/http" @@ -69,7 +70,7 @@ func (self *FileSystem) Upload(lpath, index string) (string, error) { err = filepath.Walk(localpath, func(path string, info os.FileInfo, err error) error { if (err == nil) && !info.IsDir() { if len(path) <= start { - return fmt.Errorf("Path is too short") + return errors.New("Path is too short") } if path[:start] != localpath { return fmt.Errorf("Path prefix of '%s' does not match localpath '%s'", path, localpath) @@ -86,7 +87,7 @@ func (self *FileSystem) Upload(lpath, index string) (string, error) { dir := filepath.Dir(localpath) start = len(dir) if len(localpath) <= start { - return "", fmt.Errorf("Path is too short") + return "", errors.New("Path is too short") } if localpath[:start] != dir { return "", fmt.Errorf("Path prefix of '%s' does not match dir '%s'", localpath, dir) @@ -240,7 +241,7 @@ func (self *FileSystem) Download(bzzpath, localpath string) error { case done <- true: wg.Add(1) case <-quitC: - return fmt.Errorf("aborted") + return errors.New("aborted") } go func(i int, entry *downloadListEntry) { defer wg.Done() @@ -263,7 +264,7 @@ func (self *FileSystem) Download(bzzpath, localpath string) error { case err = <-errC: return err case <-quitC: - return fmt.Errorf("aborted") + return errors.New("aborted") } } diff --git a/swarm/api/http/server.go b/swarm/api/http/server.go index c1d9a36ad541..238deaecf5ef 100644 --- a/swarm/api/http/server.go +++ b/swarm/api/http/server.go @@ -374,7 +374,7 @@ func (s *Server) HandleGet(w http.ResponseWriter, r *Request) { }) if entry == nil { getFail.Inc(1) - s.NotFound(w, r, fmt.Errorf("Manifest entry could not be loaded")) + s.NotFound(w, r, errors.New("Manifest entry could not be loaded")) return } key = storage.Key(common.Hex2Bytes(entry.Hash)) diff --git a/swarm/api/manifest.go b/swarm/api/manifest.go index f540de4301f0..d5969455ba8e 100644 --- a/swarm/api/manifest.go +++ b/swarm/api/manifest.go @@ -195,7 +195,7 @@ func readManifest(manifestReader storage.LazySectionReader, hash storage.Key, dp size, err := manifestReader.Size(quitC) if err != nil { // size == 0 // can't determine size means we don't have the root chunk - err = fmt.Errorf("Manifest not Found") + err = errors.New("Manifest not Found") return } manifestData := make([]byte, size) @@ -381,7 +381,7 @@ func (self *manifestTrie) listWithPrefixInt(prefix, rp string, quitC chan bool, for i := start; i <= stop; i++ { select { case <-quitC: - return fmt.Errorf("aborted") + return errors.New("aborted") default: } entry := self.entries[i] diff --git a/swarm/fuse/swarmfs_util.go b/swarm/fuse/swarmfs_util.go index 9817791ffba5..27259ac7e9b7 100644 --- a/swarm/fuse/swarmfs_util.go +++ b/swarm/fuse/swarmfs_util.go @@ -14,13 +14,14 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . +//go:build linux || darwin || freebsd // +build linux darwin freebsd package fuse import ( "context" - "fmt" + "errors" "os/exec" "runtime" @@ -42,7 +43,7 @@ func externalUnmount(mountPoint string) error { case "linux": return exec.CommandContext(ctx, "fusermount", "-u", mountPoint).Run() default: - return fmt.Errorf("unmount: unimplemented") + return errors.New("unmount: unimplemented") } } diff --git a/swarm/network/hive.go b/swarm/network/hive.go index 49b8b7fd71c6..511934064433 100644 --- a/swarm/network/hive.go +++ b/swarm/network/hive.go @@ -17,6 +17,7 @@ package network import ( + "errors" "fmt" "math/rand" "path/filepath" @@ -77,7 +78,7 @@ type HiveParams struct { *kademlia.KadParams } -//create default params +// create default params func NewDefaultHiveParams() *HiveParams { kad := kademlia.NewDefaultKadParams() // kad.BucketSize = bucketSize @@ -90,8 +91,8 @@ func NewDefaultHiveParams() *HiveParams { } } -//this can only finally be set after all config options (file, cmd line, env vars) -//have been evaluated +// this can only finally be set after all config options (file, cmd line, env vars) +// have been evaluated func (self *HiveParams) Init(path string) { self.KadDbPath = filepath.Join(path, "bzz-peers.json") } @@ -338,7 +339,7 @@ func (self *peer) LastActive() time.Time { func loadSync(record *kademlia.NodeRecord, node kademlia.Node) error { p, ok := node.(*peer) if !ok { - return fmt.Errorf("invalid type") + return errors.New("invalid type") } if record.Meta == nil { log.Debug(fmt.Sprintf("no sync state for node record %v setting default", record)) diff --git a/swarm/network/kademlia/kademlia.go b/swarm/network/kademlia/kademlia.go index f294b4805356..84380afc0863 100644 --- a/swarm/network/kademlia/kademlia.go +++ b/swarm/network/kademlia/kademlia.go @@ -17,6 +17,7 @@ package kademlia import ( + "errors" "fmt" "sort" "strings" @@ -27,10 +28,10 @@ import ( "github.com/XinFinOrg/XDPoSChain/metrics" ) -//metrics variables -//For metrics, we want to count how many times peers are added/removed -//at a certain index. Thus we do that with an array of counters with -//entry for each index +// metrics variables +// For metrics, we want to count how many times peers are added/removed +// at a certain index. Thus we do that with an array of counters with +// entry for each index var ( bucketAddIndexCount []metrics.Counter bucketRmIndexCount []metrics.Counter @@ -172,7 +173,7 @@ func (self *Kademlia) On(node Node, cb func(*NodeRecord, Node) error) (err error } if replaced == nil { log.Debug(fmt.Sprintf("all peers wanted, PO%03d bucket full", index)) - return fmt.Errorf("bucket full") + return errors.New("bucket full") } log.Debug(fmt.Sprintf("node %v replaced by %v (idle for %v > %v)", replaced, node, idle, self.MaxIdleInterval)) replaced.Drop() @@ -310,7 +311,7 @@ func (self *Kademlia) Suggest() (*NodeRecord, bool, int) { return self.db.findBest(self.BucketSize, func(i int) int { return len(self.buckets[i]) }) } -// adds node records to kaddb (persisted node record db) +// adds node records to kaddb (persisted node record db) func (self *Kademlia) Add(nrs []*NodeRecord) { self.db.add(nrs, self.proximityBin) } @@ -441,7 +442,7 @@ func (self *Kademlia) String() string { return strings.Join(rows, "\n") } -//We have to build up the array of counters for each index +// We have to build up the array of counters for each index func (self *Kademlia) initMetricsVariables() { //create the arrays bucketAddIndexCount = make([]metrics.Counter, self.MaxProx+1) diff --git a/swarm/network/protocol.go b/swarm/network/protocol.go index be793b40a146..1753f8fb3a29 100644 --- a/swarm/network/protocol.go +++ b/swarm/network/protocol.go @@ -46,7 +46,7 @@ import ( "github.com/XinFinOrg/XDPoSChain/swarm/storage" ) -//metrics variables +// metrics variables var ( storeRequestMsgCounter = metrics.NewRegisteredCounter("network.protocol.msg.storerequest.count", nil) retrieveRequestMsgCounter = metrics.NewRegisteredCounter("network.protocol.msg.retrieverequest.count", nil) @@ -133,15 +133,15 @@ func Bzz(cloud StorageHandler, backend chequebook.Backend, hive *Hive, dbaccess /* the main protocol loop that - * does the handshake by exchanging statusMsg - * if peer is valid and accepted, registers with the hive - * then enters into a forever loop handling incoming messages - * storage and retrieval related queries coming via bzz are dispatched to StorageHandler - * peer-related messages are dispatched to the hive - * payment related messages are relayed to SWAP service - * on disconnect, unregister the peer in the hive (note RemovePeer in the post-disconnect hook) - * whenever the loop terminates, the peer will disconnect with Subprotocol error - * whenever handlers return an error the loop terminates + - does the handshake by exchanging statusMsg + - if peer is valid and accepted, registers with the hive + - then enters into a forever loop handling incoming messages + - storage and retrieval related queries coming via bzz are dispatched to StorageHandler + - peer-related messages are dispatched to the hive + - payment related messages are relayed to SWAP service + - on disconnect, unregister the peer in the hive (note RemovePeer in the post-disconnect hook) + - whenever the loop terminates, the peer will disconnect with Subprotocol error + - whenever handlers return an error the loop terminates */ func run(requestDb *storage.LDBDatabase, depo StorageHandler, backend chequebook.Backend, hive *Hive, dbaccess *DbAccess, sp *bzzswap.SwapParams, sy *SyncParams, networkId uint64, p *p2p.Peer, rw p2p.MsgReadWriter) (err error) { @@ -246,7 +246,7 @@ func (self *bzz) handle() error { if req.isLookup() { log.Trace(fmt.Sprintf("self lookup for %v: responding with peers only...", req.from)) } else if req.Key == nil { - return fmt.Errorf("protocol handler: req.Key == nil || req.Timeout == nil") + return errors.New("protocol handler: req.Key == nil || req.Timeout == nil") } else { // swap accounting is done within netStore self.storage.HandleRetrieveRequestMsg(&req, &peer{bzz: self}) @@ -523,7 +523,7 @@ func (self *bzz) peers(req *peersMsgData) error { func (self *bzz) send(msg uint64, data interface{}) error { if self.hive.blockWrite { - return fmt.Errorf("network write blocked") + return errors.New("network write blocked") } log.Trace(fmt.Sprintf("-> %v: %v (%T) to %v", msg, data, data, self)) err := p2p.Send(self.rw, msg, data) diff --git a/swarm/network/syncer.go b/swarm/network/syncer.go index abdb33954be9..4cb99c60f1f1 100644 --- a/swarm/network/syncer.go +++ b/swarm/network/syncer.go @@ -19,6 +19,7 @@ package network import ( "encoding/binary" "encoding/json" + "errors" "fmt" "path/filepath" @@ -143,8 +144,8 @@ func NewDefaultSyncParams() *SyncParams { } } -//this can only finally be set after all config options (file, cmd line, env vars) -//have been evaluated +// this can only finally be set after all config options (file, cmd line, env vars) +// have been evaluated func (self *SyncParams) Init(path string) { self.RequestDbPath = filepath.Join(path, "requests") } @@ -237,11 +238,11 @@ func encodeSync(state *syncState) (*json.RawMessage, error) { func decodeSync(meta *json.RawMessage) (*syncState, error) { if meta == nil { - return nil, fmt.Errorf("unable to deserialise sync state from ") + return nil, errors.New("unable to deserialise sync state from ") } data := []byte(*(meta)) if len(data) == 0 { - return nil, fmt.Errorf("unable to deserialise sync state from ") + return nil, errors.New("unable to deserialise sync state from ") } state := &syncState{DbSyncState: &storage.DbSyncState{}} err := json.Unmarshal(data, state) @@ -249,22 +250,22 @@ func decodeSync(meta *json.RawMessage) (*syncState, error) { } /* - sync implements the syncing script - * first all items left in the request Db are replayed - * type = StaleSync - * Mode: by default once again via confirmation roundtrip - * Priority: the items are replayed as the proirity specified for StaleSync - * but within the order respects earlier priority level of request - * after all items are consumed for a priority level, the the respective - queue for delivery requests is open (this way new reqs not written to db) - (TODO: this should be checked) - * the sync state provided by the remote peer is used to sync history - * all the backlog from earlier (aborted) syncing is completed starting from latest - * if Last < LastSeenAt then all items in between then process all - backlog from upto last disconnect - * if Last > 0 && - - sync is called from the syncer constructor and is not supposed to be used externally +sync implements the syncing script +* first all items left in the request Db are replayed + - type = StaleSync + - Mode: by default once again via confirmation roundtrip + - Priority: the items are replayed as the proirity specified for StaleSync + - but within the order respects earlier priority level of request + - after all items are consumed for a priority level, the the respective + queue for delivery requests is open (this way new reqs not written to db) + (TODO: this should be checked) + - the sync state provided by the remote peer is used to sync history + - all the backlog from earlier (aborted) syncing is completed starting from latest + - if Last < LastSeenAt then all items in between then process all + backlog from upto last disconnect + - if Last > 0 && + +sync is called from the syncer constructor and is not supposed to be used externally */ func (self *syncer) sync() { state := self.state @@ -406,11 +407,11 @@ func (self *syncer) sendUnsyncedKeys() { } // assembles a new batch of unsynced keys -// * keys are drawn from the key buffers in order of priority queue -// * if the queues of priority for History (HistoryReq) or higher are depleted, -// historical data is used so historical items are lower priority within -// their priority group. -// * Order of historical data is unspecified +// - keys are drawn from the key buffers in order of priority queue +// - if the queues of priority for History (HistoryReq) or higher are depleted, +// historical data is used so historical items are lower priority within +// their priority group. +// - Order of historical data is unspecified func (self *syncer) syncUnsyncedKeys() { // send out new var unsynced []*syncRequest @@ -621,19 +622,19 @@ func (self *syncer) syncDeliveries() { } /* - addRequest handles requests for delivery - it accepts 4 types: +addRequest handles requests for delivery +it accepts 4 types: - * storeRequestMsgData: coming from netstore propagate response - * chunk: coming from forwarding (questionable: id?) - * key: from incoming syncRequest - * syncDbEntry: key,id encoded in db +* storeRequestMsgData: coming from netstore propagate response +* chunk: coming from forwarding (questionable: id?) +* key: from incoming syncRequest +* syncDbEntry: key,id encoded in db - If sync mode is on for the type of request, then - it sends the request to the keys queue of the correct priority - channel buffered with capacity (SyncBufferSize) +If sync mode is on for the type of request, then +it sends the request to the keys queue of the correct priority +channel buffered with capacity (SyncBufferSize) - If sync mode is off then, requests are directly sent to deliveries +If sync mode is off then, requests are directly sent to deliveries */ func (self *syncer) addRequest(req interface{}, ty int) { // retrieve priority for request type name int8 diff --git a/swarm/storage/chunker_test.go b/swarm/storage/chunker_test.go index 2dcbbe79caf9..e3409bbfb571 100644 --- a/swarm/storage/chunker_test.go +++ b/swarm/storage/chunker_test.go @@ -183,7 +183,7 @@ func testRandomBrokenData(splitter Splitter, n int, tester *chunkerTester) { chunkC := make(chan *Chunk, 1000) swg := &sync.WaitGroup{} - expectedError := fmt.Errorf("Broken reader") + expectedError := errors.New("Broken reader") key, err := tester.Split(splitter, brokendata, int64(n), chunkC, swg, expectedError) if err == nil || err.Error() != expectedError.Error() { tester.t.Fatalf("Not receiving the correct error! Expected %v, received %v", expectedError, err) diff --git a/swarm/storage/common_test.go b/swarm/storage/common_test.go index 6a3e6e06d0d7..d566c674fa98 100644 --- a/swarm/storage/common_test.go +++ b/swarm/storage/common_test.go @@ -19,6 +19,7 @@ package storage import ( "bytes" "crypto/rand" + "errors" "fmt" "io" "sync" @@ -48,7 +49,7 @@ func testDataReader(l int) (r io.Reader) { func (self *brokenLimitedReader) Read(buf []byte) (int, error) { if self.off+len(buf) > self.errAt { - return 0, fmt.Errorf("Broken reader") + return 0, errors.New("Broken reader") } self.off += len(buf) return self.lr.Read(buf) diff --git a/swarm/storage/dbstore.go b/swarm/storage/dbstore.go index caac05e1379c..c94953651173 100644 --- a/swarm/storage/dbstore.go +++ b/swarm/storage/dbstore.go @@ -27,6 +27,7 @@ import ( "bytes" "encoding/binary" "encoding/hex" + "errors" "fmt" "io" "sync" @@ -562,7 +563,7 @@ type dbSyncIterator struct { // initialises a sync iterator from a syncToken (passed in with the handshake) func (self *DbStore) NewSyncIterator(state DbSyncState) (si *dbSyncIterator, err error) { if state.First > state.Last { - return nil, fmt.Errorf("no entries found") + return nil, errors.New("no entries found") } si = &dbSyncIterator{ it: self.db.NewIterator(), diff --git a/swarm/swarm.go b/swarm/swarm.go index cb1e4a0676c7..5c732449dad8 100644 --- a/swarm/swarm.go +++ b/swarm/swarm.go @@ -20,6 +20,7 @@ import ( "bytes" "context" "crypto/ecdsa" + "errors" "fmt" "math/big" "net" @@ -94,10 +95,10 @@ func (self *Swarm) API() *SwarmAPI { // implements node.Service func NewSwarm(ctx *node.ServiceContext, backend chequebook.Backend, config *api.Config) (self *Swarm, err error) { if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroKey) { - return nil, fmt.Errorf("empty public key") + return nil, errors.New("empty public key") } if bytes.Equal(common.FromHex(config.BzzKey), storage.ZeroKey) { - return nil, fmt.Errorf("empty bzz key") + return nil, errors.New("empty bzz key") } self = &Swarm{ diff --git a/tests/block_test_util.go b/tests/block_test_util.go index 684fbf1d66e7..72e9f210809a 100644 --- a/tests/block_test_util.go +++ b/tests/block_test_util.go @@ -21,10 +21,12 @@ import ( "bytes" "encoding/hex" "encoding/json" + "errors" "fmt" - "github.com/XinFinOrg/XDPoSChain/core/rawdb" "math/big" + "github.com/XinFinOrg/XDPoSChain/core/rawdb" + "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common/hexutil" "github.com/XinFinOrg/XDPoSChain/common/math" @@ -150,17 +152,18 @@ func (t *BlockTest) genesis(config *params.ChainConfig) *core.Genesis { } } -/* See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II +/* +See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II - Whether a block is valid or not is a bit subtle, it's defined by presence of - blockHeader, transactions and uncleHeaders fields. If they are missing, the block is - invalid and we must verify that we do not accept it. + Whether a block is valid or not is a bit subtle, it's defined by presence of + blockHeader, transactions and uncleHeaders fields. If they are missing, the block is + invalid and we must verify that we do not accept it. - Since some tests mix valid and invalid blocks we need to check this for every block. + Since some tests mix valid and invalid blocks we need to check this for every block. - If a block is invalid it does not necessarily fail the test, if it's invalidness is - expected we are expected to ignore it and continue processing and then validate the - post state. + If a block is invalid it does not necessarily fail the test, if it's invalidness is + expected we are expected to ignore it and continue processing and then validate the + post state. */ func (t *BlockTest) insertBlocks(blockchain *core.BlockChain) ([]btBlock, error) { validBlocks := make([]btBlock, 0) @@ -185,7 +188,7 @@ func (t *BlockTest) insertBlocks(blockchain *core.BlockChain) ([]btBlock, error) } } if b.BlockHeader == nil { - return nil, fmt.Errorf("Block insertion should have failed") + return nil, errors.New("Block insertion should have failed") } // validate RLP decoding by checking all values against test file JSON diff --git a/tests/init_test.go b/tests/init_test.go index 77a084d95ef7..53fe8b41201c 100644 --- a/tests/init_test.go +++ b/tests/init_test.go @@ -18,6 +18,7 @@ package tests import ( "encoding/json" + "errors" "fmt" "io" "os" @@ -169,7 +170,7 @@ func (tm *testMatcher) checkFailure(t *testing.T, name string, err error) error t.Logf("error: %v", err) return nil } else { - return fmt.Errorf("test succeeded unexpectedly") + return errors.New("test succeeded unexpectedly") } } return err diff --git a/tests/rlp_test_util.go b/tests/rlp_test_util.go index 9fb53097f38a..9315d8d8ba50 100644 --- a/tests/rlp_test_util.go +++ b/tests/rlp_test_util.go @@ -46,7 +46,7 @@ type RLPTest struct { func (t *RLPTest) Run() error { outb, err := hex.DecodeString(t.Out) if err != nil { - return fmt.Errorf("invalid hex in Out") + return errors.New("invalid hex in Out") } // Handle simple decoding tests with no actual In value. @@ -74,7 +74,7 @@ func checkDecodeInterface(b []byte, isValid bool) error { case isValid && err != nil: return fmt.Errorf("decoding failed: %v", err) case !isValid && err == nil: - return fmt.Errorf("decoding of invalid value succeeded") + return errors.New("decoding of invalid value succeeded") } return nil } diff --git a/tests/vm_test_util.go b/tests/vm_test_util.go index bd516a182721..b9bdffe48552 100644 --- a/tests/vm_test_util.go +++ b/tests/vm_test_util.go @@ -19,6 +19,7 @@ package tests import ( "bytes" "encoding/json" + "errors" "fmt" "math/big" @@ -85,10 +86,10 @@ func (t *VMTest) Run(vmconfig vm.Config) error { if t.json.GasRemaining == nil { if err == nil { - return fmt.Errorf("gas unspecified (indicating an error), but VM returned no error") + return errors.New("gas unspecified (indicating an error), but VM returned no error") } if gasRemaining > 0 { - return fmt.Errorf("gas unspecified (indicating an error), but VM returned gas remaining > 0") + return errors.New("gas unspecified (indicating an error), but VM returned gas remaining > 0") } return nil } diff --git a/trie/proof.go b/trie/proof.go index fff4142401ee..0db68c103c77 100644 --- a/trie/proof.go +++ b/trie/proof.go @@ -395,11 +395,11 @@ func hasRightElement(node Node, key []byte) bool { // Expect the normal case, this function can also be used to verify the following // range proofs(note this function doesn't accept zero element proof): // -// - All elements proof. In this case the left and right proof can be nil, but the -// range should be all the leaves in the trie. +// - All elements proof. In this case the left and right proof can be nil, but the +// range should be all the leaves in the trie. // -// - One element proof. In this case no matter the left edge proof is a non-existent -// proof or not, we can always verify the correctness of the proof. +// - One element proof. In this case no matter the left edge proof is a non-existent +// proof or not, we can always verify the correctness of the proof. // // Except returning the error to indicate the proof is valid or not, the function will // also return a flag to indicate whether there exists more accounts/slots in the trie. @@ -439,7 +439,7 @@ func VerifyRangeProof(rootHash common.Hash, firstKey []byte, keys [][]byte, valu return err, false } if !bytes.Equal(val, values[0]) { - return fmt.Errorf("correct proof but invalid data"), false + return errors.New("correct proof but invalid data"), false } return nil, hasRightElement(root, keys[0]) } diff --git a/trie/trie_test.go b/trie/trie_test.go index 89d47bf7dcac..202fc76d809e 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -19,6 +19,7 @@ package trie import ( "bytes" "encoding/binary" + "errors" "fmt" "math/big" "math/rand" @@ -446,7 +447,7 @@ func runRandTest(rt randTest) bool { checktr.Update(it.Key, it.Value) } if tr.Hash() != checktr.Hash() { - rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash") + rt[i].err = errors.New("hash mismatch in opItercheckhash") } } // Abort the test on error. diff --git a/whisper/whisperv5/api.go b/whisper/whisperv5/api.go index 37c04e70aada..b28ea5075d5d 100644 --- a/whisper/whisperv5/api.go +++ b/whisper/whisperv5/api.go @@ -471,7 +471,7 @@ func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) { f := api.w.GetFilter(id) if f == nil { api.mu.Unlock() - return nil, fmt.Errorf("filter not found") + return nil, errors.New("filter not found") } api.lastUsed[id] = time.Now() api.mu.Unlock() diff --git a/whisper/whisperv5/filter.go b/whisper/whisperv5/filter.go index d91e9747bf6d..5c64d46910d1 100644 --- a/whisper/whisperv5/filter.go +++ b/whisper/whisperv5/filter.go @@ -18,6 +18,7 @@ package whisperv5 import ( "crypto/ecdsa" + "errors" "fmt" "sync" @@ -66,7 +67,7 @@ func (fs *Filters) Install(watcher *Filter) (string, error) { defer fs.mutex.Unlock() if fs.watchers[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } if watcher.expectsSymmetricEncryption() { diff --git a/whisper/whisperv5/whisper.go b/whisper/whisperv5/whisper.go index 66901034f6ec..9bbb1cae01d0 100644 --- a/whisper/whisperv5/whisper.go +++ b/whisper/whisperv5/whisper.go @@ -247,7 +247,7 @@ func (w *Whisper) NewKeyPair() (string, error) { return "", err } if !validatePrivateKey(key) { - return "", fmt.Errorf("failed to generate valid key") + return "", errors.New("failed to generate valid key") } id, err := GenerateRandomID() @@ -259,7 +259,7 @@ func (w *Whisper) NewKeyPair() (string, error) { defer w.keyMu.Unlock() if w.privateKeys[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } w.privateKeys[id] = key return id, nil @@ -305,7 +305,7 @@ func (w *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) { defer w.keyMu.RUnlock() key := w.privateKeys[id] if key == nil { - return nil, fmt.Errorf("invalid id") + return nil, errors.New("invalid id") } return key, nil } @@ -318,7 +318,7 @@ func (w *Whisper) GenerateSymKey() (string, error) { if err != nil { return "", err } else if !validateSymmetricKey(key) { - return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data") + return "", errors.New("error in GenerateSymKey: crypto/rand failed to generate random data") } id, err := GenerateRandomID() @@ -330,7 +330,7 @@ func (w *Whisper) GenerateSymKey() (string, error) { defer w.keyMu.Unlock() if w.symKeys[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } w.symKeys[id] = key return id, nil @@ -351,7 +351,7 @@ func (w *Whisper) AddSymKeyDirect(key []byte) (string, error) { defer w.keyMu.Unlock() if w.symKeys[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } w.symKeys[id] = key return id, nil @@ -364,7 +364,7 @@ func (w *Whisper) AddSymKeyFromPassword(password string) (string, error) { return "", fmt.Errorf("failed to generate ID: %s", err) } if w.HasSymKey(id) { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } derived, err := deriveKeyMaterial([]byte(password), EnvelopeVersion) @@ -377,7 +377,7 @@ func (w *Whisper) AddSymKeyFromPassword(password string) (string, error) { // double check is necessary, because deriveKeyMaterial() is very slow if w.symKeys[id] != nil { - return "", fmt.Errorf("critical error: failed to generate unique ID") + return "", errors.New("critical error: failed to generate unique ID") } w.symKeys[id] = derived return id, nil @@ -409,7 +409,7 @@ func (w *Whisper) GetSymKey(id string) ([]byte, error) { if w.symKeys[id] != nil { return w.symKeys[id], nil } - return nil, fmt.Errorf("non-existent key ID") + return nil, errors.New("non-existent key ID") } // Subscribe installs a new message handler used for filtering, decrypting @@ -427,7 +427,7 @@ func (w *Whisper) GetFilter(id string) *Filter { func (w *Whisper) Unsubscribe(id string) error { ok := w.filters.Uninstall(id) if !ok { - return fmt.Errorf("Unsubscribe: Invalid ID") + return errors.New("Unsubscribe: Invalid ID") } return nil } @@ -440,7 +440,7 @@ func (w *Whisper) Send(envelope *Envelope) error { return err } if !ok { - return fmt.Errorf("failed to add envelope") + return errors.New("failed to add envelope") } return err } @@ -576,7 +576,7 @@ func (wh *Whisper) add(envelope *Envelope) (bool, error) { if envelope.Expiry < now { if envelope.Expiry+SynchAllowance*2 < now { - return false, fmt.Errorf("very old message") + return false, errors.New("very old message") } else { log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex()) return false, nil // drop envelope without error @@ -851,7 +851,7 @@ func GenerateRandomID() (id string, err error) { return "", err } if !validateSymmetricKey(buf) { - return "", fmt.Errorf("error in generateRandomID: crypto/rand failed to generate random data") + return "", errors.New("error in generateRandomID: crypto/rand failed to generate random data") } id = common.Bytes2Hex(buf) return id, err diff --git a/whisper/whisperv6/api.go b/whisper/whisperv6/api.go index 0ea7e0fc524b..8711d6b19538 100644 --- a/whisper/whisperv6/api.go +++ b/whisper/whisperv6/api.go @@ -490,7 +490,7 @@ func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) { f := api.w.GetFilter(id) if f == nil { api.mu.Unlock() - return nil, fmt.Errorf("filter not found") + return nil, errors.New("filter not found") } api.lastUsed[id] = time.Now() api.mu.Unlock() diff --git a/whisper/whisperv6/filter.go b/whisper/whisperv6/filter.go index aae1de848001..801954c7c309 100644 --- a/whisper/whisperv6/filter.go +++ b/whisper/whisperv6/filter.go @@ -18,6 +18,7 @@ package whisperv6 import ( "crypto/ecdsa" + "errors" "fmt" "sync" @@ -65,7 +66,7 @@ func NewFilters(w *Whisper) *Filters { // Install will add a new filter to the filter collection func (fs *Filters) Install(watcher *Filter) (string, error) { if watcher.KeySym != nil && watcher.KeyAsym != nil { - return "", fmt.Errorf("filters must choose between symmetric and asymmetric keys") + return "", errors.New("filters must choose between symmetric and asymmetric keys") } if watcher.Messages == nil { @@ -81,7 +82,7 @@ func (fs *Filters) Install(watcher *Filter) (string, error) { defer fs.mutex.Unlock() if fs.watchers[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } if watcher.expectsSymmetricEncryption() { diff --git a/whisper/whisperv6/whisper.go b/whisper/whisperv6/whisper.go index 53cf11a90973..0b83c89d13d0 100644 --- a/whisper/whisperv6/whisper.go +++ b/whisper/whisperv6/whisper.go @@ -379,7 +379,7 @@ func (whisper *Whisper) NewKeyPair() (string, error) { return "", err } if !validatePrivateKey(key) { - return "", fmt.Errorf("failed to generate valid key") + return "", errors.New("failed to generate valid key") } id, err := GenerateRandomID() @@ -391,7 +391,7 @@ func (whisper *Whisper) NewKeyPair() (string, error) { defer whisper.keyMu.Unlock() if whisper.privateKeys[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } whisper.privateKeys[id] = key return id, nil @@ -437,7 +437,7 @@ func (whisper *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) { defer whisper.keyMu.RUnlock() key := whisper.privateKeys[id] if key == nil { - return nil, fmt.Errorf("invalid id") + return nil, errors.New("invalid id") } return key, nil } @@ -449,7 +449,7 @@ func (whisper *Whisper) GenerateSymKey() (string, error) { if err != nil { return "", err } else if !validateDataIntegrity(key, aesKeyLength) { - return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data") + return "", errors.New("error in GenerateSymKey: crypto/rand failed to generate random data") } id, err := GenerateRandomID() @@ -461,7 +461,7 @@ func (whisper *Whisper) GenerateSymKey() (string, error) { defer whisper.keyMu.Unlock() if whisper.symKeys[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } whisper.symKeys[id] = key return id, nil @@ -482,7 +482,7 @@ func (whisper *Whisper) AddSymKeyDirect(key []byte) (string, error) { defer whisper.keyMu.Unlock() if whisper.symKeys[id] != nil { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } whisper.symKeys[id] = key return id, nil @@ -495,7 +495,7 @@ func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) { return "", fmt.Errorf("failed to generate ID: %s", err) } if whisper.HasSymKey(id) { - return "", fmt.Errorf("failed to generate unique ID") + return "", errors.New("failed to generate unique ID") } // kdf should run no less than 0.1 seconds on an average computer, @@ -510,7 +510,7 @@ func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) { // double check is necessary, because deriveKeyMaterial() is very slow if whisper.symKeys[id] != nil { - return "", fmt.Errorf("critical error: failed to generate unique ID") + return "", errors.New("critical error: failed to generate unique ID") } whisper.symKeys[id] = derived return id, nil @@ -542,7 +542,7 @@ func (whisper *Whisper) GetSymKey(id string) ([]byte, error) { if whisper.symKeys[id] != nil { return whisper.symKeys[id], nil } - return nil, fmt.Errorf("non-existent key ID") + return nil, errors.New("non-existent key ID") } // Subscribe installs a new message handler used for filtering, decrypting @@ -581,7 +581,7 @@ func (whisper *Whisper) GetFilter(id string) *Filter { func (whisper *Whisper) Unsubscribe(id string) error { ok := whisper.filters.Uninstall(id) if !ok { - return fmt.Errorf("Unsubscribe: Invalid ID") + return errors.New("Unsubscribe: Invalid ID") } return nil } @@ -591,7 +591,7 @@ func (whisper *Whisper) Unsubscribe(id string) error { func (whisper *Whisper) Send(envelope *Envelope) error { ok, err := whisper.add(envelope, false) if err == nil && !ok { - return fmt.Errorf("failed to add envelope") + return errors.New("failed to add envelope") } return err } @@ -762,7 +762,7 @@ func (whisper *Whisper) add(envelope *Envelope, isP2P bool) (bool, error) { if envelope.Expiry < now { if envelope.Expiry+DefaultSyncAllowance*2 < now { - return false, fmt.Errorf("very old message") + return false, errors.New("very old message") } log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex()) return false, nil // drop envelope without error @@ -1009,7 +1009,7 @@ func GenerateRandomID() (id string, err error) { return "", err } if !validateDataIntegrity(buf, keyIDSize) { - return "", fmt.Errorf("error in generateRandomID: crypto/rand failed to generate random data") + return "", errors.New("error in generateRandomID: crypto/rand failed to generate random data") } id = common.Bytes2Hex(buf) return id, err