all: use errrors.New instead of empty fmt.Errorf

This commit is contained in:
JukLee0ira 2024-06-14 16:36:55 +08:00
parent b718f3593c
commit 2d89951e5b
89 changed files with 358 additions and 317 deletions

View file

@ -1,7 +1,7 @@
package lendingstate package lendingstate
import ( import (
"fmt" "errors"
"math/big" "math/big"
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
@ -273,10 +273,10 @@ func GetAllLendingBooks(statedb *state.StateDB) (mapLendingBook map[common.Hash]
baseTokens := GetSupportedBaseToken(statedb) baseTokens := GetSupportedBaseToken(statedb)
terms := GetSupportedTerms(statedb) terms := GetSupportedTerms(statedb)
if len(baseTokens) == 0 { if len(baseTokens) == 0 {
return nil, fmt.Errorf("GetAllLendingBooks: empty baseToken list") return nil, errors.New("GetAllLendingBooks: empty baseToken list")
} }
if len(terms) == 0 { 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 _, baseToken := range baseTokens {
for _, term := range terms { for _, term := range terms {
@ -295,10 +295,10 @@ func GetAllLendingPairs(statedb *state.StateDB) (allPairs []LendingPair, err err
baseTokens := GetSupportedBaseToken(statedb) baseTokens := GetSupportedBaseToken(statedb)
collaterals := GetAllCollateral(statedb) collaterals := GetAllCollateral(statedb)
if len(baseTokens) == 0 { if len(baseTokens) == 0 {
return allPairs, fmt.Errorf("GetAllLendingPairs: empty baseToken list") return allPairs, errors.New("GetAllLendingPairs: empty baseToken list")
} }
if len(collaterals) == 0 { 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 _, baseToken := range baseTokens {
for _, collateral := range collaterals { for _, collateral := range collaterals {

View file

@ -1,6 +1,7 @@
package lendingstate package lendingstate
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
"strconv" "strconv"
@ -359,7 +360,7 @@ func (l *LendingItem) VerifyLendingSignature() error {
tx.ImportSignature(V, R, S) tx.ImportSignature(V, R, S)
from, _ := types.LendingSender(types.LendingTxSigner{}, tx) from, _ := types.LendingSender(types.LendingTxSigner{}, tx)
if from != tx.UserAddress() { if from != tx.UserAddress() {
return fmt.Errorf("verify lending item: invalid signature") return errors.New("verify lending item: invalid signature")
} }
return nil return nil
} }
@ -473,10 +474,10 @@ func VerifyBalance(isXDCXLendingFork bool, statedb *state.StateDB, lendingStateD
} }
return nil return nil
default: default:
return fmt.Errorf("VerifyBalance: unknown lending side") return errors.New("VerifyBalance: unknown lending side")
} }
default: default:
return fmt.Errorf("VerifyBalance: unknown lending type") return errors.New("VerifyBalance: unknown lending type")
} }
return nil return nil
} }

View file

@ -2,6 +2,7 @@ package XDCxlending
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math/big" "math/big"
@ -264,7 +265,7 @@ func (l *Lending) processOrderList(header *types.Header, coinbase common.Address
borrowFee = lendingstate.GetFee(statedb, oldestOrder.Relayer) borrowFee = lendingstate.GetFee(statedb, oldestOrder.Relayer)
} }
if collateralToken.IsZero() { 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) depositRate, liquidationRate, recallRate := lendingstate.GetCollateralDetail(statedb, collateralToken)
if depositRate == nil || depositRate.Sign() <= 0 { 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 return nil, nil, nil, err
} }
if lendTokenXDCPrice == nil || lendTokenXDCPrice.Sign() <= 0 { 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 { 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) 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 { if err != nil && err == lendingstate.ErrQuantityTradeTooSmall && tradedQuantity != nil && tradedQuantity.Sign() >= 0 {

View file

@ -79,19 +79,19 @@ func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
// Unpack output in v according to the abi specification // Unpack output in v according to the abi specification
func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) { func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) {
if len(output) == 0 { 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, // since there can't be naming collisions with contracts and events,
// we need to decide whether we're calling a method or an event // we need to decide whether we're calling a method or an event
if method, ok := abi.Methods[name]; ok { if method, ok := abi.Methods[name]; ok {
if len(output)%32 != 0 { 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) return method.Outputs.Unpack(v, output)
} else if event, ok := abi.Events[name]; ok { } else if event, ok := abi.Events[name]; ok {
return event.Inputs.Unpack(v, output) 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 // UnmarshalJSON implements json.Unmarshaler interface

View file

@ -335,7 +335,7 @@ func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log)
return errNoEventSignature return errNoEventSignature
} }
if log.Topics[0] != c.abi.Events[event].Id() { 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 len(log.Data) > 0 {
if err := c.abi.Unpack(out, event, log.Data); err != nil { if err := c.abi.Unpack(out, event, log.Data); err != nil {

View file

@ -18,7 +18,7 @@ package bind
import ( import (
"context" "context"
"fmt" "errors"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/common" "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. // 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) { func WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) (common.Address, error) {
if tx.To() != nil { 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) receipt, err := WaitMined(ctx, b, tx)
if err != nil { if err != nil {
return common.Address{}, err return common.Address{}, err
} }
if receipt.ContractAddress == (common.Address{}) { 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. // Check that code has indeed been deployed at the address.
// This matters on pre-Homestead chains: OOG in the constructor // This matters on pre-Homestead chains: OOG in the constructor

View file

@ -17,6 +17,7 @@
package abi package abi
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
) )
@ -117,7 +118,7 @@ func requireUniqueStructFieldNames(args Arguments) error {
for _, arg := range args { for _, arg := range args {
field := capitalise(arg.Name) field := capitalise(arg.Name)
if field == "" { 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] { if exists[field] {
return fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", field) return fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", field)

View file

@ -17,6 +17,7 @@
package abi package abi
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"regexp" "regexp"
@ -61,7 +62,7 @@ var (
func NewType(t string) (typ Type, err error) { func NewType(t string) (typ Type, err error) {
// check that array brackets are equal if they exist // check that array brackets are equal if they exist
if strings.Count(t, "[") != strings.Count(t, "]") { 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 typ.stringKind = t
@ -98,7 +99,7 @@ func NewType(t string) (typ Type, err error) {
} }
typ.Type = reflect.ArrayOf(typ.Size, embeddedType.Type) typ.Type = reflect.ArrayOf(typ.Size, embeddedType.Type)
} else { } else {
return Type{}, fmt.Errorf("invalid formatting of array type") return Type{}, errors.New("invalid formatting of array type")
} }
return typ, err return typ, err
} }

View file

@ -18,6 +18,7 @@ package abi
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"reflect" "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) // 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) { func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
if t.T != FunctionTy { 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 { if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
err = fmt.Errorf("abi: got improperly encoded function type, got %v", word) 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 // through reflection, creates a fixed array to be read from
func readFixedBytes(t Type, word []byte) (interface{}, error) { func readFixedBytes(t Type, word []byte) (interface{}, error) {
if t.T != FixedBytesTy { 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 // convert
array := reflect.New(t.Type).Elem() array := reflect.New(t.Type).Elem()
@ -123,7 +124,7 @@ func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error)
// declare our array // declare our array
refSlice = reflect.New(t.Type).Elem() refSlice = reflect.New(t.Type).Elem()
} else { } 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. // Arrays have packed elements, resulting in longer unpack steps.

View file

@ -17,6 +17,7 @@
package keystore package keystore
import ( import (
"errors"
"fmt" "fmt"
"math/rand" "math/rand"
"os" "os"
@ -305,7 +306,7 @@ func waitForAccounts(wantAccounts []accounts.Account, ks *KeyStore) error {
select { select {
case <-ks.changes: case <-ks.changes:
default: default:
return fmt.Errorf("wasn't notified of new accounts") return errors.New("wasn't notified of new accounts")
} }
return nil return nil
} }

View file

@ -24,7 +24,6 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
crand "crypto/rand" crand "crypto/rand"
"errors" "errors"
"fmt"
"math/big" "math/big"
"os" "os"
"path/filepath" "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) { func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
key := newKeyFromECDSA(priv) key := newKeyFromECDSA(priv)
if ks.cache.hasAddress(key.Address) { 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) return ks.importKey(key, passphrase)
} }

View file

@ -19,6 +19,7 @@ package bmt
import ( import (
"bytes" "bytes"
crand "crypto/rand" crand "crypto/rand"
"errors"
"fmt" "fmt"
"hash" "hash"
"io" "io"
@ -288,7 +289,7 @@ func TestHasherConcurrency(t *testing.T) {
var err error var err error
select { select {
case <-time.NewTimer(5 * time.Second).C: case <-time.NewTimer(5 * time.Second).C:
err = fmt.Errorf("timed out") err = errors.New("timed out")
case err = <-errc: case err = <-errc:
} }
if err != nil { if err != nil {
@ -321,7 +322,7 @@ func testHasherCorrectness(bmt hash.Hash, hasher BaseHasher, d []byte, n, count
}() }()
select { select {
case <-timeout.C: case <-timeout.C:
err = fmt.Errorf("BMT hash calculation timed out") err = errors.New("BMT hash calculation timed out")
case err = <-c: case err = <-c:
} }
return err return err

View file

@ -19,6 +19,7 @@ package utils
import ( import (
"compress/gzip" "compress/gzip"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -130,7 +131,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
for batch := 0; ; batch++ { for batch := 0; ; batch++ {
// Load a batch of RLP blocks. // Load a batch of RLP blocks.
if checkInterrupt() { if checkInterrupt() {
return fmt.Errorf("interrupted") return errors.New("interrupted")
} }
i := 0 i := 0
for ; i < importBatchSize; i++ { for ; i < importBatchSize; i++ {
@ -153,7 +154,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
} }
// Import the batch. // Import the batch.
if checkInterrupt() { if checkInterrupt() {
return fmt.Errorf("interrupted") return errors.New("interrupted")
} }
missing := missingBlocks(chain, blocks[:i]) missing := missingBlocks(chain, blocks[:i])
if len(missing) == 0 { if len(missing) == 0 {

View file

@ -1,7 +1,7 @@
package countdown package countdown
import ( import (
"fmt" "errors"
"testing" "testing"
"time" "time"
@ -76,7 +76,7 @@ func TestCountdownShouldResetEvenIfErrored(t *testing.T) {
called := make(chan int) called := make(chan int)
OnTimeoutFn := func(time.Time, interface{}) error { OnTimeoutFn := func(time.Time, interface{}) error {
called <- 1 called <- 1
return fmt.Errorf("ERROR!") return errors.New("ERROR!")
} }
countdown := NewCountDown(5000 * time.Millisecond) countdown := NewCountDown(5000 * time.Millisecond)

View file

@ -17,6 +17,7 @@
package XDPoS package XDPoS
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
@ -438,7 +439,7 @@ func (x *XDPoS) CalculateMissingRounds(chain consensus.ChainReader, header *type
case params.ConsensusEngineVersion2: case params.ConsensusEngineVersion2:
return x.EngineV2.CalculateMissingRounds(chain, header) return x.EngineV2.CalculateMissingRounds(chain, header)
default: // Default "v1" default: // Default "v1"
return nil, fmt.Errorf("Not supported in the v1 consensus") return nil, errors.New("Not supported in the v1 consensus")
} }
} }

View file

@ -686,7 +686,7 @@ func (x *XDPoS_v1) GetValidator(creator common.Address, chain consensus.ChainRea
if no%epoch == 0 { if no%epoch == 0 {
cpHeader = header cpHeader = header
} else { } 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()) m, err := getM1M2FromCheckpointHeader(cpHeader, header, chain.Config())

View file

@ -661,7 +661,7 @@ func (x *XDPoS_v2) VerifyTimeoutMessage(chain consensus.ChainReader, timeoutMsg
} }
if len(snap.NextEpochCandidates) == 0 { if len(snap.NextEpochCandidates) == 0 {
log.Error("[VerifyTimeoutMessage] cannot find NextEpochCandidates from snapshot", "messageGapNumber", timeoutMsg.GapNumber) 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{ 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 present, then its value shall consistent with what's provided in the blockInfo
if blockHeader.Hash() != blockInfo.Hash { if blockHeader.Hash() != blockInfo.Hash {
log.Warn("[VerifyBlockInfo] BlockHeader and blockInfo mismatch", "BlockInfoHash", blockInfo.Hash.Hex(), "BlockHeaderHash", blockHeader.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.Number.Cmp(x.config.V2.SwitchBlock) == 0 {
if blockInfo.Round != 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) 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 return nil
} }
@ -789,7 +789,7 @@ func (x *XDPoS_v2) verifyQC(blockChainReader consensus.ChainReader, quorumCert *
epochInfo, err := x.getEpochSwitchInfo(blockChainReader, parentHeader, quorumCert.ProposedBlockInfo.Hash) epochInfo, err := x.getEpochSwitchInfo(blockChainReader, parentHeader, quorumCert.ProposedBlockInfo.Hash)
if err != nil { if err != nil {
log.Error("[verifyQC] Error when getting epoch switch Info to verify QC", "Error", err) 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) signatures, duplicates := UniqueSignatures(quorumCert.Signatures)
@ -821,12 +821,12 @@ func (x *XDPoS_v2) verifyQC(blockChainReader consensus.ChainReader, quorumCert *
}), sig, epochInfo.Masternodes) }), sig, epochInfo.Masternodes)
if err != nil { if err != nil {
log.Error("[verifyQC] Error while verfying QC message signatures", "Error", err) 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 return
} }
if !verified { if !verified {
log.Warn("[verifyQC] Signature not verified doing QC verification", "QC", quorumCert) 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 return
} }
}(signature) }(signature)

View file

@ -2,6 +2,7 @@ package engine_v2
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"reflect" "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. // 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 { if len(headers) != NUM_OF_FORENSICS_QC-1 {
log.Error("[SetCommittedQcs] Received input length not equal to 2", len(headers)) 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 var committedQCs []types.QuorumCert
@ -64,11 +65,11 @@ func (f *Forensics) SetCommittedQCs(headers []types.Header, incomingQC types.Quo
if i != 0 { if i != 0 {
if decodedExtraField.QuorumCert.ProposedBlockInfo.Hash != headers[i-1].Hash() { 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()) 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 } else if i == len(headers)-1 { // The last header shall be pointed by the incoming QC
if incomingQC.ProposedBlockInfo.Hash != h.Hash() { 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()) 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 highestCommittedQCs := f.HighestCommittedQCs
if len(highestCommittedQCs) != NUM_OF_FORENSICS_QC { 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) 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) // 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) incomingQuorunCerts, err := f.findAncestorQCs(chain, incomingQC, 2)
@ -163,7 +164,7 @@ func (f *Forensics) SendForensicProof(chain consensus.ChainReader, engine *XDPoS
if ancestorBlock == nil { if ancestorBlock == nil {
log.Error("[SendForensicProof] Unable to find the ancestor block by its hash", "Hash", ancestorHash) 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{ content, err := json.Marshal(&types.ForensicsContent{
@ -209,7 +210,7 @@ func (f *Forensics) findAncestorQCs(chain consensus.ChainReader, currentQc types
parentHeader := chain.GetHeaderByHash(parentHash) parentHeader := chain.GetHeaderByHash(parentHash)
if parentHeader == nil { if parentHeader == nil {
log.Error("[findAncestorQCs] Forensics findAncestorQCs unable to find its parent block header", "BlockNum", parentHeader.Number.Int64(), "ParentHash", parentHash.Hex()) 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 var decodedExtraField types.ExtraFields_v2
err := utils.DecodeBytesExtraFields(parentHeader.Extra, &decodedExtraField) err := utils.DecodeBytesExtraFields(parentHeader.Extra, &decodedExtraField)
@ -318,7 +319,7 @@ func (f *Forensics) findAncestorQcThroughRound(chain consensus.ChainReader, high
} }
ancestorQC = *decodedExtraField.QuorumCert 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) { 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 highestCommittedQCs := f.HighestCommittedQCs
if len(highestCommittedQCs) != NUM_OF_FORENSICS_QC { 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) 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 { if incomingVote.ProposedBlockInfo.Round < highestCommittedQCs[NUM_OF_FORENSICS_QC-1].ProposedBlockInfo.Round {
log.Debug("Received a too old vote in forensics", "vote", incomingVote) log.Debug("Received a too old vote in forensics", "vote", incomingVote)

View file

@ -1,6 +1,7 @@
package engine_v2 package engine_v2
import ( import (
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -99,7 +100,7 @@ func (x *XDPoS_v2) verifyTC(chain consensus.ChainReader, timeoutCert *types.Time
} }
if snap == nil || len(snap.NextEpochCandidates) == 0 { if snap == nil || len(snap.NextEpochCandidates) == 0 {
log.Error("[verifyTC] Something wrong with the snapshot from gapNumber", "messageGapNumber", timeoutCert.GapNumber, "snapshot", snap) 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) 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) haveError = fmt.Errorf("error while verifying TC message signatures, %s", err)
} else { } else {
log.Warn("[verifyTC] Signature not verified doing TC verification", "timeoutCert.Round", timeoutCert.Round, "timeoutCert.GapNumber", timeoutCert.GapNumber, "Signatures len", len(signatures)) 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 mutex.Unlock() // Unlock after modifying haveError

View file

@ -1,6 +1,7 @@
package engine_v2 package engine_v2
import ( import (
"errors"
"fmt" "fmt"
"github.com/XinFinOrg/XDPoSChain/accounts" "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) { func (x *XDPoS_v2) verifyMsgSignature(signedHashToBeVerified common.Hash, signature types.Signature, masternodes []common.Address) (bool, common.Address, error) {
var signerAddress common.Address var signerAddress common.Address
if len(masternodes) == 0 { 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 // Recover the public key and the Ethereum address
pubkey, err := crypto.Ecrecover(signedHashToBeVerified.Bytes(), signature) pubkey, err := crypto.Ecrecover(signedHashToBeVerified.Bytes(), signature)

View file

@ -1,6 +1,7 @@
package engine_v2 package engine_v2
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
"strconv" "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()) epochInfo, err := x.getEpochSwitchInfo(chain, chain.CurrentHeader(), chain.CurrentHeader().Hash())
if err != nil { if err != nil {
log.Error("[voteHandler] Error when getting epoch switch Info", "error", err) 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 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()) epochInfo, err := x.getEpochSwitchInfo(chain, chain.CurrentHeader(), chain.CurrentHeader().Hash())
if err != nil { if err != nil {
log.Error("[voteHandler] Error when getting epoch switch Info", "error", err) 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 // Skip and wait for the next vote to process again if valid votes is less than what we required

View file

@ -2,6 +2,7 @@ package utils
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sort" "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) // Decode extra fields for consensus version >= 2 (XDPoS 2.0 and future versions)
func DecodeBytesExtraFields(b []byte, val interface{}) error { func DecodeBytesExtraFields(b []byte, val interface{}) error {
if len(b) == 0 { if len(b) == 0 {
return fmt.Errorf("extra field is 0 length") return errors.New("extra field is 0 length")
} }
switch b[0] { switch b[0] {
case 2: case 2:

View file

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"math/rand" "math/rand"
@ -178,7 +179,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err
amountInt := new(big.Int) amountInt := new(big.Int)
amount, ok := amountInt.SetString("60000", 10) amount, ok := amountInt.SetString("60000", 10)
if !ok { if !ok {
return nil, fmt.Errorf("big int init failed") return nil, errors.New("big int init failed")
} }
to := common.MasternodeVotingSMCBinary to := common.MasternodeVotingSMCBinary
tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) 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 // 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()) sighash, err := signFn(accounts.Account{Address: signer}, blockchain.Engine().(*XDPoS.XDPoS).SigHash(header).Bytes())
if err != nil { 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) copy(header.Extra[len(header.Extra)-utils.ExtraSeal:], sighash)
} }

View file

@ -5,6 +5,7 @@ import (
"context" "context"
"crypto/ecdsa" "crypto/ecdsa"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"math/rand" "math/rand"
@ -103,7 +104,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err
amountInt := new(big.Int) amountInt := new(big.Int)
amount, ok := amountInt.SetString("60000", 10) amount, ok := amountInt.SetString("60000", 10)
if !ok { if !ok {
return nil, fmt.Errorf("big int init failed") return nil, errors.New("big int init failed")
} }
to := common.MasternodeVotingSMCBinary to := common.MasternodeVotingSMCBinary
tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) 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 // 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()) sighash, err := signFn(accounts.Account{Address: signer}, blockchain.Engine().(*XDPoS.XDPoS).SigHash(header).Bytes())
if err != nil { 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) 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 var decodedExtraField types.ExtraFields_v2
err := utils.DecodeBytesExtraFields(header.Extra, &decodedExtraField) err := utils.DecodeBytesExtraFields(header.Extra, &decodedExtraField)
if err != nil { 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 round := decodedExtraField.Round
masterNodes := getMasternodesList(signer) masterNodes := getMasternodesList(signer)
@ -757,7 +758,7 @@ func findSignerAndSignFn(bc *BlockChain, header *types.Header, signer common.Add
} }
addressedSignFn = signFn addressedSignFn = signFn
if err != nil { 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"))
} }
} }

View file

@ -18,6 +18,7 @@ package console
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"reflect" "reflect"
@ -75,18 +76,18 @@ func (b *bridge) NewAccount(call jsre.Call) (goja.Value, error) {
return nil, err return nil, err
} }
if password != confirm { 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 // A single string password was specified, use that
case len(call.Arguments) == 1 && call.Argument(0).ToString() != nil: case len(call.Arguments) == 1 && call.Argument(0).ToString() != nil:
password = call.Argument(0).ToString().String() password = call.Argument(0).ToString().String()
default: 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 // Password acquired, execute the call and return
newAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("newAccount")) newAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("newAccount"))
if !callable { 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)) ret, err := newAccount(goja.Null(), call.VM.ToValue(password))
if err != nil { 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) { func (b *bridge) OpenWallet(call jsre.Call) (goja.Value, error) {
// Make sure we have a wallet specified to open // Make sure we have a wallet specified to open
if call.Argument(0).ToObject(call.VM).ClassName() != "String" { 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) 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 // Open the wallet and return if successful in itself
openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet")) openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet"))
if !callable { 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) val, err := openWallet(goja.Null(), wallet, passwd)
if err == nil { 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")) openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet"))
if !callable { 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)) 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")) openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet"))
if !callable { 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)) 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) { func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) {
// Make sure we have an account specified to unlock. // Make sure we have an account specified to unlock.
if call.Argument(0).ExportType().Kind() != reflect.String { 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) account := call.Argument(0)
@ -195,7 +196,7 @@ func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) {
passwd = call.VM.ToValue(input) passwd = call.VM.ToValue(input)
} else { } else {
if call.Argument(1).ExportType().Kind() != reflect.String { 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) passwd = call.Argument(1)
} }
@ -204,7 +205,7 @@ func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) {
duration := goja.Null() duration := goja.Null()
if !goja.IsUndefined(call.Argument(2)) && !goja.IsNull(call.Argument(2)) { if !goja.IsUndefined(call.Argument(2)) && !goja.IsNull(call.Argument(2)) {
if !isNumber(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) 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. // Send the request to the backend and return.
unlockAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount")) unlockAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount"))
if !callable { 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) 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 { 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 { 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 // 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) passwd = call.VM.ToValue(input)
} else if passwd.ExportType().Kind() != reflect.String { } 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 // Send the request to the backend and return
sign, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount")) sign, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount"))
if !callable { 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) 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. // Sleep will block the console for the specified number of seconds.
func (b *bridge) Sleep(call jsre.Call) (goja.Value, error) { func (b *bridge) Sleep(call jsre.Call) (goja.Value, error) {
if !isNumber(call.Argument(0)) { if !isNumber(call.Argument(0)) {
return nil, fmt.Errorf("usage: sleep(<number of seconds>)") return nil, errors.New("usage: sleep(<number of seconds>)")
} }
sleep := call.Argument(0).ToFloat() sleep := call.Argument(0).ToFloat()
time.Sleep(time.Duration(sleep * float64(time.Second))) 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) nArgs := len(call.Arguments)
if nArgs == 0 { if nArgs == 0 {
return nil, fmt.Errorf("usage: sleepBlocks(<n blocks>[, max sleep in seconds])") return nil, errors.New("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
} }
if nArgs >= 1 { if nArgs >= 1 {
if !isNumber(call.Argument(0)) { 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() blocks = call.Argument(0).ToInteger()
} }
if nArgs >= 2 { if nArgs >= 2 {
if isNumber(call.Argument(1)) { 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() 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) JSON := call.VM.Get("JSON").ToObject(call.VM)
parse, callable := goja.AssertFunction(JSON.Get("parse")) parse, callable := goja.AssertFunction(JSON.Get("parse"))
if !callable { 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))) resultVal, err := parse(goja.Null(), call.VM.ToValue(string(result)))
if err != nil { if err != nil {

View file

@ -29,6 +29,7 @@ import (
"context" "context"
"crypto/ecdsa" "crypto/ecdsa"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"os" "os"
@ -446,7 +447,7 @@ type Inbox struct {
// from blockchain when first cheque is received. // 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) { func NewInbox(prvKey *ecdsa.PrivateKey, contractAddr, beneficiary common.Address, signer *ecdsa.PublicKey, abigen bind.ContractBackend) (self *Inbox, err error) {
if signer == nil { if signer == nil {
return nil, fmt.Errorf("signer is null") return nil, errors.New("signer is null")
} }
chbook, err := contract.NewChequebook(contractAddr, abigen) chbook, err := contract.NewChequebook(contractAddr, abigen)
if err != nil { 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) { 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) log.Trace("Verifying chequebook cheque", "cheque", self, "sum", sum)
if sum == nil { if sum == nil {
return nil, fmt.Errorf("invalid amount") return nil, errors.New("invalid amount")
} }
if self.Beneficiary != beneficiary { if self.Beneficiary != beneficiary {

View file

@ -17,6 +17,7 @@
package core package core
import ( import (
"errors"
"fmt" "fmt"
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
@ -113,7 +114,7 @@ func (v *BlockValidator) ValidateTradingOrder(statedb *state.StateDB, XDCxStated
} }
XDCXService := XDPoSEngine.GetXDCXService() XDCXService := XDPoSEngine.GetXDCXService()
if XDCXService == nil { 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)) log.Debug("verify matching transaction found a TxMatches Batch", "numTxMatches", len(txMatchBatch.Data))
tradingResult := map[common.Hash]tradingstate.MatchingResult{} tradingResult := map[common.Hash]tradingstate.MatchingResult{}
@ -149,11 +150,11 @@ func (v *BlockValidator) ValidateLendingOrder(statedb *state.StateDB, lendingSta
} }
XDCXService := XDPoSEngine.GetXDCXService() XDCXService := XDPoSEngine.GetXDCXService()
if XDCXService == nil { if XDCXService == nil {
return fmt.Errorf("XDCx not found") return errors.New("XDCx not found")
} }
lendingService := XDPoSEngine.GetLendingService() lendingService := XDPoSEngine.GetLendingService()
if lendingService == nil { if lendingService == nil {
return fmt.Errorf("lendingService not found") return errors.New("lendingService not found")
} }
log.Debug("verify lendingItem ", "numItems", len(batch.Data)) log.Debug("verify lendingItem ", "numItems", len(batch.Data))
lendingResult := map[common.Hash]lendingstate.MatchingResult{} lendingResult := map[common.Hash]lendingstate.MatchingResult{}

View file

@ -2197,10 +2197,10 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
} }
} }
if oldBlock == nil { if oldBlock == nil {
return fmt.Errorf("Invalid old chain") return errors.New("Invalid old chain")
} }
if newBlock == nil { if newBlock == nil {
return fmt.Errorf("Invalid new chain") return errors.New("Invalid new chain")
} }
for { 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) oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
if oldBlock == nil { if oldBlock == nil {
return fmt.Errorf("Invalid old chain") return errors.New("Invalid old chain")
} }
if newBlock == nil { if newBlock == nil {
return fmt.Errorf("Invalid new chain") return errors.New("Invalid new chain")
} }
} }
// Ensure XDPoS engine committed block will be not reverted // Ensure XDPoS engine committed block will be not reverted

View file

@ -18,6 +18,7 @@ package core
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"sync" "sync"
"sync/atomic" "sync/atomic"
@ -357,7 +358,7 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com
if header == nil { if header == nil {
return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4]) return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4])
} else if header.ParentHash != lastHead { } 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) c.backend.Process(header)
lastHead = header.Hash() lastHead = header.Hash()

View file

@ -141,10 +141,10 @@ func (e *GenesisMismatchError) Error() string {
// SetupGenesisBlock writes or updates the genesis block in db. // SetupGenesisBlock writes or updates the genesis block in db.
// The block that will be used is: // The block that will be used is:
// //
// genesis == nil genesis != nil // genesis == nil genesis != nil
// +------------------------------------------ // +------------------------------------------
// db has no genesis | main-net default | genesis // db has no genesis | main-net default | genesis
// db has genesis | from DB | genesis (if compatible) // db has genesis | from DB | genesis (if compatible)
// //
// The stored chain configuration will be updated if it is compatible (i.e. does not // 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 // 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. // are returned to the caller unless we're already at block zero.
height := GetBlockNumber(db, GetHeadHeaderHash(db)) height := GetBlockNumber(db, GetHeadHeaderHash(db))
if height == missingNumber { 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) compatErr := storedcfg.CheckCompatible(newcfg, height)
if compatErr != nil && height != 0 && compatErr.RewindTo != 0 { 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) { func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
block := g.ToBlock(db) block := g.ToBlock(db)
if block.Number().Sign() != 0 { 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 { if err := WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty); err != nil {
return nil, err return nil, err

View file

@ -519,7 +519,7 @@ func (pool *LendingPool) validateBalance(cloneStateDb *state.StateDB, cloneLendi
XDCXServ := XDPoSEngine.GetXDCXService() XDCXServ := XDPoSEngine.GetXDCXService()
lendingServ := XDPoSEngine.GetLendingService() lendingServ := XDPoSEngine.GetLendingService()
if XDCXServ == nil { 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()) lendingTokenDecimal, err := XDCXServ.GetTokenDecimal(pool.chain, cloneStateDb, tx.LendingToken())
if err != nil { if err != nil {

View file

@ -468,7 +468,7 @@ func (pool *OrderPool) validateOrder(tx *types.OrderTransaction) error {
} }
XDCXServ := XDPoSEngine.GetXDCXService() XDCXServ := XDPoSEngine.GetXDCXService()
if XDCXServ == nil { 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()) baseDecimal, err := XDCXServ.GetTokenDecimal(pool.chain, cloneStateDb, tx.BaseToken())
if err != nil { if err != nil {

View file

@ -1,6 +1,7 @@
package types package types
import ( import (
"errors"
"fmt" "fmt"
"math/big" "math/big"
"reflect" "reflect"
@ -15,11 +16,11 @@ import (
// Decode extra fields for consensus version >= 2 (XDPoS 2.0 and future versions) // Decode extra fields for consensus version >= 2 (XDPoS 2.0 and future versions)
func DecodeBytesExtraFields(b []byte, val interface{}) error { func DecodeBytesExtraFields(b []byte, val interface{}) error {
if len(b) == 0 { if len(b) == 0 {
return fmt.Errorf("extra field is 0 length") return errors.New("extra field is 0 length")
} }
switch b[0] { switch b[0] {
case 1: 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: case 2:
return rlp.DecodeBytes(b[1:], val) return rlp.DecodeBytes(b[1:], val)
default: default:

View file

@ -18,7 +18,7 @@ package types
import ( import (
"encoding/json" "encoding/json"
"fmt" "errors"
"reflect" "reflect"
"testing" "testing"
@ -97,7 +97,7 @@ var unmarshalLogTests = map[string]struct {
}, },
"missing data": { "missing data": {
input: `{"address":"0xecf8f87f810ecf450940c9f60066b4a7a501d6a7","blockHash":"0x656c34545f90a730a19008c0e7a7cd4fb3895064b48d6d69761bd5abad681056","blockNumber":"0x1ecfa4","logIndex":"0x2","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef","0x00000000000000000000000080b2c9d7cbbf30a1b0fc8983c647d754c6525615","0x000000000000000000000000f9dff387dcb5cc4cca5b91adb07a95f54e9f1bb6"],"transactionHash":"0x3b198bfd5d2907285af009e9ae84a0ecd63677110d89d7e030251acb87f6487e","transactionIndex":"0x3"}`, 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"),
}, },
} }

View file

@ -540,7 +540,7 @@ func assertEqual(orig *Transaction, cpy *Transaction) error {
} }
if orig.AccessList() != nil { if orig.AccessList() != nil {
if !reflect.DeepEqual(orig.AccessList(), cpy.AccessList()) { if !reflect.DeepEqual(orig.AccessList(), cpy.AccessList()) {
return fmt.Errorf("access list wrong!") return errors.New("access list wrong!")
} }
} }
return nil return nil

View file

@ -142,11 +142,11 @@ func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
// The priv.D must < N // The priv.D must < N
if priv.D.Cmp(secp256k1N) >= 0 { 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. // The priv.D must not be zero or negative.
if priv.D.Sign() <= 0 { 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) 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 { if err != nil {
return nil, err return nil, err
} else if n != len(buf) { } 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 { if err := checkKeyFileEnd(r); err != nil {
return nil, err return nil, err

View file

@ -35,6 +35,7 @@ import (
"crypto/elliptic" "crypto/elliptic"
"crypto/hmac" "crypto/hmac"
"crypto/subtle" "crypto/subtle"
"errors"
"fmt" "fmt"
"hash" "hash"
"io" "io"
@ -42,12 +43,12 @@ import (
) )
var ( var (
ErrImport = fmt.Errorf("ecies: failed to import key") ErrImport = errors.New("ecies: failed to import key")
ErrInvalidCurve = fmt.Errorf("ecies: invalid elliptic curve") ErrInvalidCurve = errors.New("ecies: invalid elliptic curve")
ErrInvalidParams = fmt.Errorf("ecies: invalid ECIES parameters") ErrInvalidParams = errors.New("ecies: invalid ECIES parameters")
ErrInvalidPublicKey = fmt.Errorf("ecies: invalid public key") ErrInvalidPublicKey = errors.New("ecies: invalid public key")
ErrSharedKeyIsPointAtInfinity = fmt.Errorf("ecies: shared key is point at infinity") ErrSharedKeyIsPointAtInfinity = errors.New("ecies: shared key is point at infinity")
ErrSharedKeyTooBig = fmt.Errorf("ecies: shared key params are too big") ErrSharedKeyTooBig = errors.New("ecies: shared key params are too big")
) )
// PublicKey is a representation of an elliptic curve public key. // 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 ( var (
ErrKeyDataTooLong = fmt.Errorf("ecies: can't supply requested key data") ErrKeyDataTooLong = errors.New("ecies: can't supply requested key data")
ErrSharedTooLong = fmt.Errorf("ecies: shared secret is too long") ErrSharedTooLong = errors.New("ecies: shared secret is too long")
ErrInvalidMessage = fmt.Errorf("ecies: invalid message") ErrInvalidMessage = errors.New("ecies: invalid message")
) )
var ( var (

View file

@ -35,6 +35,7 @@ import (
"crypto/rand" "crypto/rand"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"testing" "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 // cmpParams compares a set of ECIES parameters. We assume, as per the
// docs, that AES is the only supported symmetric encryption algorithm. // docs, that AES is the only supported symmetric encryption algorithm.

View file

@ -39,7 +39,7 @@ import (
"crypto/elliptic" "crypto/elliptic"
"crypto/sha256" "crypto/sha256"
"crypto/sha512" "crypto/sha512"
"fmt" "errors"
"hash" "hash"
ethcrypto "github.com/XinFinOrg/XDPoSChain/crypto" ethcrypto "github.com/XinFinOrg/XDPoSChain/crypto"
@ -47,8 +47,8 @@ import (
var ( var (
DefaultCurve = ethcrypto.S256() DefaultCurve = ethcrypto.S256()
ErrUnsupportedECDHAlgorithm = fmt.Errorf("ecies: unsupported ECDH algorithm") ErrUnsupportedECDHAlgorithm = errors.New("ecies: unsupported ECDH algorithm")
ErrUnsupportedECIESParameters = fmt.Errorf("ecies: unsupported ECIES parameters") ErrUnsupportedECIESParameters = errors.New("ecies: unsupported ECIES parameters")
) )
type ECIESParams struct { type ECIESParams struct {

View file

@ -447,7 +447,7 @@ func (s *Ethereum) Etherbase() (eb common.Address, err error) {
return etherbase, nil 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 // 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 return false, nil
} }
} else { } 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 return true, nil
} }
@ -487,7 +487,7 @@ func (s *Ethereum) ValidateMasternodeTestnet() (bool, error) {
return false, err return false, err
} }
if s.chainConfig.XDPoS == nil { 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{ masternodes := []common.Address{
common.HexToAddress("0x3Ea0A3555f9B1dE983572BfF6444aeb1899eC58C"), common.HexToAddress("0x3Ea0A3555f9B1dE983572BfF6444aeb1899eC58C"),

View file

@ -1,7 +1,7 @@
package bft package bft
import ( import (
"fmt" "errors"
"math/big" "math/big"
"sync/atomic" "sync/atomic"
"testing" "testing"
@ -102,7 +102,7 @@ func TestNotBoardcastInvalidVote(t *testing.T) {
targetVotes := 0 targetVotes := 0
tester.bfter.consensus.verifyVote = func(chain consensus.ChainReader, vote *types.Vote) (bool, error) { 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 { tester.bfter.consensus.voteHandler = func(chain consensus.ChainReader, vote *types.Vote) error {

View file

@ -387,7 +387,7 @@ func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*ty
api.filtersMu.Unlock() api.filtersMu.Unlock()
if !found || f.typ != LogsSubscription { if !found || f.typ != LogsSubscription {
return nil, fmt.Errorf("filter not found") return nil, errors.New("filter not found")
} }
var filter *Filter 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, // 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.BlockHash != nil {
if raw.FromBlock != nil || raw.ToBlock != nil { if raw.FromBlock != nil || raw.ToBlock != nil {
// BlockHash is mutually exclusive with FromBlock/ToBlock criteria // 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 args.BlockHash = raw.BlockHash
} else { } else {
@ -558,11 +558,11 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error {
} }
args.Topics[i] = append(args.Topics[i], parsed) args.Topics[i] = append(args.Topics[i], parsed)
} else { } else {
return fmt.Errorf("invalid topic(s)") return errors.New("invalid topic(s)")
} }
} }
default: default:
return fmt.Errorf("invalid topic(s)") return errors.New("invalid topic(s)")
} }
} }
} }

View file

@ -21,7 +21,6 @@ package filters
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"sync" "sync"
"time" "time"
@ -227,7 +226,7 @@ func (es *EventSystem) SubscribeLogs(crit ethereum.FilterQuery, logs chan []*typ
if from >= 0 && to == rpc.LatestBlockNumber { if from >= 0 && to == rpc.LatestBlockNumber {
return es.subscribeLogs(crit, logs), nil 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 // subscribeMinedPendingLogs creates a subscription that returned mined and

View file

@ -2,7 +2,6 @@ package hooks
import ( import (
"errors" "errors"
"fmt"
"math/big" "math/big"
"time" "time"
@ -41,7 +40,7 @@ func AttachConsensusV2Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf
if timeout > 30 { // wait over 30s if timeout > 30 { // wait over 30s
log.Error("[V2 Hook Penalty] parentHeader is nil, wait too long not writen in to disk", "parentNumber", parentNumber) 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")
} }
} }

View file

@ -427,17 +427,17 @@ func New(code string) (*Tracer, error) {
tracer.tracerObject = 0 // yeah, nice, eval can't return the index itself tracer.tracerObject = 0 // yeah, nice, eval can't return the index itself
if !tracer.vm.GetPropString(tracer.tracerObject, "step") { 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() tracer.vm.Pop()
if !tracer.vm.GetPropString(tracer.tracerObject, "fault") { 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() tracer.vm.Pop()
if !tracer.vm.GetPropString(tracer.tracerObject, "result") { 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() tracer.vm.Pop()
@ -548,7 +548,6 @@ func (jst *Tracer) CaptureStart(env *vm.EVM, from common.Address, to common.Addr
jst.ctx["intrinsicGas"] = intrinsicGas jst.ctx["intrinsicGas"] = intrinsicGas
} }
// CaptureState implements the Tracer interface to trace a single step of VM execution. // 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) { 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 { 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 // 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) { 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 { if jst.err != nil {

View file

@ -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. // Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 { 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 { 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 { 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 { 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. // Load uncles because they are not included in the block response.
var uncles []*types.Header var uncles []*types.Header
@ -197,7 +197,7 @@ func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *
} else if json == nil { } else if json == nil {
return nil, false, ethereum.NotFound return nil, false, ethereum.NotFound
} else if _, r, _ := json.tx.RawSignatureValues(); r == nil { } 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) setSenderFromServer(json.tx, json.From, json.BlockHash)
return json.tx, json.BlockNumber == nil, nil return json.tx, json.BlockNumber == nil, nil
@ -243,7 +243,7 @@ func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash,
if json == nil { if json == nil {
return nil, ethereum.NotFound return nil, ethereum.NotFound
} else if _, r, _ := json.tx.RawSignatureValues(); r == nil { } 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) setSenderFromServer(json.tx, json.From, json.BlockHash)

View file

@ -17,6 +17,7 @@
package event package event
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sync" "sync"
@ -68,7 +69,7 @@ func checkPanic(want error, fn func()) (err error) {
defer func() { defer func() {
panic := recover() panic := recover()
if panic == nil { if panic == nil {
err = fmt.Errorf("didn't panic") err = errors.New("didn't panic")
} else if !reflect.DeepEqual(panic, want) { } else if !reflect.DeepEqual(panic, want) {
err = fmt.Errorf("panicked with wrong error: got %q, want %q", panic, want) err = fmt.Errorf("panicked with wrong error: got %q, want %q", panic, want)
} }

View file

@ -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 // 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 // tx into the transaction pool, but right back to the user
if args.Gas == nil { if args.Gas == nil {
return nil, fmt.Errorf("gas not specified") return nil, errors.New("gas not specified")
} }
if args.GasPrice == nil { if args.GasPrice == nil {
return nil, fmt.Errorf("gasPrice not specified") return nil, errors.New("gasPrice not specified")
} }
if args.Nonce == nil { 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) signed, err := s.signTransaction(ctx, args, passwd)
if err != nil { 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) return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
} }
if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 { 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 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 maxMasternodes = s.b.ChainConfig().XDPoS.V2.Config(uint64(round)).MaxMasternodes
} else { } 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()) { } else if s.b.ChainConfig().IsTIPIncreaseMasternodes(block.Number()) {
maxMasternodes = common.MaxMasternodesV2 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 maxMasternodes = s.b.ChainConfig().XDPoS.V2.Config(uint64(round)).MaxMasternodes
} else { } 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()) { } else if s.b.ChainConfig().IsTIPIncreaseMasternodes(block.Number()) {
maxMasternodes = common.MaxMasternodesV2 maxMasternodes = common.MaxMasternodesV2
@ -3348,13 +3348,13 @@ type SignTransactionResult struct {
// the given from address and it needs to be unlocked. // the given from address and it needs to be unlocked.
func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) { func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
if args.Gas == nil { if args.Gas == nil {
return nil, fmt.Errorf("gas not specified") return nil, errors.New("gas not specified")
} }
if args.GasPrice == nil { if args.GasPrice == nil {
return nil, fmt.Errorf("gasPrice not specified") return nil, errors.New("gasPrice not specified")
} }
if args.Nonce == nil { 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 { if err := args.setDefaults(ctx, s.b); err != nil {
return nil, err 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. // 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) { func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
if sendArgs.Nonce == nil { 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 { if err := sendArgs.setDefaults(ctx, s.b); err != nil {
return common.Hash{}, err return common.Hash{}, err
@ -3494,7 +3494,7 @@ func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
LDB() *leveldb.DB LDB() *leveldb.DB
}) })
if !ok { if !ok {
return "", fmt.Errorf("chaindbProperty does not work for memory databases") return "", errors.New("chaindbProperty does not work for memory databases")
} }
if property == "" { if property == "" {
property = "leveldb.stats" property = "leveldb.stats"
@ -3509,7 +3509,7 @@ func (api *PrivateDebugAPI) ChaindbCompact() error {
LDB() *leveldb.DB LDB() *leveldb.DB
}) })
if !ok { 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++ { for b := byte(0); b < 255; b++ {
log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))

View file

@ -2,7 +2,7 @@ package ethapi
import ( import (
"bytes" "bytes"
"fmt" "errors"
"math/big" "math/big"
"reflect" "reflect"
"testing" "testing"
@ -36,7 +36,7 @@ func (n *proofPairList) Get(key []byte) ([]byte, error) {
return b, nil return b, nil
} }
} }
return nil, fmt.Errorf("key not found") return nil, errors.New("key not found")
} }
func TestTransactionProof(t *testing.T) { func TestTransactionProof(t *testing.T) {

View file

@ -18,7 +18,7 @@
package les package les
import ( import (
"fmt" "errors"
"sync" "sync"
"time" "time"
@ -155,12 +155,12 @@ type LightDummyAPI struct{}
// Etherbase is the address that mining rewards will be send to // Etherbase is the address that mining rewards will be send to
func (s *LightDummyAPI) Etherbase() (common.Address, error) { 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) // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
func (s *LightDummyAPI) Coinbase() (common.Address, error) { 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 // Hashrate returns the POW hashrate

View file

@ -291,7 +291,7 @@ func (p *peer) RequestHelperTrieProofs(reqID, cost uint64, reqs []HelperTrieReq)
reqsV1 := make([]ChtReq, len(reqs)) reqsV1 := make([]ChtReq, len(reqs))
for i, req := range reqs { for i, req := range reqs {
if req.Type != htCanonical || req.AuxReq != auxHeader || len(req.Key) != 8 { 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) blockNum := binary.BigEndian.Uint64(req.Key)
// convert HelperTrie request to old CHT request // convert HelperTrie request to old CHT request

View file

@ -22,7 +22,7 @@ import (
"context" "context"
"crypto/rand" "crypto/rand"
"encoding/binary" "encoding/binary"
"fmt" "errors"
"sync" "sync"
"time" "time"
@ -119,7 +119,7 @@ func (rm *retrieveManager) retrieve(ctx context.Context, reqID uint64, req *dist
case <-ctx.Done(): case <-ctx.Done():
sentReq.stop(ctx.Err()) sentReq.stop(ctx.Err())
case <-shutdown: case <-shutdown:
sentReq.stop(fmt.Errorf("Client is shutting down")) sentReq.stop(errors.New("Client is shutting down"))
} }
return sentReq.getError() return sentReq.getError()
} }

View file

@ -19,10 +19,12 @@ package light
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/consensus/ethash" "github.com/XinFinOrg/XDPoSChain/consensus/ethash"
"github.com/XinFinOrg/XDPoSChain/core" "github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/core/state" "github.com/XinFinOrg/XDPoSChain/core/state"
@ -74,9 +76,9 @@ func diffTries(t1, t2 state.Trie) error {
case i2.Err != nil: case i2.Err != nil:
return fmt.Errorf("light trie iterator error: %v", i1.Err) return fmt.Errorf("light trie iterator error: %v", i1.Err)
case i1.Next(): 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(): 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 return nil
} }

View file

@ -18,6 +18,7 @@ package node
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"strings" "strings"
"time" "time"
@ -169,7 +170,7 @@ func (api *PrivateAdminAPI) StopRPC() (bool, error) {
defer api.node.lock.Unlock() defer api.node.lock.Unlock()
if api.node.httpHandler == nil { if api.node.httpHandler == nil {
return false, fmt.Errorf("HTTP RPC not running") return false, errors.New("HTTP RPC not running")
} }
api.node.stopHTTP() api.node.stopHTTP()
return true, nil return true, nil
@ -223,7 +224,7 @@ func (api *PrivateAdminAPI) StopWS() (bool, error) {
defer api.node.lock.Unlock() defer api.node.lock.Unlock()
if api.node.wsHandler == nil { if api.node.wsHandler == nil {
return false, fmt.Errorf("WebSocket RPC not running") return false, errors.New("WebSocket RPC not running")
} }
api.node.stopWS() api.node.stopWS()
return true, nil return true, nil

View file

@ -17,6 +17,7 @@
package node package node
import ( import (
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@ -70,7 +71,7 @@ func TestContextServices(t *testing.T) {
verifier := func(ctx *ServiceContext) (Service, error) { verifier := func(ctx *ServiceContext) (Service, error) {
var objA *NoopServiceA var objA *NoopServiceA
if ctx.Service(&objA) != nil { if ctx.Service(&objA) != nil {
return nil, fmt.Errorf("former service not found") return nil, errors.New("former service not found")
} }
var objB *NoopServiceB var objB *NoopServiceB
if err := ctx.Service(&objB); err != ErrServiceUnknown { if err := ctx.Service(&objB); err != ErrServiceUnknown {

View file

@ -1063,7 +1063,7 @@ func (net *Network) checkPacket(n *Node, ev nodeEvent, pkt *ingressPacket) error
case pongPacket: case pongPacket:
if !bytes.Equal(pkt.data.(*pong).ReplyTok, n.pingEcho) { if !bytes.Equal(pkt.data.(*pong).ReplyTok, n.pingEcho) {
// fmt.Println("pong reply token mismatch") // fmt.Println("pong reply token mismatch")
return fmt.Errorf("pong reply token mismatch") return errors.New("pong reply token mismatch")
} }
n.pingEcho = nil n.pingEcho = nil
} }

View file

@ -19,6 +19,7 @@ package discv5
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"math" "math"
"math/rand" "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)) return nil, fmt.Errorf("bad wait period list: got %d values, want %d", len(topics), len(wps))
} }
if rlpHash(topics) != p.data.(*pong).TopicHash { if rlpHash(topics) != p.data.(*pong).TopicHash {
return nil, fmt.Errorf("bad topic hash") return nil, errors.New("bad topic hash")
} }
t := &ticket{ t := &ticket{
issueTime: localTime, issueTime: localTime,

View file

@ -275,7 +275,7 @@ func (r *Record) verifySignature() error {
if err := r.Load(&entry); err != nil { if err := r.Load(&entry); err != nil {
return err return err
} else if len(entry) != 33 { } else if len(entry) != 33 {
return fmt.Errorf("invalid public key") return errors.New("invalid public key")
} }
// Verify the signature. // Verify the signature.

View file

@ -17,12 +17,13 @@
package nat package nat
import ( import (
"errors"
"fmt" "fmt"
"net" "net"
"strings" "strings"
"time" "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 // 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 { func (n *pmp) AddMapping(protocol string, extport, intport int, name string, lifetime time.Duration) error {
if lifetime <= 0 { 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 // Note order of port arguments is switched between our
// AddMapping and the client's AddPortMapping. // AddMapping and the client's AddPortMapping.

View file

@ -17,6 +17,7 @@
package p2p package p2p
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net" "net"
@ -409,7 +410,7 @@ func (rw *protoRW) WriteMsg(msg Msg) (err error) {
// as well but we don't want to rely on that. // as well but we don't want to rely on that.
rw.werr <- err rw.werr <- err
case <-rw.closed: case <-rw.closed:
err = fmt.Errorf("shutting down") err = errors.New("shutting down")
} }
return err return err
} }

View file

@ -43,7 +43,7 @@ type kill struct {
type drop 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 // the first message peers send and receive as part the initial exchange
type protoHandshake struct { type protoHandshake struct {
Version uint // local and remote peer should have identical version 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) { 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) { func TestModuleHandshakeSuccess(t *testing.T) {
@ -376,14 +376,14 @@ WAIT:
func TestMultiplePeersDropSelf(t *testing.T) { func TestMultiplePeersDropSelf(t *testing.T) {
runMultiplePeers(t, 0, runMultiplePeers(t, 0,
fmt.Errorf("subprotocol error"), errors.New("subprotocol error"),
fmt.Errorf("Message handler error: (msg code 3): dropped"), errors.New("Message handler error: (msg code 3): dropped"),
) )
} }
func TestMultiplePeersDropOther(t *testing.T) { func TestMultiplePeersDropOther(t *testing.T) {
runMultiplePeers(t, 1, runMultiplePeers(t, 1,
fmt.Errorf("Message handler error: (msg code 3): dropped"), errors.New("Message handler error: (msg code 3): dropped"),
fmt.Errorf("subprotocol error"), errors.New("subprotocol error"),
) )
} }

View file

@ -147,7 +147,7 @@ func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake,
return nil, err return nil, err
} }
if msg.Size > baseProtocolMaxMsgSize { if msg.Size > baseProtocolMaxMsgSize {
return nil, fmt.Errorf("message too big") return nil, errors.New("message too big")
} }
if msg.Code == discMsg { if msg.Code == discMsg {
// Disconnect before protocol handshake is valid according to the // Disconnect before protocol handshake is valid according to the

View file

@ -20,7 +20,6 @@ package p2p
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"errors" "errors"
"fmt"
"net" "net"
"sync" "sync"
"time" "time"
@ -365,7 +364,7 @@ type sharedUDPConn struct {
func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
packet, ok := <-s.unhandled packet, ok := <-s.unhandled
if !ok { if !ok {
return 0, nil, fmt.Errorf("Connection was closed") return 0, nil, errors.New("Connection was closed")
} }
l := len(packet.Data) l := len(packet.Data)
if l > len(b) { if l > len(b) {
@ -397,7 +396,7 @@ func (srv *Server) Start() (err error) {
// static fields // static fields
if srv.PrivateKey == nil { 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 { if srv.newTransport == nil {
srv.newTransport = newRLPX srv.newTransport = newRLPX

View file

@ -273,7 +273,7 @@ func (self *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error
} }
delete(expects, event.Peer) delete(expects, event.Peer)
case <-timeout: case <-timeout:
return fmt.Errorf("timed out waiting for peers to disconnect") return errors.New("timed out waiting for peers to disconnect")
} }
} }
return nil return nil

View file

@ -19,7 +19,7 @@ package rpc
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "errors"
"math" "math"
"strings" "strings"
@ -109,7 +109,7 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
return err return err
} }
if blckNum > math.MaxInt64 { if blckNum > math.MaxInt64 {
return fmt.Errorf("block number larger than int64") return errors.New("block number larger than int64")
} }
*bn = BlockNumber(blckNum) *bn = BlockNumber(blckNum)
return nil return nil
@ -131,7 +131,7 @@ func (e *EpochNumber) UnmarshalJSON(data []byte) error {
return err return err
} }
if eNum > math.MaxInt64 { if eNum > math.MaxInt64 {
return fmt.Errorf("EpochNumber too high") return errors.New("EpochNumber too high")
} }
*e = EpochNumber(eNum) *e = EpochNumber(eNum)
@ -154,7 +154,7 @@ func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error {
err := json.Unmarshal(data, &e) err := json.Unmarshal(data, &e)
if err == nil { if err == nil {
if e.BlockNumber != nil && e.BlockHash != 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.BlockNumber = e.BlockNumber
bnh.BlockHash = e.BlockHash bnh.BlockHash = e.BlockHash
@ -198,7 +198,7 @@ func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error {
return err return err
} }
if blckNum > math.MaxInt64 { if blckNum > math.MaxInt64 {
return fmt.Errorf("blocknumber too high") return errors.New("blocknumber too high")
} }
bn := BlockNumber(blckNum) bn := BlockNumber(blckNum)
bnh.BlockNumber = &bn bnh.BlockNumber = &bn

View file

@ -18,6 +18,7 @@ package api
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "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 { err = filepath.Walk(localpath, func(path string, info os.FileInfo, err error) error {
if (err == nil) && !info.IsDir() { if (err == nil) && !info.IsDir() {
if len(path) <= start { if len(path) <= start {
return fmt.Errorf("Path is too short") return errors.New("Path is too short")
} }
if path[:start] != localpath { if path[:start] != localpath {
return fmt.Errorf("Path prefix of '%s' does not match localpath '%s'", path, 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) dir := filepath.Dir(localpath)
start = len(dir) start = len(dir)
if len(localpath) <= start { if len(localpath) <= start {
return "", fmt.Errorf("Path is too short") return "", errors.New("Path is too short")
} }
if localpath[:start] != dir { if localpath[:start] != dir {
return "", fmt.Errorf("Path prefix of '%s' does not match dir '%s'", localpath, 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: case done <- true:
wg.Add(1) wg.Add(1)
case <-quitC: case <-quitC:
return fmt.Errorf("aborted") return errors.New("aborted")
} }
go func(i int, entry *downloadListEntry) { go func(i int, entry *downloadListEntry) {
defer wg.Done() defer wg.Done()
@ -263,7 +264,7 @@ func (self *FileSystem) Download(bzzpath, localpath string) error {
case err = <-errC: case err = <-errC:
return err return err
case <-quitC: case <-quitC:
return fmt.Errorf("aborted") return errors.New("aborted")
} }
} }

View file

@ -374,7 +374,7 @@ func (s *Server) HandleGet(w http.ResponseWriter, r *Request) {
}) })
if entry == nil { if entry == nil {
getFail.Inc(1) 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 return
} }
key = storage.Key(common.Hex2Bytes(entry.Hash)) key = storage.Key(common.Hex2Bytes(entry.Hash))

View file

@ -195,7 +195,7 @@ func readManifest(manifestReader storage.LazySectionReader, hash storage.Key, dp
size, err := manifestReader.Size(quitC) size, err := manifestReader.Size(quitC)
if err != nil { // size == 0 if err != nil { // size == 0
// can't determine size means we don't have the root chunk // 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 return
} }
manifestData := make([]byte, size) manifestData := make([]byte, size)
@ -381,7 +381,7 @@ func (self *manifestTrie) listWithPrefixInt(prefix, rp string, quitC chan bool,
for i := start; i <= stop; i++ { for i := start; i <= stop; i++ {
select { select {
case <-quitC: case <-quitC:
return fmt.Errorf("aborted") return errors.New("aborted")
default: default:
} }
entry := self.entries[i] entry := self.entries[i]

View file

@ -14,13 +14,14 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//go:build linux || darwin || freebsd
// +build linux darwin freebsd // +build linux darwin freebsd
package fuse package fuse
import ( import (
"context" "context"
"fmt" "errors"
"os/exec" "os/exec"
"runtime" "runtime"
@ -42,7 +43,7 @@ func externalUnmount(mountPoint string) error {
case "linux": case "linux":
return exec.CommandContext(ctx, "fusermount", "-u", mountPoint).Run() return exec.CommandContext(ctx, "fusermount", "-u", mountPoint).Run()
default: default:
return fmt.Errorf("unmount: unimplemented") return errors.New("unmount: unimplemented")
} }
} }

View file

@ -17,6 +17,7 @@
package network package network
import ( import (
"errors"
"fmt" "fmt"
"math/rand" "math/rand"
"path/filepath" "path/filepath"
@ -77,7 +78,7 @@ type HiveParams struct {
*kademlia.KadParams *kademlia.KadParams
} }
//create default params // create default params
func NewDefaultHiveParams() *HiveParams { func NewDefaultHiveParams() *HiveParams {
kad := kademlia.NewDefaultKadParams() kad := kademlia.NewDefaultKadParams()
// kad.BucketSize = bucketSize // 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) // this can only finally be set after all config options (file, cmd line, env vars)
//have been evaluated // have been evaluated
func (self *HiveParams) Init(path string) { func (self *HiveParams) Init(path string) {
self.KadDbPath = filepath.Join(path, "bzz-peers.json") 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 { func loadSync(record *kademlia.NodeRecord, node kademlia.Node) error {
p, ok := node.(*peer) p, ok := node.(*peer)
if !ok { if !ok {
return fmt.Errorf("invalid type") return errors.New("invalid type")
} }
if record.Meta == nil { if record.Meta == nil {
log.Debug(fmt.Sprintf("no sync state for node record %v setting default", record)) log.Debug(fmt.Sprintf("no sync state for node record %v setting default", record))

View file

@ -17,6 +17,7 @@
package kademlia package kademlia
import ( import (
"errors"
"fmt" "fmt"
"sort" "sort"
"strings" "strings"
@ -27,10 +28,10 @@ import (
"github.com/XinFinOrg/XDPoSChain/metrics" "github.com/XinFinOrg/XDPoSChain/metrics"
) )
//metrics variables // metrics variables
//For metrics, we want to count how many times peers are added/removed // 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 // at a certain index. Thus we do that with an array of counters with
//entry for each index // entry for each index
var ( var (
bucketAddIndexCount []metrics.Counter bucketAddIndexCount []metrics.Counter
bucketRmIndexCount []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 { if replaced == nil {
log.Debug(fmt.Sprintf("all peers wanted, PO%03d bucket full", index)) 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)) log.Debug(fmt.Sprintf("node %v replaced by %v (idle for %v > %v)", replaced, node, idle, self.MaxIdleInterval))
replaced.Drop() 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]) }) 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) { func (self *Kademlia) Add(nrs []*NodeRecord) {
self.db.add(nrs, self.proximityBin) self.db.add(nrs, self.proximityBin)
} }
@ -441,7 +442,7 @@ func (self *Kademlia) String() string {
return strings.Join(rows, "\n") 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() { func (self *Kademlia) initMetricsVariables() {
//create the arrays //create the arrays
bucketAddIndexCount = make([]metrics.Counter, self.MaxProx+1) bucketAddIndexCount = make([]metrics.Counter, self.MaxProx+1)

View file

@ -46,7 +46,7 @@ import (
"github.com/XinFinOrg/XDPoSChain/swarm/storage" "github.com/XinFinOrg/XDPoSChain/swarm/storage"
) )
//metrics variables // metrics variables
var ( var (
storeRequestMsgCounter = metrics.NewRegisteredCounter("network.protocol.msg.storerequest.count", nil) storeRequestMsgCounter = metrics.NewRegisteredCounter("network.protocol.msg.storerequest.count", nil)
retrieveRequestMsgCounter = metrics.NewRegisteredCounter("network.protocol.msg.retrieverequest.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 the main protocol loop that
* does the handshake by exchanging statusMsg - does the handshake by exchanging statusMsg
* if peer is valid and accepted, registers with the hive - if peer is valid and accepted, registers with the hive
* then enters into a forever loop handling incoming messages - then enters into a forever loop handling incoming messages
* storage and retrieval related queries coming via bzz are dispatched to StorageHandler - storage and retrieval related queries coming via bzz are dispatched to StorageHandler
* peer-related messages are dispatched to the hive - peer-related messages are dispatched to the hive
* payment related messages are relayed to SWAP service - payment related messages are relayed to SWAP service
* on disconnect, unregister the peer in the hive (note RemovePeer in the post-disconnect hook) - 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 the loop terminates, the peer will disconnect with Subprotocol error
* whenever handlers return an error the loop terminates - 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) { 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() { if req.isLookup() {
log.Trace(fmt.Sprintf("self lookup for %v: responding with peers only...", req.from)) log.Trace(fmt.Sprintf("self lookup for %v: responding with peers only...", req.from))
} else if req.Key == nil { } 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 { } else {
// swap accounting is done within netStore // swap accounting is done within netStore
self.storage.HandleRetrieveRequestMsg(&req, &peer{bzz: self}) 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 { func (self *bzz) send(msg uint64, data interface{}) error {
if self.hive.blockWrite { 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)) log.Trace(fmt.Sprintf("-> %v: %v (%T) to %v", msg, data, data, self))
err := p2p.Send(self.rw, msg, data) err := p2p.Send(self.rw, msg, data)

View file

@ -19,6 +19,7 @@ package network
import ( import (
"encoding/binary" "encoding/binary"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"path/filepath" "path/filepath"
@ -143,8 +144,8 @@ func NewDefaultSyncParams() *SyncParams {
} }
} }
//this can only finally be set after all config options (file, cmd line, env vars) // this can only finally be set after all config options (file, cmd line, env vars)
//have been evaluated // have been evaluated
func (self *SyncParams) Init(path string) { func (self *SyncParams) Init(path string) {
self.RequestDbPath = filepath.Join(path, "requests") self.RequestDbPath = filepath.Join(path, "requests")
} }
@ -237,11 +238,11 @@ func encodeSync(state *syncState) (*json.RawMessage, error) {
func decodeSync(meta *json.RawMessage) (*syncState, error) { func decodeSync(meta *json.RawMessage) (*syncState, error) {
if meta == nil { if meta == nil {
return nil, fmt.Errorf("unable to deserialise sync state from <nil>") return nil, errors.New("unable to deserialise sync state from <nil>")
} }
data := []byte(*(meta)) data := []byte(*(meta))
if len(data) == 0 { if len(data) == 0 {
return nil, fmt.Errorf("unable to deserialise sync state from <nil>") return nil, errors.New("unable to deserialise sync state from <nil>")
} }
state := &syncState{DbSyncState: &storage.DbSyncState{}} state := &syncState{DbSyncState: &storage.DbSyncState{}}
err := json.Unmarshal(data, state) err := json.Unmarshal(data, state)
@ -249,22 +250,22 @@ func decodeSync(meta *json.RawMessage) (*syncState, error) {
} }
/* /*
sync implements the syncing script sync implements the syncing script
* first all items left in the request Db are replayed * first all items left in the request Db are replayed
* type = StaleSync - type = StaleSync
* Mode: by default once again via confirmation roundtrip - Mode: by default once again via confirmation roundtrip
* Priority: the items are replayed as the proirity specified for StaleSync - Priority: the items are replayed as the proirity specified for StaleSync
* but within the order respects earlier priority level of request - but within the order respects earlier priority level of request
* after all items are consumed for a priority level, the the respective - 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) queue for delivery requests is open (this way new reqs not written to db)
(TODO: this should be checked) (TODO: this should be checked)
* the sync state provided by the remote peer is used to sync history - 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 - all the backlog from earlier (aborted) syncing is completed starting from latest
* if Last < LastSeenAt then all items in between then process all - if Last < LastSeenAt then all items in between then process all
backlog from upto last disconnect backlog from upto last disconnect
* if Last > 0 && - if Last > 0 &&
sync is called from the syncer constructor and is not supposed to be used externally sync is called from the syncer constructor and is not supposed to be used externally
*/ */
func (self *syncer) sync() { func (self *syncer) sync() {
state := self.state state := self.state
@ -406,11 +407,11 @@ func (self *syncer) sendUnsyncedKeys() {
} }
// assembles a new batch of unsynced keys // assembles a new batch of unsynced keys
// * keys are drawn from the key buffers in order of priority queue // - keys are drawn from the key buffers in order of priority queue
// * if the queues of priority for History (HistoryReq) or higher are depleted, // - if the queues of priority for History (HistoryReq) or higher are depleted,
// historical data is used so historical items are lower priority within // historical data is used so historical items are lower priority within
// their priority group. // their priority group.
// * Order of historical data is unspecified // - Order of historical data is unspecified
func (self *syncer) syncUnsyncedKeys() { func (self *syncer) syncUnsyncedKeys() {
// send out new // send out new
var unsynced []*syncRequest var unsynced []*syncRequest
@ -621,19 +622,19 @@ func (self *syncer) syncDeliveries() {
} }
/* /*
addRequest handles requests for delivery addRequest handles requests for delivery
it accepts 4 types: it accepts 4 types:
* storeRequestMsgData: coming from netstore propagate response * storeRequestMsgData: coming from netstore propagate response
* chunk: coming from forwarding (questionable: id?) * chunk: coming from forwarding (questionable: id?)
* key: from incoming syncRequest * key: from incoming syncRequest
* syncDbEntry: key,id encoded in db * syncDbEntry: key,id encoded in db
If sync mode is on for the type of request, then If sync mode is on for the type of request, then
it sends the request to the keys queue of the correct priority it sends the request to the keys queue of the correct priority
channel buffered with capacity (SyncBufferSize) 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) { func (self *syncer) addRequest(req interface{}, ty int) {
// retrieve priority for request type name int8 // retrieve priority for request type name int8

View file

@ -183,7 +183,7 @@ func testRandomBrokenData(splitter Splitter, n int, tester *chunkerTester) {
chunkC := make(chan *Chunk, 1000) chunkC := make(chan *Chunk, 1000)
swg := &sync.WaitGroup{} swg := &sync.WaitGroup{}
expectedError := fmt.Errorf("Broken reader") expectedError := errors.New("Broken reader")
key, err := tester.Split(splitter, brokendata, int64(n), chunkC, swg, expectedError) key, err := tester.Split(splitter, brokendata, int64(n), chunkC, swg, expectedError)
if err == nil || err.Error() != expectedError.Error() { if err == nil || err.Error() != expectedError.Error() {
tester.t.Fatalf("Not receiving the correct error! Expected %v, received %v", expectedError, err) tester.t.Fatalf("Not receiving the correct error! Expected %v, received %v", expectedError, err)

View file

@ -19,6 +19,7 @@ package storage
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"errors"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@ -48,7 +49,7 @@ func testDataReader(l int) (r io.Reader) {
func (self *brokenLimitedReader) Read(buf []byte) (int, error) { func (self *brokenLimitedReader) Read(buf []byte) (int, error) {
if self.off+len(buf) > self.errAt { if self.off+len(buf) > self.errAt {
return 0, fmt.Errorf("Broken reader") return 0, errors.New("Broken reader")
} }
self.off += len(buf) self.off += len(buf)
return self.lr.Read(buf) return self.lr.Read(buf)

View file

@ -27,6 +27,7 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@ -562,7 +563,7 @@ type dbSyncIterator struct {
// initialises a sync iterator from a syncToken (passed in with the handshake) // initialises a sync iterator from a syncToken (passed in with the handshake)
func (self *DbStore) NewSyncIterator(state DbSyncState) (si *dbSyncIterator, err error) { func (self *DbStore) NewSyncIterator(state DbSyncState) (si *dbSyncIterator, err error) {
if state.First > state.Last { if state.First > state.Last {
return nil, fmt.Errorf("no entries found") return nil, errors.New("no entries found")
} }
si = &dbSyncIterator{ si = &dbSyncIterator{
it: self.db.NewIterator(), it: self.db.NewIterator(),

View file

@ -20,6 +20,7 @@ import (
"bytes" "bytes"
"context" "context"
"crypto/ecdsa" "crypto/ecdsa"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"net" "net"
@ -94,10 +95,10 @@ func (self *Swarm) API() *SwarmAPI {
// implements node.Service // implements node.Service
func NewSwarm(ctx *node.ServiceContext, backend chequebook.Backend, config *api.Config) (self *Swarm, err error) { func NewSwarm(ctx *node.ServiceContext, backend chequebook.Backend, config *api.Config) (self *Swarm, err error) {
if bytes.Equal(common.FromHex(config.PublicKey), storage.ZeroKey) { 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) { 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{ self = &Swarm{

View file

@ -21,10 +21,12 @@ import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"math/big" "math/big"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/common/hexutil" "github.com/XinFinOrg/XDPoSChain/common/hexutil"
"github.com/XinFinOrg/XDPoSChain/common/math" "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 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 blockHeader, transactions and uncleHeaders fields. If they are missing, the block is
invalid and we must verify that we do not accept it. 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 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 expected we are expected to ignore it and continue processing and then validate the
post state. post state.
*/ */
func (t *BlockTest) insertBlocks(blockchain *core.BlockChain) ([]btBlock, error) { func (t *BlockTest) insertBlocks(blockchain *core.BlockChain) ([]btBlock, error) {
validBlocks := make([]btBlock, 0) validBlocks := make([]btBlock, 0)
@ -185,7 +188,7 @@ func (t *BlockTest) insertBlocks(blockchain *core.BlockChain) ([]btBlock, error)
} }
} }
if b.BlockHeader == nil { 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 // validate RLP decoding by checking all values against test file JSON

View file

@ -18,6 +18,7 @@ package tests
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -169,7 +170,7 @@ func (tm *testMatcher) checkFailure(t *testing.T, name string, err error) error
t.Logf("error: %v", err) t.Logf("error: %v", err)
return nil return nil
} else { } else {
return fmt.Errorf("test succeeded unexpectedly") return errors.New("test succeeded unexpectedly")
} }
} }
return err return err

View file

@ -46,7 +46,7 @@ type RLPTest struct {
func (t *RLPTest) Run() error { func (t *RLPTest) Run() error {
outb, err := hex.DecodeString(t.Out) outb, err := hex.DecodeString(t.Out)
if err != nil { 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. // Handle simple decoding tests with no actual In value.
@ -74,7 +74,7 @@ func checkDecodeInterface(b []byte, isValid bool) error {
case isValid && err != nil: case isValid && err != nil:
return fmt.Errorf("decoding failed: %v", err) return fmt.Errorf("decoding failed: %v", err)
case !isValid && err == nil: case !isValid && err == nil:
return fmt.Errorf("decoding of invalid value succeeded") return errors.New("decoding of invalid value succeeded")
} }
return nil return nil
} }

View file

@ -19,6 +19,7 @@ package tests
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math/big" "math/big"
@ -85,10 +86,10 @@ func (t *VMTest) Run(vmconfig vm.Config) error {
if t.json.GasRemaining == nil { if t.json.GasRemaining == nil {
if err == 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 { 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 return nil
} }

View file

@ -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 // 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): // 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 // - 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. // 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 // - 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. // 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 // 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. // 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 return err, false
} }
if !bytes.Equal(val, values[0]) { 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]) return nil, hasRightElement(root, keys[0])
} }

View file

@ -19,6 +19,7 @@ package trie
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"math/rand" "math/rand"
@ -446,7 +447,7 @@ func runRandTest(rt randTest) bool {
checktr.Update(it.Key, it.Value) checktr.Update(it.Key, it.Value)
} }
if tr.Hash() != checktr.Hash() { 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. // Abort the test on error.

View file

@ -471,7 +471,7 @@ func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) {
f := api.w.GetFilter(id) f := api.w.GetFilter(id)
if f == nil { if f == nil {
api.mu.Unlock() api.mu.Unlock()
return nil, fmt.Errorf("filter not found") return nil, errors.New("filter not found")
} }
api.lastUsed[id] = time.Now() api.lastUsed[id] = time.Now()
api.mu.Unlock() api.mu.Unlock()

View file

@ -18,6 +18,7 @@ package whisperv5
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"errors"
"fmt" "fmt"
"sync" "sync"
@ -66,7 +67,7 @@ func (fs *Filters) Install(watcher *Filter) (string, error) {
defer fs.mutex.Unlock() defer fs.mutex.Unlock()
if fs.watchers[id] != nil { if fs.watchers[id] != nil {
return "", fmt.Errorf("failed to generate unique ID") return "", errors.New("failed to generate unique ID")
} }
if watcher.expectsSymmetricEncryption() { if watcher.expectsSymmetricEncryption() {

View file

@ -247,7 +247,7 @@ func (w *Whisper) NewKeyPair() (string, error) {
return "", err return "", err
} }
if !validatePrivateKey(key) { if !validatePrivateKey(key) {
return "", fmt.Errorf("failed to generate valid key") return "", errors.New("failed to generate valid key")
} }
id, err := GenerateRandomID() id, err := GenerateRandomID()
@ -259,7 +259,7 @@ func (w *Whisper) NewKeyPair() (string, error) {
defer w.keyMu.Unlock() defer w.keyMu.Unlock()
if w.privateKeys[id] != nil { 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 w.privateKeys[id] = key
return id, nil return id, nil
@ -305,7 +305,7 @@ func (w *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
defer w.keyMu.RUnlock() defer w.keyMu.RUnlock()
key := w.privateKeys[id] key := w.privateKeys[id]
if key == nil { if key == nil {
return nil, fmt.Errorf("invalid id") return nil, errors.New("invalid id")
} }
return key, nil return key, nil
} }
@ -318,7 +318,7 @@ func (w *Whisper) GenerateSymKey() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} else if !validateSymmetricKey(key) { } 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() id, err := GenerateRandomID()
@ -330,7 +330,7 @@ func (w *Whisper) GenerateSymKey() (string, error) {
defer w.keyMu.Unlock() defer w.keyMu.Unlock()
if w.symKeys[id] != nil { 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 w.symKeys[id] = key
return id, nil return id, nil
@ -351,7 +351,7 @@ func (w *Whisper) AddSymKeyDirect(key []byte) (string, error) {
defer w.keyMu.Unlock() defer w.keyMu.Unlock()
if w.symKeys[id] != nil { 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 w.symKeys[id] = key
return id, nil return id, nil
@ -364,7 +364,7 @@ func (w *Whisper) AddSymKeyFromPassword(password string) (string, error) {
return "", fmt.Errorf("failed to generate ID: %s", err) return "", fmt.Errorf("failed to generate ID: %s", err)
} }
if w.HasSymKey(id) { 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) 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 // double check is necessary, because deriveKeyMaterial() is very slow
if w.symKeys[id] != nil { 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 w.symKeys[id] = derived
return id, nil return id, nil
@ -409,7 +409,7 @@ func (w *Whisper) GetSymKey(id string) ([]byte, error) {
if w.symKeys[id] != nil { if w.symKeys[id] != nil {
return 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 // 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 { func (w *Whisper) Unsubscribe(id string) error {
ok := w.filters.Uninstall(id) ok := w.filters.Uninstall(id)
if !ok { if !ok {
return fmt.Errorf("Unsubscribe: Invalid ID") return errors.New("Unsubscribe: Invalid ID")
} }
return nil return nil
} }
@ -440,7 +440,7 @@ func (w *Whisper) Send(envelope *Envelope) error {
return err return err
} }
if !ok { if !ok {
return fmt.Errorf("failed to add envelope") return errors.New("failed to add envelope")
} }
return err return err
} }
@ -576,7 +576,7 @@ func (wh *Whisper) add(envelope *Envelope) (bool, error) {
if envelope.Expiry < now { if envelope.Expiry < now {
if envelope.Expiry+SynchAllowance*2 < now { if envelope.Expiry+SynchAllowance*2 < now {
return false, fmt.Errorf("very old message") return false, errors.New("very old message")
} else { } else {
log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex()) log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
return false, nil // drop envelope without error return false, nil // drop envelope without error
@ -851,7 +851,7 @@ func GenerateRandomID() (id string, err error) {
return "", err return "", err
} }
if !validateSymmetricKey(buf) { 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) id = common.Bytes2Hex(buf)
return id, err return id, err

View file

@ -490,7 +490,7 @@ func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error) {
f := api.w.GetFilter(id) f := api.w.GetFilter(id)
if f == nil { if f == nil {
api.mu.Unlock() api.mu.Unlock()
return nil, fmt.Errorf("filter not found") return nil, errors.New("filter not found")
} }
api.lastUsed[id] = time.Now() api.lastUsed[id] = time.Now()
api.mu.Unlock() api.mu.Unlock()

View file

@ -18,6 +18,7 @@ package whisperv6
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"errors"
"fmt" "fmt"
"sync" "sync"
@ -65,7 +66,7 @@ func NewFilters(w *Whisper) *Filters {
// Install will add a new filter to the filter collection // Install will add a new filter to the filter collection
func (fs *Filters) Install(watcher *Filter) (string, error) { func (fs *Filters) Install(watcher *Filter) (string, error) {
if watcher.KeySym != nil && watcher.KeyAsym != nil { 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 { if watcher.Messages == nil {
@ -81,7 +82,7 @@ func (fs *Filters) Install(watcher *Filter) (string, error) {
defer fs.mutex.Unlock() defer fs.mutex.Unlock()
if fs.watchers[id] != nil { if fs.watchers[id] != nil {
return "", fmt.Errorf("failed to generate unique ID") return "", errors.New("failed to generate unique ID")
} }
if watcher.expectsSymmetricEncryption() { if watcher.expectsSymmetricEncryption() {

View file

@ -379,7 +379,7 @@ func (whisper *Whisper) NewKeyPair() (string, error) {
return "", err return "", err
} }
if !validatePrivateKey(key) { if !validatePrivateKey(key) {
return "", fmt.Errorf("failed to generate valid key") return "", errors.New("failed to generate valid key")
} }
id, err := GenerateRandomID() id, err := GenerateRandomID()
@ -391,7 +391,7 @@ func (whisper *Whisper) NewKeyPair() (string, error) {
defer whisper.keyMu.Unlock() defer whisper.keyMu.Unlock()
if whisper.privateKeys[id] != nil { 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 whisper.privateKeys[id] = key
return id, nil return id, nil
@ -437,7 +437,7 @@ func (whisper *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
defer whisper.keyMu.RUnlock() defer whisper.keyMu.RUnlock()
key := whisper.privateKeys[id] key := whisper.privateKeys[id]
if key == nil { if key == nil {
return nil, fmt.Errorf("invalid id") return nil, errors.New("invalid id")
} }
return key, nil return key, nil
} }
@ -449,7 +449,7 @@ func (whisper *Whisper) GenerateSymKey() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} else if !validateDataIntegrity(key, aesKeyLength) { } 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() id, err := GenerateRandomID()
@ -461,7 +461,7 @@ func (whisper *Whisper) GenerateSymKey() (string, error) {
defer whisper.keyMu.Unlock() defer whisper.keyMu.Unlock()
if whisper.symKeys[id] != nil { 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 whisper.symKeys[id] = key
return id, nil return id, nil
@ -482,7 +482,7 @@ func (whisper *Whisper) AddSymKeyDirect(key []byte) (string, error) {
defer whisper.keyMu.Unlock() defer whisper.keyMu.Unlock()
if whisper.symKeys[id] != nil { 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 whisper.symKeys[id] = key
return id, nil return id, nil
@ -495,7 +495,7 @@ func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) {
return "", fmt.Errorf("failed to generate ID: %s", err) return "", fmt.Errorf("failed to generate ID: %s", err)
} }
if whisper.HasSymKey(id) { 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, // 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 // double check is necessary, because deriveKeyMaterial() is very slow
if whisper.symKeys[id] != nil { 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 whisper.symKeys[id] = derived
return id, nil return id, nil
@ -542,7 +542,7 @@ func (whisper *Whisper) GetSymKey(id string) ([]byte, error) {
if whisper.symKeys[id] != nil { if whisper.symKeys[id] != nil {
return 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 // 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 { func (whisper *Whisper) Unsubscribe(id string) error {
ok := whisper.filters.Uninstall(id) ok := whisper.filters.Uninstall(id)
if !ok { if !ok {
return fmt.Errorf("Unsubscribe: Invalid ID") return errors.New("Unsubscribe: Invalid ID")
} }
return nil return nil
} }
@ -591,7 +591,7 @@ func (whisper *Whisper) Unsubscribe(id string) error {
func (whisper *Whisper) Send(envelope *Envelope) error { func (whisper *Whisper) Send(envelope *Envelope) error {
ok, err := whisper.add(envelope, false) ok, err := whisper.add(envelope, false)
if err == nil && !ok { if err == nil && !ok {
return fmt.Errorf("failed to add envelope") return errors.New("failed to add envelope")
} }
return err return err
} }
@ -762,7 +762,7 @@ func (whisper *Whisper) add(envelope *Envelope, isP2P bool) (bool, error) {
if envelope.Expiry < now { if envelope.Expiry < now {
if envelope.Expiry+DefaultSyncAllowance*2 < 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()) log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
return false, nil // drop envelope without error return false, nil // drop envelope without error
@ -1009,7 +1009,7 @@ func GenerateRandomID() (id string, err error) {
return "", err return "", err
} }
if !validateDataIntegrity(buf, keyIDSize) { 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) id = common.Bytes2Hex(buf)
return id, err return id, err