From c913f35c2e42e9cc1a1c31d681f834531cc095bb Mon Sep 17 00:00:00 2001 From: Andrea Lanfranchi Date: Mon, 4 Oct 2021 17:16:52 +0200 Subject: [PATCH] Inner errors (#2774) --- accounts/abi/argument.go | 2 +- accounts/abi/bind/backends/simulated.go | 2 +- accounts/abi/bind/base.go | 4 +-- accounts/abi/bind/bind.go | 2 +- accounts/abi/type.go | 4 +-- accounts/abi/unpack_test.go | 4 +-- cmd/hack/db/lmdb.go | 14 +++++----- cmd/hack/hack.go | 26 +++++++++---------- cmd/rpcdaemon/commands/erigon_receipts.go | 4 +-- cmd/rpcdaemon/commands/eth_accounts.go | 6 ++--- cmd/rpcdaemon/commands/eth_receipts.go | 4 +-- cmd/rpcdaemon/commands/rpc_block.go | 2 +- cmd/rpcdaemon/commands/storage_range.go | 2 +- cmd/rpcdaemon/commands/trace_filtering.go | 2 +- cmd/rpctest/rpctest/utils.go | 2 +- .../commands/generate_body_snapshot.go | 2 +- .../commands/generate_header_snapshot.go | 2 +- .../commands/generate_state_snapshot.go | 4 +-- cmd/snapshots/tracker/commands/root.go | 2 +- cmd/state/commands/opcode_tracer.go | 6 ++--- cmd/utils/diskusage_windows.go | 4 +-- cmd/utils/flags.go | 2 +- common/compiler/solidity.go | 4 +-- common/compiler/vyper.go | 2 +- common/test_utils.go | 4 +-- core/blockchain.go | 4 +-- core/genesis.go | 6 ++--- core/rawdb/accessors_chain.go | 16 ++++++------ core/state/database_test.go | 2 +- core/state/dump.go | 6 ++--- core/state/intra_block_state_test.go | 2 +- core/state/state_object.go | 2 +- core/types/receipt.go | 4 +-- core/types/transaction.go | 4 +-- eth/api_backend.go | 2 +- eth/backend.go | 4 +-- eth/filters/api.go | 4 +-- eth/tracers/internal/tracers/assets.go | 6 ++--- internal/build/archive.go | 12 ++++----- internal/build/download.go | 2 +- internal/build/util.go | 2 +- internal/jsre/deps/bindata.go | 8 +++--- internal/jsre/jsre.go | 4 +-- migrations/receipt_repair.go | 10 +++---- node/api.go | 8 +++--- p2p/discover/table.go | 2 +- p2p/discover/v4_udp.go | 2 +- p2p/discover/v4_udp_test.go | 4 +-- p2p/discover/v5_udp_test.go | 6 ++--- p2p/discover/v5wire/crypto.go | 4 +-- p2p/discover/v5wire/encoding.go | 12 ++++----- p2p/discover/v5wire/encoding_test.go | 4 +-- p2p/dnsdisc/client.go | 4 +-- p2p/enode/localnode.go | 4 +-- p2p/enode/nodedb_test.go | 4 +-- p2p/enr/enr.go | 2 +- p2p/rlpx/rlpx.go | 2 +- p2p/simulations/adapters/exec.go | 8 +++--- p2p/simulations/network.go | 4 +-- p2p/transport.go | 2 +- rlp/decode.go | 20 ++++++++------ rpc/http.go | 2 +- rpc/json.go | 2 +- rpc/subscription_test.go | 6 ++--- tests/block_test_util.go | 12 ++++----- tests/init_test.go | 4 +-- tests/rlp_test_util.go | 4 +-- tests/state_test_util.go | 6 ++--- tests/transaction_test_util.go | 2 +- tests/vm_test_util.go | 4 +-- turbo/stages/blockchain_test.go | 2 +- turbo/stages/genesis_test.go | 8 +++--- turbo/transactions/tracing.go | 4 +-- turbo/trie/trie.go | 2 +- turbo/txpool/p2p.go | 22 ++++++++-------- 75 files changed, 193 insertions(+), 191 deletions(-) diff --git a/accounts/abi/argument.go b/accounts/abi/argument.go index e6d52455965..2a0559a6fc3 100644 --- a/accounts/abi/argument.go +++ b/accounts/abi/argument.go @@ -46,7 +46,7 @@ func (argument *Argument) UnmarshalJSON(data []byte) error { var arg ArgumentMarshaling err := json.Unmarshal(data, &arg) if err != nil { - return fmt.Errorf("argument json err: %v", err) + return fmt.Errorf("argument json err: %w", err) } argument.Type, err = NewType(arg.Type, arg.InternalType, arg.Components) diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 6c545cff39b..7a97115ae70 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -673,7 +673,7 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx types.Transac signer := types.MakeSigner(b.m.ChainConfig, b.pendingBlock.NumberU64()) sender, senderErr := tx.Sender(*signer) if senderErr != nil { - return fmt.Errorf("invalid transaction: %v", senderErr) + return fmt.Errorf("invalid transaction: %w", senderErr) } nonce := b.pendingState.GetNonce(sender) if tx.GetNonce() != nonce { diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index b25221cf430..2b30bf7ad68 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -221,7 +221,7 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i if opts.Nonce == nil { nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From) if err != nil { - return nil, fmt.Errorf("failed to retrieve account nonce: %v", err) + return nil, fmt.Errorf("failed to retrieve account nonce: %w", err) } } else { nonce = opts.Nonce.Uint64() @@ -252,7 +252,7 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input} gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg) if err != nil { - return nil, fmt.Errorf("failed to estimate gas needed: %v", err) + return nil, fmt.Errorf("failed to estimate gas needed: %w", err) } } // Create the transaction, sign it and schedule it for execution diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 9befda58edc..0e6e832ed1b 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -240,7 +240,7 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string] if lang == LangGo { code, err := format.Source(buffer.Bytes()) if err != nil { - return "", fmt.Errorf("%v\n%s", err, buffer) + return "", fmt.Errorf("%w\n%s", err, buffer) } return string(code), nil } diff --git a/accounts/abi/type.go b/accounts/abi/type.go index 7272b9440bf..199410da840 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -103,7 +103,7 @@ func NewType(t string, internalType string, components []ArgumentMarshaling) (ty typ.Elem = &embeddedType typ.Size, err = strconv.Atoi(intz[0]) if err != nil { - return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) + return Type{}, fmt.Errorf("abi: error parsing variable size: %w", err) } typ.stringKind = embeddedType.stringKind + sliced } else { @@ -124,7 +124,7 @@ func NewType(t string, internalType string, components []ArgumentMarshaling) (ty var err error varSize, err = strconv.Atoi(parsedType[2]) if err != nil { - return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) + return Type{}, fmt.Errorf("abi: error parsing variable size: %w", err) } } else { if parsedType[0] == "uint" || parsedType[0] == "int" { diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index cc617254c04..2d169d65f96 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -66,9 +66,9 @@ type unpackTest struct { func (test unpackTest) checkError(err error) error { if err != nil { if len(test.err) == 0 { - return fmt.Errorf("expected no err but got: %v", err) + return fmt.Errorf("expected no err but got: %w", err) } else if err.Error() != test.err { - return fmt.Errorf("expected err: '%v' got err: %q", test.err, err) + return fmt.Errorf("expected err: '%v' got err: %w", test.err, err) } } else if len(test.err) > 0 { return fmt.Errorf("expected err: %v but got none", test.err) diff --git a/cmd/hack/db/lmdb.go b/cmd/hack/db/lmdb.go index 39bed92d1d9..395da6a05e3 100644 --- a/cmd/hack/db/lmdb.go +++ b/cmd/hack/db/lmdb.go @@ -945,13 +945,13 @@ func TextInfo(chaindata string, visStream io.Writer) error { f, err := os.Open(datafile) if err != nil { - return fmt.Errorf("opening %v: %v", MdbxDataFile, err) + return fmt.Errorf("opening %v: %w", MdbxDataFile, err) } defer f.Close() var meta [PageSize]byte // Read meta page 0 if _, err = f.ReadAt(meta[:], 0*PageSize); err != nil { - return fmt.Errorf("reading meta page 0: %v", err) + return fmt.Errorf("reading meta page 0: %w", err) } header1 := new(header) @@ -967,12 +967,12 @@ func TextInfo(chaindata string, visStream io.Writer) error { // meta1.print() if err != nil { - return fmt.Errorf("reading meta page 0: %v", err) + return fmt.Errorf("reading meta page 0: %w", err) } // Read meta page 1 if _, err = f.ReadAt(meta[:], 1*PageSize); err != nil { - return fmt.Errorf("reading meta page 1: %v", err) + return fmt.Errorf("reading meta page 1: %w", err) } header2 := new(header) @@ -988,7 +988,7 @@ func TextInfo(chaindata string, visStream io.Writer) error { // meta2.print() if err != nil { - return fmt.Errorf("reading meta page 1: %v", err) + return fmt.Errorf("reading meta page 1: %w", err) } var freeRoot, mainRoot uint32 @@ -1115,7 +1115,7 @@ func _conditions(f io.ReaderAt, visStream io.Writer, node *mdbx_node, _header *h func readPages(f io.ReaderAt, visStream io.Writer, pgno uint32, blockID *int, parentBlock int, level *int) error { var page [PageSize]byte if _, err := f.ReadAt(page[:], int64(pgno*PageSize)); err != nil { - return fmt.Errorf("reading page: %v, error: %v", pgno, err) + return fmt.Errorf("reading page: %v, error: %w", pgno, err) } _header := new(header) @@ -1193,7 +1193,7 @@ func readPages(f io.ReaderAt, visStream io.Writer, pgno uint32, blockID *int, pa func freeDBPages(f io.ReaderAt, visStream io.Writer, freeRoot uint32) error { var page [PageSize]byte if _, err := f.ReadAt(page[:], int64(freeRoot*PageSize)); err != nil { - return fmt.Errorf("reading page: %v, error: %v", freeRoot, err) + return fmt.Errorf("reading page: %v, error: %w", freeRoot, err) } _header := new(header) diff --git a/cmd/hack/hack.go b/cmd/hack/hack.go index d7f302ba3e9..dc48d772470 100644 --- a/cmd/hack/hack.go +++ b/cmd/hack/hack.go @@ -1191,7 +1191,7 @@ func mphf(chaindata string, block uint64) error { statefile := "statedump.dat" if _, err := os.Stat(statefile); err != nil { if !os.IsNotExist(err) { - return fmt.Errorf("not sure if statedump.dat exists: %v", err) + return fmt.Errorf("not sure if statedump.dat exists: %w", err) } if err = dumpState(chaindata, statefile); err != nil { return err @@ -1589,7 +1589,7 @@ func compress(chaindata string, block uint64) error { statefile := "statedump.dat" if _, err := os.Stat(statefile); err != nil { if !os.IsNotExist(err) { - return fmt.Errorf("not sure if statedump.dat exists: %v", err) + return fmt.Errorf("not sure if statedump.dat exists: %w", err) } if err = dumpState(chaindata, statefile); err != nil { return err @@ -2490,7 +2490,7 @@ func extractHeaders(chaindata string, block uint64) error { blockHash := common.BytesToHash(k[8:]) var header types.Header if err = rlp.DecodeBytes(v, &header); err != nil { - return fmt.Errorf("decoding header from %x: %v", v, err) + return fmt.Errorf("decoding header from %x: %w", v, err) } fmt.Printf("Header %d %x: stateRoot %x, parentHash %x, diff %d\n", blockNumber, blockHash, header.Root, header.ParentHash, header.Difficulty) } @@ -2664,7 +2664,7 @@ func fixTd(chaindata string) error { fmt.Printf("Missing TD record for %x, fixing\n", k) var header types.Header if err = rlp.DecodeBytes(v, &header); err != nil { - return fmt.Errorf("decoding header from %x: %v", v, err) + return fmt.Errorf("decoding header from %x: %w", v, err) } if header.Number.Uint64() == 0 { continue @@ -2674,17 +2674,17 @@ func fixTd(chaindata string) error { copy(parentK[8:], header.ParentHash[:]) var parentTdRec []byte if parentTdRec, err = tx.GetOne(kv.HeaderTD, parentK[:]); err != nil { - return fmt.Errorf("reading parentTd Rec for %d: %v", header.Number.Uint64(), err) + return fmt.Errorf("reading parentTd Rec for %d: %w", header.Number.Uint64(), err) } var parentTd big.Int if err = rlp.DecodeBytes(parentTdRec, &parentTd); err != nil { - return fmt.Errorf("decoding parent Td record for block %d, from %x: %v", header.Number.Uint64(), parentTdRec, err) + return fmt.Errorf("decoding parent Td record for block %d, from %x: %w", header.Number.Uint64(), parentTdRec, err) } var td big.Int td.Add(&parentTd, header.Difficulty) var newHv []byte if newHv, err = rlp.EncodeToBytes(&td); err != nil { - return fmt.Errorf("encoding td record for block %d: %v", header.Number.Uint64(), err) + return fmt.Errorf("encoding td record for block %d: %w", header.Number.Uint64(), err) } if err = tx.Put(kv.HeaderTD, k, newHv); err != nil { return err @@ -2781,7 +2781,7 @@ func fixState(chaindata string) error { } var header types.Header if err = rlp.DecodeBytes(hv, &header); err != nil { - return fmt.Errorf("decoding header from %x: %v", v, err) + return fmt.Errorf("decoding header from %x: %w", v, err) } if header.Number.Uint64() > 1 { var parentK [40]byte @@ -3142,10 +3142,10 @@ func scanReceipts(chaindata string, block uint64) error { buf.Reset() err := cbor.Marshal(&buf, receipts1) if err != nil { - return fmt.Errorf("encode block receipts for block %d: %v", blockNum, err) + return fmt.Errorf("encode block receipts for block %d: %w", blockNum, err) } if err = tx.Put(kv.Receipts, key[:], buf.Bytes()); err != nil { - return fmt.Errorf("writing receipts for block %d: %v", blockNum, err) + return fmt.Errorf("writing receipts for block %d: %w", blockNum, err) } if _, err = w.Write([]byte(fmt.Sprintf("%d\n", blockNum))); err != nil { return err @@ -3172,7 +3172,7 @@ func runBlock(ibs *state.IntraBlockState, txnWriter state.StateWriter, blockWrit ibs.Prepare(tx.Hash(), block.Hash(), i) receipt, _, err := core.ApplyTransaction(chainConfig, getHeader, engine, nil, gp, ibs, txnWriter, header, tx, usedGas, vmConfig, contractHasTEVM) if err != nil { - return nil, fmt.Errorf("could not apply tx %d [%x] failed: %v", i, tx.Hash(), err) + return nil, fmt.Errorf("could not apply tx %d [%x] failed: %w", i, tx.Hash(), err) } receipts = append(receipts, receipt) //fmt.Printf("%d, cumulative gas: %d\n", i, receipt.CumulativeGasUsed) @@ -3181,11 +3181,11 @@ func runBlock(ibs *state.IntraBlockState, txnWriter state.StateWriter, blockWrit if !vmConfig.ReadOnly { // Finalize the block, applying any consensus engine specific extras (e.g. block rewards) if _, err := engine.FinalizeAndAssemble(chainConfig, header, ibs, block.Transactions(), block.Uncles(), receipts, nil, nil, nil, nil); err != nil { - return nil, fmt.Errorf("finalize of block %d failed: %v", block.NumberU64(), err) + return nil, fmt.Errorf("finalize of block %d failed: %w", block.NumberU64(), err) } if err := ibs.CommitBlock(rules, blockWriter); err != nil { - return nil, fmt.Errorf("committing block %d failed: %v", block.NumberU64(), err) + return nil, fmt.Errorf("committing block %d failed: %w", block.NumberU64(), err) } } diff --git a/cmd/rpcdaemon/commands/erigon_receipts.go b/cmd/rpcdaemon/commands/erigon_receipts.go index b014b1e30e6..b8d4ead38c6 100644 --- a/cmd/rpcdaemon/commands/erigon_receipts.go +++ b/cmd/rpcdaemon/commands/erigon_receipts.go @@ -30,7 +30,7 @@ func (api *ErigonImpl) GetLogsByHash(ctx context.Context, hash common.Hash) ([][ } receipts, err := getReceipts(ctx, tx, chainConfig, block, block.Body().SendersFromTxs()) if err != nil { - return nil, fmt.Errorf("getReceipts error: %v", err) + return nil, fmt.Errorf("getReceipts error: %w", err) } logs := make([][]*types.Log, len(receipts)) @@ -55,7 +55,7 @@ func (api *ErigonImpl) GetLogsByHash(ctx context.Context, hash common.Hash) ([][ // receipts, err := getReceipts(ctx, tx, *number, hash) // if err != nil { -// return nil, fmt.Errorf("getReceipts error: %v", err) +// return nil, fmt.Errorf("getReceipts error: %w", err) // } // logs := make([][]*types.Log, len(receipts)) diff --git a/cmd/rpcdaemon/commands/eth_accounts.go b/cmd/rpcdaemon/commands/eth_accounts.go index f0dd9f2aa4f..d0089389e05 100644 --- a/cmd/rpcdaemon/commands/eth_accounts.go +++ b/cmd/rpcdaemon/commands/eth_accounts.go @@ -17,7 +17,7 @@ import ( func (api *APIImpl) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) { tx, err1 := api.db.BeginRo(ctx) if err1 != nil { - return nil, fmt.Errorf("getBalance cannot open tx: %v", err1) + return nil, fmt.Errorf("getBalance cannot open tx: %w", err1) } defer tx.Rollback() blockNumber, _, err := rpchelper.GetBlockNumber(blockNrOrHash, tx, api.filters) @@ -41,7 +41,7 @@ func (api *APIImpl) GetBalance(ctx context.Context, address common.Address, bloc func (api *APIImpl) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) { tx, err1 := api.db.BeginRo(ctx) if err1 != nil { - return nil, fmt.Errorf("getTransactionCount cannot open tx: %v", err1) + return nil, fmt.Errorf("getTransactionCount cannot open tx: %w", err1) } defer tx.Rollback() blockNumber, _, err := rpchelper.GetBlockNumber(blockNrOrHash, tx, api.filters) @@ -61,7 +61,7 @@ func (api *APIImpl) GetTransactionCount(ctx context.Context, address common.Addr func (api *APIImpl) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { tx, err1 := api.db.BeginRo(ctx) if err1 != nil { - return nil, fmt.Errorf("getCode cannot open tx: %v", err1) + return nil, fmt.Errorf("getCode cannot open tx: %w", err1) } defer tx.Rollback() blockNumber, _, err := rpchelper.GetBlockNumber(blockNrOrHash, tx, api.filters) diff --git a/cmd/rpcdaemon/commands/eth_receipts.go b/cmd/rpcdaemon/commands/eth_receipts.go index 1f0e281d793..6910b7004ac 100644 --- a/cmd/rpcdaemon/commands/eth_receipts.go +++ b/cmd/rpcdaemon/commands/eth_receipts.go @@ -262,7 +262,7 @@ func (api *APIImpl) GetTransactionReceipt(ctx context.Context, hash common.Hash) } receipts, err := getReceipts(ctx, tx, cc, block, block.Body().SendersFromTxs()) if err != nil { - return nil, fmt.Errorf("getReceipts error: %v", err) + return nil, fmt.Errorf("getReceipts error: %w", err) } if len(receipts) <= int(txIndex) { return nil, fmt.Errorf("block has less receipts than expected: %d <= %d, block: %d", len(receipts), int(txIndex), blockNumber) @@ -295,7 +295,7 @@ func (api *APIImpl) GetBlockReceipts(ctx context.Context, number rpc.BlockNumber } receipts, err := getReceipts(ctx, tx, chainConfig, block, block.Body().SendersFromTxs()) if err != nil { - return nil, fmt.Errorf("getReceipts error: %v", err) + return nil, fmt.Errorf("getReceipts error: %w", err) } result := make([]map[string]interface{}, 0, len(receipts)) for _, receipt := range receipts { diff --git a/cmd/rpcdaemon/commands/rpc_block.go b/cmd/rpcdaemon/commands/rpc_block.go index 2465831c01e..b24451c538b 100644 --- a/cmd/rpcdaemon/commands/rpc_block.go +++ b/cmd/rpcdaemon/commands/rpc_block.go @@ -28,7 +28,7 @@ func getBlockNumber(number rpc.BlockNumber, tx kv.Tx) (uint64, error) { func getLatestBlockNumber(tx kv.Tx) (uint64, error) { blockNum, err := stages.GetStageProgress(tx, stages.Execution) if err != nil { - return 0, fmt.Errorf("getting latest block number: %v", err) + return 0, fmt.Errorf("getting latest block number: %w", err) } return blockNum, nil diff --git a/cmd/rpcdaemon/commands/storage_range.go b/cmd/rpcdaemon/commands/storage_range.go index 69d8f0f0025..141be618bbc 100644 --- a/cmd/rpcdaemon/commands/storage_range.go +++ b/cmd/rpcdaemon/commands/storage_range.go @@ -36,7 +36,7 @@ func StorageRangeAt(stateReader *state.PlainState, contractAddress common.Addres resultCount++ return resultCount <= maxResult }, maxResult+1); err != nil { - return StorageRangeResult{}, fmt.Errorf("error walking over storage: %v", err) + return StorageRangeResult{}, fmt.Errorf("error walking over storage: %w", err) } return result, nil } diff --git a/cmd/rpcdaemon/commands/trace_filtering.go b/cmd/rpcdaemon/commands/trace_filtering.go index ed7388f3c5a..05a24c5791c 100644 --- a/cmd/rpcdaemon/commands/trace_filtering.go +++ b/cmd/rpcdaemon/commands/trace_filtering.go @@ -199,7 +199,7 @@ func (api *TraceAPIImpl) Filter(ctx context.Context, req TraceFilterRequest, str dbtx, err1 := api.kv.BeginRo(ctx) if err1 != nil { stream.WriteNil() - return fmt.Errorf("traceFilter cannot open tx: %v", err1) + return fmt.Errorf("traceFilter cannot open tx: %w", err1) } defer dbtx.Rollback() diff --git a/cmd/rpctest/rpctest/utils.go b/cmd/rpctest/rpctest/utils.go index 7bade8a5161..bec1c14690f 100644 --- a/cmd/rpctest/rpctest/utils.go +++ b/cmd/rpctest/rpctest/utils.go @@ -223,7 +223,7 @@ func requestAndCompare(request string, methodName string, errCtx string, reqGen oeRespFile, _ := os.Create("oe-response.json") //nolint:errcheck oeRespFile.Write(resg.Response) //nolint:errcheck oeRespFile.Close() //nolint:errcheck - return fmt.Errorf("different results for method %s, errCtx %s: %v\nRequest in file request.json, Erigon response in file erigon-response.json, Geth/OE response in file oe-response.json", methodName, errCtx, err) + return fmt.Errorf("different results for method %s, errCtx %s: %w\nRequest in file request.json, Erigon response in file erigon-response.json, Geth/OE response in file oe-response.json", methodName, errCtx, err) } } } diff --git a/cmd/snapshots/generator/commands/generate_body_snapshot.go b/cmd/snapshots/generator/commands/generate_body_snapshot.go index 8a601488c09..ced7d4c7a17 100644 --- a/cmd/snapshots/generator/commands/generate_body_snapshot.go +++ b/cmd/snapshots/generator/commands/generate_body_snapshot.go @@ -61,7 +61,7 @@ func BodySnapshot(ctx context.Context, logger log.Logger, dbPath, snapshotPath s hash, err = rawdb.ReadCanonicalHash(tx, i) if err != nil { - return fmt.Errorf("getting canonical hash for block %d: %v", i, err) + return fmt.Errorf("getting canonical hash for block %d: %w", i, err) } body := rawdb.ReadBodyRLP(tx, hash, i) if err = sntx.Put(kv.BlockBody, dbutils.BlockBodyKey(i, hash), body); err != nil { diff --git a/cmd/snapshots/generator/commands/generate_header_snapshot.go b/cmd/snapshots/generator/commands/generate_header_snapshot.go index 750e3d66ab8..4f15f42cc7a 100644 --- a/cmd/snapshots/generator/commands/generate_header_snapshot.go +++ b/cmd/snapshots/generator/commands/generate_header_snapshot.go @@ -77,7 +77,7 @@ func HeaderSnapshot(ctx context.Context, logger log.Logger, dbPath, snapshotPath hash, err = rawdb.ReadCanonicalHash(tx, i) if err != nil { - return fmt.Errorf("getting canonical hash for block %d: %v", i, err) + return fmt.Errorf("getting canonical hash for block %d: %w", i, err) } header = rawdb.ReadHeaderRLP(tx, hash, i) if len(header) == 0 { diff --git a/cmd/snapshots/generator/commands/generate_state_snapshot.go b/cmd/snapshots/generator/commands/generate_state_snapshot.go index 45490e8c475..d3566c8a991 100644 --- a/cmd/snapshots/generator/commands/generate_state_snapshot.go +++ b/cmd/snapshots/generator/commands/generate_state_snapshot.go @@ -96,7 +96,7 @@ func GenerateStateSnapshot(ctx context.Context, logger log.Logger, dbPath, snaps var acc accounts.Account if err = acc.DecodeForStorage(v); err != nil { - return false, fmt.Errorf("decoding %x for %x: %v", v, k, err) + return false, fmt.Errorf("decoding %x for %x: %w", v, k, err) } if acc.Incarnation > 0 { @@ -125,7 +125,7 @@ func GenerateStateSnapshot(ctx context.Context, logger log.Logger, dbPath, snaps if acc.IsEmptyCodeHash() { codeHash, err1 := tx2.GetOne(kv.PlainContractCode, storagePrefix) if err1 != nil && errors.Is(err1, ethdb.ErrKeyNotFound) { - return false, fmt.Errorf("getting code hash for %x: %v", k, err1) + return false, fmt.Errorf("getting code hash for %x: %w", k, err1) } if len(codeHash) > 0 { code, err1 := tx2.GetOne(kv.Code, codeHash) diff --git a/cmd/snapshots/tracker/commands/root.go b/cmd/snapshots/tracker/commands/root.go index 6c443015e41..89b4569f2db 100644 --- a/cmd/snapshots/tracker/commands/root.go +++ b/cmd/snapshots/tracker/commands/root.go @@ -343,7 +343,7 @@ func ParseRequest(r *http.Request) (AnnounceReq, error) { } port, err := strconv.Atoi(q.Get("port")) if err != nil { - return AnnounceReq{}, fmt.Errorf("port: %v - %w", q.Get("port"), err) + return AnnounceReq{}, fmt.Errorf("port: %v - %w", q.Get("port"), err) } res := AnnounceReq{ diff --git a/cmd/state/commands/opcode_tracer.go b/cmd/state/commands/opcode_tracer.go index 379140c96d6..557ee5b7cea 100644 --- a/cmd/state/commands/opcode_tracer.go +++ b/cmd/state/commands/opcode_tracer.go @@ -681,7 +681,7 @@ func runBlock(ibs *state.IntraBlockState, txnWriter state.StateWriter, blockWrit ibs.Prepare(tx.Hash(), block.Hash(), i) receipt, _, err := core.ApplyTransaction(chainConfig, getHeader, engine, nil, gp, ibs, txnWriter, header, tx, usedGas, vmConfig, contractHasTEVM) if err != nil { - return nil, fmt.Errorf("could not apply tx %d [%x] failed: %v", i, tx.Hash(), err) + return nil, fmt.Errorf("could not apply tx %d [%x] failed: %w", i, tx.Hash(), err) } receipts = append(receipts, receipt) } @@ -689,11 +689,11 @@ func runBlock(ibs *state.IntraBlockState, txnWriter state.StateWriter, blockWrit if !vmConfig.ReadOnly { // Finalize the block, applying any consensus engine specific extras (e.g. block rewards) if _, err := engine.FinalizeAndAssemble(chainConfig, header, ibs, block.Transactions(), block.Uncles(), receipts, nil, nil, nil, nil); err != nil { - return nil, fmt.Errorf("finalize of block %d failed: %v", block.NumberU64(), err) + return nil, fmt.Errorf("finalize of block %d failed: %w", block.NumberU64(), err) } if err := ibs.CommitBlock(rules, blockWriter); err != nil { - return nil, fmt.Errorf("committing block %d failed: %v", block.NumberU64(), err) + return nil, fmt.Errorf("committing block %d failed: %w", block.NumberU64(), err) } } diff --git a/cmd/utils/diskusage_windows.go b/cmd/utils/diskusage_windows.go index 9bf7740b994..75e76500ded 100644 --- a/cmd/utils/diskusage_windows.go +++ b/cmd/utils/diskusage_windows.go @@ -26,12 +26,12 @@ func getFreeDiskSpace(path string) (uint64, error) { cwd, err := windows.UTF16PtrFromString(path) if err != nil { - return 0, fmt.Errorf("failed to call UTF16PtrFromString: %v", err) + return 0, fmt.Errorf("failed to call UTF16PtrFromString: %w", err) } var freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes uint64 if err := windows.GetDiskFreeSpaceEx(cwd, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes); err != nil { - return 0, fmt.Errorf("failed to call GetDiskFreeSpaceEx: %v", err) + return 0, fmt.Errorf("failed to call GetDiskFreeSpaceEx: %w", err) } return freeBytesAvailableToCaller, nil diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index e0b21c32abd..3ffb1ccaca3 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -732,7 +732,7 @@ func NewP2PConfig(nodiscover bool, datadir, netRestrict, natSetting, nodeName st } natif, err := nat.Parse(natSetting) if err != nil { - return nil, fmt.Errorf("invalid nat option %s: %v", natSetting, err) + return nil, fmt.Errorf("invalid nat option %s: %w", natSetting, err) } cfg.NAT = natif return cfg, nil diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index 3e457cbd5f5..0e50cd18a86 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -137,7 +137,7 @@ func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, erro cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { - return nil, fmt.Errorf("solc: %v\n%s", err, stderr.Bytes()) + return nil, fmt.Errorf("solc: %w\n%s", err, stderr.Bytes()) } return ParseCombinedJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " ")) } @@ -163,7 +163,7 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin // Parse the individual compilation results. var abi interface{} if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil { - return nil, fmt.Errorf("solc: error reading abi definition (%v)", err) + return nil, fmt.Errorf("solc: error reading abi definition (%w)", err) } var userdoc, devdoc interface{} json.Unmarshal([]byte(info.Userdoc), &userdoc) diff --git a/common/compiler/vyper.go b/common/compiler/vyper.go index fb1f98d863e..dd588260b09 100644 --- a/common/compiler/vyper.go +++ b/common/compiler/vyper.go @@ -92,7 +92,7 @@ func (s *Vyper) run(cmd *exec.Cmd, source string) (map[string]*Contract, error) cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { - return nil, fmt.Errorf("vyper: %v\n%s", err, stderr.Bytes()) + return nil, fmt.Errorf("vyper: %w\n%s", err, stderr.Bytes()) } return ParseVyperJSON(stdout.Bytes(), source, s.Version, s.Version, strings.Join(s.makeArgs(), " ")) diff --git a/common/test_utils.go b/common/test_utils.go index a848642f77f..8e182792b94 100644 --- a/common/test_utils.go +++ b/common/test_utils.go @@ -31,9 +31,9 @@ func LoadJSON(file string, val interface{}) error { if err := json.Unmarshal(content, val); err != nil { if syntaxerr, ok := err.(*json.SyntaxError); ok { line := findLine(content, syntaxerr.Offset) - return fmt.Errorf("JSON syntax error at %v:%v: %v", file, line, err) + return fmt.Errorf("JSON syntax error at %v:%v: %w", file, line, err) } - return fmt.Errorf("JSON unmarshal error in %v: %v", file, err) + return fmt.Errorf("JSON unmarshal error in %v: %w", file, err) } return nil } diff --git a/core/blockchain.go b/core/blockchain.go index b8f99ad8550..fdc2e0a4115 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -266,7 +266,7 @@ func FinalizeBlockExecution(engine consensus.Engine, stateReader state.StateRead } if err := ibs.CommitBlock(cc.Rules(header.Number.Uint64()), stateWriter); err != nil { - return fmt.Errorf("committing block %d failed: %v", header.Number.Uint64(), err) + return fmt.Errorf("committing block %d failed: %w", header.Number.Uint64(), err) } if originalSystemAcc != nil { // hack for Sokol - don't understand why eip158 is enabled, but OE still save SystemAddress with nonce=0 @@ -278,7 +278,7 @@ func FinalizeBlockExecution(engine consensus.Engine, stateReader state.StateRead } if err := stateWriter.WriteChangeSets(); err != nil { - return fmt.Errorf("writing changesets for block %d failed: %v", header.Number.Uint64(), err) + return fmt.Errorf("writing changesets for block %d failed: %w", header.Number.Uint64(), err) } return nil } diff --git a/core/genesis.go b/core/genesis.go index fd4f5893838..65f7fb03443 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -429,13 +429,13 @@ func (g *Genesis) WriteGenesisState(tx kv.RwTx) (*types.Block, *state.IntraBlock blockWriter := state.NewPlainStateWriter(tx, tx, 0) if err := statedb.CommitBlock(params.Rules{}, blockWriter); err != nil { - return nil, statedb, fmt.Errorf("cannot write state: %v", err) + return nil, statedb, fmt.Errorf("cannot write state: %w", err) } if err := blockWriter.WriteChangeSets(); err != nil { - return nil, statedb, fmt.Errorf("cannot write change sets: %v", err) + return nil, statedb, fmt.Errorf("cannot write change sets: %w", err) } if err := blockWriter.WriteHistory(); err != nil { - return nil, statedb, fmt.Errorf("cannot write history: %v", err) + return nil, statedb, fmt.Errorf("cannot write history: %w", err) } return block, statedb, nil } diff --git a/core/rawdb/accessors_chain.go b/core/rawdb/accessors_chain.go index 71db385d8d3..0441c848a75 100644 --- a/core/rawdb/accessors_chain.go +++ b/core/rawdb/accessors_chain.go @@ -641,22 +641,22 @@ func WriteReceipts(tx kv.Putter, number uint64, receipts types.Receipts) error { buf.Reset() err := cbor.Marshal(buf, r.Logs) if err != nil { - return fmt.Errorf("encode block logs for block %d: %v", number, err) + return fmt.Errorf("encode block logs for block %d: %w", number, err) } if err = tx.Put(kv.Log, dbutils.LogKey(number, uint32(txId)), buf.Bytes()); err != nil { - return fmt.Errorf("writing logs for block %d: %v", number, err) + return fmt.Errorf("writing logs for block %d: %w", number, err) } } buf.Reset() err := cbor.Marshal(buf, receipts) if err != nil { - return fmt.Errorf("encode block receipts for block %d: %v", number, err) + return fmt.Errorf("encode block receipts for block %d: %w", number, err) } if err = tx.Put(kv.Receipts, dbutils.EncodeBlockNumber(number), buf.Bytes()); err != nil { - return fmt.Errorf("writing receipts for block %d: %v", number, err) + return fmt.Errorf("writing receipts for block %d: %w", number, err) } return nil } @@ -673,22 +673,22 @@ func AppendReceipts(tx kv.RwTx, blockNumber uint64, receipts types.Receipts) err buf.Reset() err := cbor.Marshal(buf, r.Logs) if err != nil { - return fmt.Errorf("encode block receipts for block %d: %v", blockNumber, err) + return fmt.Errorf("encode block receipts for block %d: %w", blockNumber, err) } if err = tx.Append(kv.Log, dbutils.LogKey(blockNumber, uint32(txId)), buf.Bytes()); err != nil { - return fmt.Errorf("writing receipts for block %d: %v", blockNumber, err) + return fmt.Errorf("writing receipts for block %d: %w", blockNumber, err) } } buf.Reset() err := cbor.Marshal(buf, receipts) if err != nil { - return fmt.Errorf("encode block receipts for block %d: %v", blockNumber, err) + return fmt.Errorf("encode block receipts for block %d: %w", blockNumber, err) } if err = tx.Append(kv.Receipts, dbutils.EncodeBlockNumber(blockNumber), buf.Bytes()); err != nil { - return fmt.Errorf("writing receipts for block %d: %v", blockNumber, err) + return fmt.Errorf("writing receipts for block %d: %w", blockNumber, err) } return nil } diff --git a/core/state/database_test.go b/core/state/database_test.go index 905461901b2..0a1068f8cca 100644 --- a/core/state/database_test.go +++ b/core/state/database_test.go @@ -1296,7 +1296,7 @@ func TestChangeAccountCodeBetweenBlocks(t *testing.T) { intraBlockState.SetCode(contract, oldCode) intraBlockState.AddBalance(contract, uint256.NewInt(1000000000)) if err := intraBlockState.FinalizeTx(params.Rules{}, tsw); err != nil { - t.Errorf("error finalising 1st tx: %w", err) + t.Errorf("error finalising 1st tx: %v", err) } _, err := trie.CalcRoot("test", tx) require.NoError(t, err) diff --git a/core/state/dump.go b/core/state/dump.go index c0427f56564..e46f25593be 100644 --- a/core/state/dump.go +++ b/core/state/dump.go @@ -155,7 +155,7 @@ func (d *Dumper) DumpToCollector(c DumpCollector, excludeCode, excludeStorage bo return true, nil } if e := acc.DecodeForStorage(v); e != nil { - return false, fmt.Errorf("decoding %x for %x: %v", v, k, e) + return false, fmt.Errorf("decoding %x for %x: %w", v, k, e) } account := DumpAccount{ Balance: acc.Balance.ToBig().String(), @@ -181,7 +181,7 @@ func (d *Dumper) DumpToCollector(c DumpCollector, excludeCode, excludeStorage bo if incarnation > 0 { codeHash, err := d.db.GetOne(kv.PlainContractCode, storagePrefix) if err != nil { - return nil, fmt.Errorf("getting code hash for %x: %v", addr, err) + return nil, fmt.Errorf("getting code hash for %x: %w", addr, err) } if codeHash != nil { account.CodeHash = codeHash @@ -211,7 +211,7 @@ func (d *Dumper) DumpToCollector(c DumpCollector, excludeCode, excludeStorage bo t.Update(h.Bytes(), common.CopyBytes(vs)) return true, nil }); err != nil { - return nil, fmt.Errorf("walking over storage for %x: %v", addr, err) + return nil, fmt.Errorf("walking over storage for %x: %w", addr, err) } account.Root = t.Hash().Bytes() } diff --git a/core/state/intra_block_state_test.go b/core/state/intra_block_state_test.go index 3b6c0b4be75..8074095c3d3 100644 --- a/core/state/intra_block_state_test.go +++ b/core/state/intra_block_state_test.go @@ -248,7 +248,7 @@ func (test *snapshotTest) run() bool { } state.RevertToSnapshot(snapshotRevs[sindex]) if err := test.checkEqual(state, checkstate); err != nil { - test.err = fmt.Errorf("state mismatch after revert to snapshot %d\n%v", sindex, err) + test.err = fmt.Errorf("state mismatch after revert to snapshot %d\n%w", sindex, err) return false } } diff --git a/core/state/state_object.go b/core/state/state_object.go index d6617d17701..55d416d0a1a 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -328,7 +328,7 @@ func (so *stateObject) Code() []byte { } code, err := so.db.stateReader.ReadAccountCode(so.Address(), so.data.Incarnation, common.BytesToHash(so.CodeHash())) if err != nil { - so.setError(fmt.Errorf("can't load code hash %x: %v", so.CodeHash(), err)) + so.setError(fmt.Errorf("can't load code hash %x: %w", so.CodeHash(), err)) } so.code = code return code diff --git a/core/types/receipt.go b/core/types/receipt.go index 6392dd17077..68dc6ab98bf 100644 --- a/core/types/receipt.go +++ b/core/types/receipt.go @@ -38,8 +38,6 @@ var ( receiptStatusSuccessfulRLP = []byte{0x01} ) -var errEmptyTypedReceipt = errors.New("empty typed receipt bytes") - const ( // ReceiptStatusFailed is the status code of a transaction if execution failed. ReceiptStatusFailed = uint64(0) @@ -244,7 +242,7 @@ func (r *Receipt) DecodeRLP(s *rlp.Stream) error { return fmt.Errorf("read TxType: %w", err) } if len(b) != 1 { - return fmt.Errorf("only 1-byte tx type prefix is supported, got %d bytes: %w", len(b), errEmptyTypedReceipt) + return fmt.Errorf("%w, got %d bytes", rlp.ErrWrongTxTypePrefix, len(b)) } r.Type = b[0] switch r.Type { diff --git a/core/types/transaction.go b/core/types/transaction.go index 75808a6247d..4dfc74f262c 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -122,7 +122,7 @@ func DecodeTransaction(s *rlp.Stream) (Transaction, error) { return nil, err } if len(b) != 1 { - return nil, fmt.Errorf("only 1-byte tx type prefix is supported, got %d bytes", len(b)) + return nil, fmt.Errorf("%w, got %d bytes", rlp.ErrWrongTxTypePrefix, len(b)) } var tx Transaction switch b[0] { @@ -139,7 +139,7 @@ func DecodeTransaction(s *rlp.Stream) (Transaction, error) { } tx = t default: - return nil, fmt.Errorf("unknown tx type prefix: %d", b[0]) + return nil, fmt.Errorf("%w, got: %d", rlp.ErrUnknownTxTypePrefix, b[0]) } if kind == rlp.String { if err = s.ListEnd(); err != nil { diff --git a/eth/api_backend.go b/eth/api_backend.go index 9ee6f233a29..d1c055c8de3 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -191,7 +191,7 @@ func (b *EthAPIBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*typ } receipts, err := b.GetReceipts(ctx, hash) if err != nil { - return nil, fmt.Errorf("getReceipt error: %v", err) + return nil, fmt.Errorf("getReceipt error: %w", err) } if receipts == nil { return nil, nil diff --git a/eth/backend.go b/eth/backend.go index 6dbe22b5e73..88d57a594d0 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -663,12 +663,12 @@ func (s *Ethereum) StartMining(ctx context.Context, db kv.RwDB, mining *stagedsy eb, err := s.Etherbase() if err != nil { log.Error("Cannot start mining without etherbase", "err", err) - return fmt.Errorf("etherbase missing: %v", err) + return fmt.Errorf("etherbase missing: %w", err) } if clique, ok := s.engine.(*clique.Clique); ok { if cfg.SigKey == nil { log.Error("Etherbase account unavailable locally", "err", err) - return fmt.Errorf("signer missing: %v", err) + return fmt.Errorf("signer missing: %w", err) } clique.Authorize(eb, func(_ common.Address, mimeType string, message []byte) ([]byte, error) { diff --git a/eth/filters/api.go b/eth/filters/api.go index aa5d851dbc0..81325f650e9 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -504,7 +504,7 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { if strAddr, ok := addr.(string); ok { addr, err := decodeAddress(strAddr) if err != nil { - return fmt.Errorf("invalid address at index %d: %v", i, err) + return fmt.Errorf("invalid address at index %d: %w", i, err) } args.Addresses = append(args.Addresses, addr) } else { @@ -514,7 +514,7 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { case string: addr, err := decodeAddress(rawAddr) if err != nil { - return fmt.Errorf("invalid address: %v", err) + return fmt.Errorf("invalid address: %w", err) } args.Addresses = []common.Address{addr} default: diff --git a/eth/tracers/internal/tracers/assets.go b/eth/tracers/internal/tracers/assets.go index 7f45ab286e7..fa4e2df9433 100644 --- a/eth/tracers/internal/tracers/assets.go +++ b/eth/tracers/internal/tracers/assets.go @@ -265,7 +265,7 @@ func Asset(name string) ([]byte, error) { if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { - return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) + return nil, fmt.Errorf("Asset %s can't read by error: %w", name, err) } return a.bytes, nil } @@ -303,7 +303,7 @@ func AssetInfo(name string) (os.FileInfo, error) { if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { - return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) + return nil, fmt.Errorf("AssetInfo %s can't read by error: %w", name, err) } return a.info, nil } @@ -317,7 +317,7 @@ func AssetDigest(name string) ([sha256.Size]byte, error) { if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { - return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s can't read by error: %v", name, err) + return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s can't read by error: %w", name, err) } return a.digest, nil } diff --git a/internal/build/archive.go b/internal/build/archive.go index 8b3ac23d1d8..6db519bd2af 100644 --- a/internal/build/archive.go +++ b/internal/build/archive.go @@ -122,13 +122,13 @@ func (a *ZipArchive) Directory(name string) error { func (a *ZipArchive) Header(fi os.FileInfo) (io.Writer, error) { head, err := zip.FileInfoHeader(fi) if err != nil { - return nil, fmt.Errorf("can't make zip header: %v", err) + return nil, fmt.Errorf("can't make zip header: %w", err) } head.Name = a.dir + head.Name head.Method = zip.Deflate w, err := a.zipw.CreateHeader(head) if err != nil { - return nil, fmt.Errorf("can't add zip header: %v", err) + return nil, fmt.Errorf("can't add zip header: %w", err) } return w, nil } @@ -165,11 +165,11 @@ func (a *TarballArchive) Directory(name string) error { func (a *TarballArchive) Header(fi os.FileInfo) (io.Writer, error) { head, err := tar.FileInfoHeader(fi, "") if err != nil { - return nil, fmt.Errorf("can't make tar header: %v", err) + return nil, fmt.Errorf("can't make tar header: %w", err) } head.Name = a.dir + head.Name if err := a.tarw.WriteHeader(head); err != nil { - return nil, fmt.Errorf("can't add tar header: %v", err) + return nil, fmt.Errorf("can't add tar header: %w", err) } return a.tarw, nil } @@ -226,7 +226,7 @@ func extractTarball(ar io.Reader, dest string) error { armode := header.FileInfo().Mode() err := extractFile(header.Name, armode, tr, dest) if err != nil { - return fmt.Errorf("extract %s: %v", header.Name, err) + return fmt.Errorf("extract %s: %w", header.Name, err) } } } @@ -255,7 +255,7 @@ func extractZip(ar *os.File, dest string) error { err = extractFile(zf.Name, zf.Mode(), data, dest) data.Close() if err != nil { - return fmt.Errorf("extract %s: %v", zf.Name, err) + return fmt.Errorf("extract %s: %w", zf.Name, err) } } return nil diff --git a/internal/build/download.go b/internal/build/download.go index abdc60b2401..c25cefa93bd 100644 --- a/internal/build/download.go +++ b/internal/build/download.go @@ -84,7 +84,7 @@ func (db *ChecksumDB) DownloadFile(url, dstPath string) error { resp, respErr := http.Get(url) if respErr != nil { - return fmt.Errorf("download error: %v", respErr) + return fmt.Errorf("download error: %w", respErr) } else if resp.StatusCode != http.StatusOK { return fmt.Errorf("download error: status %d", resp.StatusCode) } diff --git a/internal/build/util.go b/internal/build/util.go index 1f8d3a0d1ed..07da06b594a 100644 --- a/internal/build/util.go +++ b/internal/build/util.go @@ -154,7 +154,7 @@ func UploadSFTP(identityFile, host, dir string, files []string) error { stdin, err := sftp.StdinPipe() if err != nil { - return fmt.Errorf("can't create stdin pipe for sftp: %v", err) + return fmt.Errorf("can't create stdin pipe for sftp: %w", err) } if err := sftp.Start(); err != nil { return err diff --git a/internal/jsre/deps/bindata.go b/internal/jsre/deps/bindata.go index a6545b7140d..f8883aaea2e 100644 --- a/internal/jsre/deps/bindata.go +++ b/internal/jsre/deps/bindata.go @@ -19,7 +19,7 @@ import ( func bindataRead(data []byte, name string) ([]byte, error) { gz, err := gzip.NewReader(bytes.NewBuffer(data)) if err != nil { - return nil, fmt.Errorf("read %q: %v", name, err) + return nil, fmt.Errorf("read %q: %w", name, err) } var buf bytes.Buffer @@ -27,7 +27,7 @@ func bindataRead(data []byte, name string) ([]byte, error) { clErr := gz.Close() if err != nil { - return nil, fmt.Errorf("read %q: %v", name, err) + return nil, fmt.Errorf("read %q: %w", name, err) } if clErr != nil { return nil, err @@ -126,7 +126,7 @@ func Asset(name string) ([]byte, error) { if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { - return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) + return nil, fmt.Errorf("Asset %s can't read by error: %w", name, err) } return a.bytes, nil } @@ -152,7 +152,7 @@ func AssetInfo(name string) (os.FileInfo, error) { if f, ok := _bindata[canonicalName]; ok { a, err := f() if err != nil { - return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) + return nil, fmt.Errorf("AssetInfo %s can't read by error: %w", name, err) } return a.info, nil } diff --git a/internal/jsre/jsre.go b/internal/jsre/jsre.go index aa6f1afac08..9fb2257d6a1 100644 --- a/internal/jsre/jsre.go +++ b/internal/jsre/jsre.go @@ -295,11 +295,11 @@ func (re *JSRE) loadScript(call Call) (goja.Value, error) { file = common.AbsolutePath(re.assetPath, file) source, err := ioutil.ReadFile(file) if err != nil { - return nil, fmt.Errorf("could not read file %s: %v", file, err) + return nil, fmt.Errorf("could not read file %s: %w", file, err) } value, err := compileAndRun(re.vm, file, string(source)) if err != nil { - return nil, fmt.Errorf("error while compiling or running script: %v", err) + return nil, fmt.Errorf("error while compiling or running script: %w", err) } return value, nil } diff --git a/migrations/receipt_repair.go b/migrations/receipt_repair.go index 8cf8055c6ff..d1ee62d594d 100644 --- a/migrations/receipt_repair.go +++ b/migrations/receipt_repair.go @@ -133,10 +133,10 @@ var ReceiptRepair = Migration{ buf.Reset() err := cbor.Marshal(&buf, receipts1) if err != nil { - return fmt.Errorf("encode block receipts for block %d: %v", blockNum, err) + return fmt.Errorf("encode block receipts for block %d: %w", blockNum, err) } if err = tx.Put(kv.Receipts, key[:], buf.Bytes()); err != nil { - return fmt.Errorf("writing receipts for block %d: %v", blockNum, err) + return fmt.Errorf("writing receipts for block %d: %w", blockNum, err) } fixedCount++ } @@ -163,7 +163,7 @@ func runBlock(ibs *state.IntraBlockState, txnWriter state.StateWriter, blockWrit ibs.Prepare(tx.Hash(), block.Hash(), i) receipt, _, err := core.ApplyTransaction(chainConfig, getHeader, engine, nil, gp, ibs, txnWriter, header, tx, usedGas, vmConfig, contractHasTEVM) if err != nil { - return nil, fmt.Errorf("could not apply tx %d [%x] failed: %v", i, tx.Hash(), err) + return nil, fmt.Errorf("could not apply tx %d [%x] failed: %w", i, tx.Hash(), err) } receipts = append(receipts, receipt) } @@ -171,11 +171,11 @@ func runBlock(ibs *state.IntraBlockState, txnWriter state.StateWriter, blockWrit if !vmConfig.ReadOnly { // Finalize the block, applying any consensus engine specific extras (e.g. block rewards) if _, err := engine.FinalizeAndAssemble(chainConfig, header, ibs, block.Transactions(), block.Uncles(), receipts, nil, nil, nil, nil); err != nil { - return nil, fmt.Errorf("finalize of block %d failed: %v", block.NumberU64(), err) + return nil, fmt.Errorf("finalize of block %d failed: %w", block.NumberU64(), err) } if err := ibs.CommitBlock(chainConfig.Rules(header.Number.Uint64()), blockWriter); err != nil { - return nil, fmt.Errorf("committing block %d failed: %v", block.NumberU64(), err) + return nil, fmt.Errorf("committing block %d failed: %w", block.NumberU64(), err) } } diff --git a/node/api.go b/node/api.go index 46241c8abee..cf529e2f639 100644 --- a/node/api.go +++ b/node/api.go @@ -72,7 +72,7 @@ func (api *privateAdminAPI) AddPeer(url string) (bool, error) { // Try to add the url as a static peer and return node, err := enode.Parse(enode.ValidSchemes, url) if err != nil { - return false, fmt.Errorf("invalid enode: %v", err) + return false, fmt.Errorf("invalid enode: %w", err) } server.AddPeer(node) return true, nil @@ -88,7 +88,7 @@ func (api *privateAdminAPI) RemovePeer(url string) (bool, error) { // Try to remove the url as a static peer and return node, err := enode.Parse(enode.ValidSchemes, url) if err != nil { - return false, fmt.Errorf("invalid enode: %v", err) + return false, fmt.Errorf("invalid enode: %w", err) } server.RemovePeer(node) return true, nil @@ -103,7 +103,7 @@ func (api *privateAdminAPI) AddTrustedPeer(url string) (bool, error) { } node, err := enode.Parse(enode.ValidSchemes, url) if err != nil { - return false, fmt.Errorf("invalid enode: %v", err) + return false, fmt.Errorf("invalid enode: %w", err) } server.AddTrustedPeer(node) return true, nil @@ -119,7 +119,7 @@ func (api *privateAdminAPI) RemoveTrustedPeer(url string) (bool, error) { } node, err := enode.Parse(enode.ValidSchemes, url) if err != nil { - return false, fmt.Errorf("invalid enode: %v", err) + return false, fmt.Errorf("invalid enode: %w", err) } server.RemoveTrustedPeer(node) return true, nil diff --git a/p2p/discover/table.go b/p2p/discover/table.go index 549daa373b9..11cb0d253bd 100644 --- a/p2p/discover/table.go +++ b/p2p/discover/table.go @@ -188,7 +188,7 @@ func (tab *Table) close() { func (tab *Table) setFallbackNodes(nodes []*enode.Node) error { for _, n := range nodes { if err := n.ValidateComplete(); err != nil { - return fmt.Errorf("bad bootstrap node %q: %v", n, err) + return fmt.Errorf("bad bootstrap node %q: %w", n, err) } } tab.nursery = wrapNodes(nodes) diff --git a/p2p/discover/v4_udp.go b/p2p/discover/v4_udp.go index e084e9064f6..196c3646851 100644 --- a/p2p/discover/v4_udp.go +++ b/p2p/discover/v4_udp.go @@ -385,7 +385,7 @@ func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) { return n, nil // response record is older } if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil { - return nil, fmt.Errorf("invalid IP in response record: %v", err) + return nil, fmt.Errorf("invalid IP in response record: %w", err) } return respN, nil } diff --git a/p2p/discover/v4_udp_test.go b/p2p/discover/v4_udp_test.go index 1ddf728c6a4..834608e5e2b 100644 --- a/p2p/discover/v4_udp_test.go +++ b/p2p/discover/v4_udp_test.go @@ -102,7 +102,7 @@ func (test *udpTest) packetInFrom(wantError error, key *ecdsa.PrivateKey, addr * enc, _, err := v4wire.Encode(key, data) if err != nil { - test.t.Errorf("%s encode error: %v", data.Name(), err) + test.t.Errorf("%s encode error: %w", data.Name(), err) } test.sent = append(test.sent, enc) if err = test.udp.handlePacket(addr, enc); err != wantError { @@ -124,7 +124,7 @@ func (test *udpTest) waitPacketOut(validate interface{}) (closed bool) { } p, _, hash, err := v4wire.Decode(dgram.data) if err != nil { - test.t.Errorf("sent packet decode error: %v", err) + test.t.Errorf("sent packet decode error: %w", err) return false } fn := reflect.ValueOf(validate) diff --git a/p2p/discover/v5_udp_test.go b/p2p/discover/v5_udp_test.go index 369078118a4..5d132e6fe20 100644 --- a/p2p/discover/v5_udp_test.go +++ b/p2p/discover/v5_udp_test.go @@ -688,7 +688,7 @@ func (c *testCodec) Decode(input []byte, addr string) (enode.ID, *enode.Node, v5 func (c *testCodec) decodeFrame(input []byte) (frame testCodecFrame, p v5wire.Packet, err error) { if err = rlp.DecodeBytes(input, &frame); err != nil { - return frame, nil, fmt.Errorf("invalid frame: %v", err) + return frame, nil, fmt.Errorf("invalid frame: %w", err) } switch frame.Ptype { case v5wire.UnknownPacket: @@ -755,7 +755,7 @@ func (test *udpV5Test) packetInFrom(key *ecdsa.PrivateKey, addr *net.UDPAddr, pa codec := &testCodec{test: test, id: ln.ID()} enc, _, err := codec.Encode(test.udp.Self().ID(), addr.String(), packet, nil) if err != nil { - test.t.Errorf("%s encode error: %v", packet.Name(), err) + test.t.Errorf("%s encode error: %w", packet.Name(), err) } if test.udp.dispatchReadPacket(addr, enc) { <-test.udp.readNextCh // unblock UDPv5.dispatch @@ -807,7 +807,7 @@ func (test *udpV5Test) waitPacketOut(validate interface{}) (closed bool) { codec := &testCodec{test: test, id: ln.ID()} frame, p, err := codec.decodeFrame(dgram.data) if err != nil { - test.t.Errorf("sent packet decode error: %v", err) + test.t.Errorf("sent packet decode error: %w", err) return false } if !reflect.TypeOf(p).AssignableTo(exptype) { diff --git a/p2p/discover/v5wire/crypto.go b/p2p/discover/v5wire/crypto.go index 18c68fab183..bb3bbefa21a 100644 --- a/p2p/discover/v5wire/crypto.go +++ b/p2p/discover/v5wire/crypto.go @@ -154,11 +154,11 @@ func ecdh(privkey *ecdsa.PrivateKey, pubkey *ecdsa.PublicKey) []byte { func encryptGCM(dest, key, nonce, plaintext, authData []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { - panic(fmt.Errorf("can't create block cipher: %v", err)) + panic(fmt.Errorf("can't create block cipher: %w", err)) } aesgcm, err := cipher.NewGCMWithNonceSize(block, gcmNonceSize) if err != nil { - panic(fmt.Errorf("can't create GCM: %v", err)) + panic(fmt.Errorf("can't create GCM: %w", err)) } return aesgcm.Seal(dest, nonce, plaintext, authData), nil } diff --git a/p2p/discover/v5wire/encoding.go b/p2p/discover/v5wire/encoding.go index 9ba8c69b894..5e983d0b9a3 100644 --- a/p2p/discover/v5wire/encoding.go +++ b/p2p/discover/v5wire/encoding.go @@ -188,7 +188,7 @@ func (c *Codec) Encode(id enode.ID, addr string, packet Packet, challenge *Whoar // Generate masking IV. if err = c.sc.maskingIVGen(head.IV[:]); err != nil { - return nil, Nonce{}, fmt.Errorf("can't generate masking IV: %v", err) + return nil, Nonce{}, fmt.Errorf("can't generate masking IV: %w", err) } // Encode header data. @@ -266,7 +266,7 @@ func (c *Codec) encodeRandom(toID enode.ID) (Header, []byte, error) { // Encode auth data. auth := messageAuthData{SrcID: c.localnode.ID()} if _, err := crand.Read(head.Nonce[:]); err != nil { - return head, nil, fmt.Errorf("can't get random data: %v", err) + return head, nil, fmt.Errorf("can't get random data: %w", err) } c.headbuf.Reset() binary.Write(&c.headbuf, binary.BigEndian, auth) //nolint:errcheck @@ -318,7 +318,7 @@ func (c *Codec) encodeHandshakeHeader(toID enode.ID, addr string, challenge *Who // Generate nonce for message. nonce, err := c.sc.nextNonce(session) if err != nil { - return Header{}, nil, fmt.Errorf("can't generate nonce: %v", err) + return Header{}, nil, fmt.Errorf("can't generate nonce: %w", err) } // TODO: this should happen when the first authenticated message is received @@ -363,7 +363,7 @@ func (c *Codec) makeHandshakeAuth(toID enode.ID, addr string, challenge *Whoarey cdata := challenge.ChallengeData idsig, err := makeIDSignature(c.sha256, c.privkey, cdata, ephpubkey, toID) if err != nil { - return nil, nil, fmt.Errorf("can't sign: %v", err) + return nil, nil, fmt.Errorf("can't sign: %w", err) } auth.signature = idsig auth.h.SigSize = byte(len(auth.signature)) @@ -389,7 +389,7 @@ func (c *Codec) encodeMessageHeader(toID enode.ID, s *session) (Header, error) { // Create the header. nonce, err := c.sc.nextNonce(s) if err != nil { - return Header{}, fmt.Errorf("can't generate nonce: %v", err) + return Header{}, fmt.Errorf("can't generate nonce: %w", err) } auth := messageAuthData{SrcID: c.localnode.ID()} c.buf.Reset() @@ -572,7 +572,7 @@ func (c *Codec) decodeHandshakeRecord(local *enode.Node, wantID enode.ID, remote if local == nil || local.Seq() < record.Seq() { n, err := enode.New(enode.ValidSchemes, &record) if err != nil { - return nil, fmt.Errorf("invalid node record: %v", err) + return nil, fmt.Errorf("invalid node record: %w", err) } if n.ID() != wantID { return nil, fmt.Errorf("record in handshake has wrong ID: %v", n.ID()) diff --git a/p2p/discover/v5wire/encoding_test.go b/p2p/discover/v5wire/encoding_test.go index 26b9293dc1e..a4764dc2497 100644 --- a/p2p/discover/v5wire/encoding_test.go +++ b/p2p/discover/v5wire/encoding_test.go @@ -546,7 +546,7 @@ func (n *handshakeTestNode) encodeWithChallenge(t testing.TB, to handshakeTestNo // Encode to destination. enc, nonce, err := n.c.Encode(to.id(), to.addr(), p, challenge) if err != nil { - t.Fatal(fmt.Errorf("(%s) %v", n.ln.ID().TerminalString(), err)) + t.Fatal(fmt.Errorf("(%s) %w", n.ln.ID().TerminalString(), err)) } t.Logf("(%s) -> (%s) %s\n%s", n.ln.ID().TerminalString(), to.id().TerminalString(), p.Name(), hex.Dump(enc)) return enc, nonce @@ -557,7 +557,7 @@ func (n *handshakeTestNode) expectDecode(t *testing.T, ptype byte, p []byte) Pac dec, err := n.decode(p) if err != nil { - t.Fatal(fmt.Errorf("(%s) %v", n.ln.ID().TerminalString(), err)) + t.Fatal(fmt.Errorf("(%s) %w", n.ln.ID().TerminalString(), err)) } t.Logf("(%s) %#v", n.ln.ID().TerminalString(), pp.NewFormatter(dec)) if dec.Kind() != ptype { diff --git a/p2p/dnsdisc/client.go b/p2p/dnsdisc/client.go index 1005980e2de..1ba1378ebc8 100644 --- a/p2p/dnsdisc/client.go +++ b/p2p/dnsdisc/client.go @@ -105,7 +105,7 @@ func NewClient(cfg Config) *Client { func (c *Client) SyncTree(url string) (*Tree, error) { le, err := parseLink(url) if err != nil { - return nil, fmt.Errorf("invalid enrtree URL: %v", err) + return nil, fmt.Errorf("invalid enrtree URL: %w", err) } ct := newClientTree(c, new(linkCache), le) t := &Tree{entries: make(map[string]entry)} @@ -258,7 +258,7 @@ func (it *randomIterator) Next() bool { func (it *randomIterator) addTree(url string) error { le, err := parseLink(url) if err != nil { - return fmt.Errorf("invalid enrtree URL: %v", err) + return fmt.Errorf("invalid enrtree URL: %w", err) } it.lc.addLink("", le.str) return nil diff --git a/p2p/enode/localnode.go b/p2p/enode/localnode.go index 187d47f3cd0..741fd100cc4 100644 --- a/p2p/enode/localnode.go +++ b/p2p/enode/localnode.go @@ -274,11 +274,11 @@ func (ln *LocalNode) sign() { ln.bumpSeq() r.SetSeq(ln.seq) if err := SignV4(&r, ln.key); err != nil { - panic(fmt.Errorf("enode: can't sign record: %v", err)) + panic(fmt.Errorf("enode: can't sign record: %w", err)) } n, err := New(ValidSchemes, &r) if err != nil { - panic(fmt.Errorf("enode: can't verify local record: %v", err)) + panic(fmt.Errorf("enode: can't verify local record: %w", err)) } ln.cur.Store(n) log.Debug("New local node record", "seq", ln.seq, "id", n.ID(), "ip", n.IP(), "udp", n.UDP(), "tcp", n.TCP()) diff --git a/p2p/enode/nodedb_test.go b/p2p/enode/nodedb_test.go index e76729e5a3d..0ca44575f90 100644 --- a/p2p/enode/nodedb_test.go +++ b/p2p/enode/nodedb_test.go @@ -273,10 +273,10 @@ func testSeedQuery() error { // Insert a batch of nodes for querying for i, seed := range nodeDBSeedQueryNodes { if err := db.UpdateNode(seed.node); err != nil { - return fmt.Errorf("node %d: failed to insert: %v", i, err) + return fmt.Errorf("node %d: failed to insert: %w", i, err) } if err := db.UpdateLastPongReceived(seed.node.ID(), seed.node.IP(), seed.pong); err != nil { - return fmt.Errorf("node %d: failed to insert bondTime: %v", i, err) + return fmt.Errorf("node %d: failed to insert bondTime: %w", i, err) } } diff --git a/p2p/enr/enr.go b/p2p/enr/enr.go index 5c005209a09..10f2f79c528 100644 --- a/p2p/enr/enr.go +++ b/p2p/enr/enr.go @@ -131,7 +131,7 @@ func (r *Record) Load(e Entry) error { func (r *Record) Set(e Entry) { blob, err := rlp.EncodeToBytes(e) if err != nil { - panic(fmt.Errorf("enr: can't encode %s: %v", e.ENRKey(), err)) + panic(fmt.Errorf("enr: can't encode %s: %w", e.ENRKey(), err)) } r.invalidate() diff --git a/p2p/rlpx/rlpx.go b/p2p/rlpx/rlpx.go index c6137f47d67..b1dc199d34c 100644 --- a/p2p/rlpx/rlpx.go +++ b/p2p/rlpx/rlpx.go @@ -139,7 +139,7 @@ func (c *Conn) Read() (code uint64, data []byte, wireSize int, err error) { } code, data, err = rlp.SplitUint64(frame) if err != nil { - return 0, nil, 0, fmt.Errorf("invalid message code: %v", err) + return 0, nil, 0, fmt.Errorf("invalid message code: %w", err) } wireSize = len(data) diff --git a/p2p/simulations/adapters/exec.go b/p2p/simulations/adapters/exec.go index 924fcf651be..5b09d2b446c 100644 --- a/p2p/simulations/adapters/exec.go +++ b/p2p/simulations/adapters/exec.go @@ -224,7 +224,7 @@ func (n *ExecNode) Start(snapshots map[string][]byte) error { } client, err := rpc.DialWebsocket(ctx, status.WSEndpoint, "") if err != nil { - return fmt.Errorf("can't connect to RPC server: %v", err) + return fmt.Errorf("can't connect to RPC server: %w", err) } // Node ready :) @@ -472,7 +472,7 @@ func startExecNodeStack() (*node.Node, error) { } var conf execNodeConfig if err := json.Unmarshal([]byte(confEnv), &conf); err != nil { - return nil, fmt.Errorf("error decoding %s: %v", envNodeConfig, err) + return nil, fmt.Errorf("error decoding %s: %w", envNodeConfig, err) } // create enode record @@ -487,7 +487,7 @@ func startExecNodeStack() (*node.Node, error) { // initialize the devp2p stack stack, err := node.New(&conf.Stack) if err != nil { - return nil, fmt.Errorf("error creating node stack: %v", err) + return nil, fmt.Errorf("error creating node stack: %w", err) } // Register the services, collecting them into a map so they can @@ -520,7 +520,7 @@ func startExecNodeStack() (*node.Node, error) { }}) if err = stack.Start(); err != nil { - err = fmt.Errorf("error starting stack: %v", err) + err = fmt.Errorf("error starting stack: %w", err) } return stack, err } diff --git a/p2p/simulations/network.go b/p2p/simulations/network.go index 47458664fc9..a97cdd40713 100644 --- a/p2p/simulations/network.go +++ b/p2p/simulations/network.go @@ -199,12 +199,12 @@ func (net *Network) startWithSnapshots(id enode.ID, snapshots map[string][]byte) // subscribe to peer events client, err := node.Client() if err != nil { - return fmt.Errorf("error getting rpc client for node %v: %s", id, err) + return fmt.Errorf("error getting rpc client for node %v: %w", id, err) } events := make(chan *p2p.PeerEvent) sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents") if err != nil { - return fmt.Errorf("error getting peer events for node %v: %s", id, err) + return fmt.Errorf("error getting peer events for node %v: %w", id, err) } go net.watchPeerEvents(id, events, sub) return nil diff --git a/p2p/transport.go b/p2p/transport.go index 30dca9417a5..9b28c1d686e 100644 --- a/p2p/transport.go +++ b/p2p/transport.go @@ -150,7 +150,7 @@ func (t *rlpxTransport) doProtoHandshake(our *protoHandshake) (their *protoHands return nil, err } if err := <-werr; err != nil { - return nil, fmt.Errorf("write error: %v", err) + return nil, fmt.Errorf("write error: %w", err) } // If the protocol version supports Snappy encoding, upgrade immediately t.conn.SetSnappy(their.Version >= snappyProtocolVersion) diff --git a/rlp/decode.go b/rlp/decode.go index d3022b27301..fefca41ff3c 100644 --- a/rlp/decode.go +++ b/rlp/decode.go @@ -38,13 +38,15 @@ import ( var EOL = errors.New("rlp: end of list") var ( - ErrExpectedString = errors.New("rlp: expected String or Byte") - ErrExpectedList = errors.New("rlp: expected List") - ErrCanonInt = errors.New("rlp: non-canonical integer format") - ErrCanonSize = errors.New("rlp: non-canonical size information") - ErrElemTooLarge = errors.New("rlp: element is larger than containing list") - ErrValueTooLarge = errors.New("rlp: value size exceeds available input length") - ErrMoreThanOneValue = errors.New("rlp: input contains more than one value") + ErrExpectedString = errors.New("rlp: expected String or Byte") + ErrExpectedList = errors.New("rlp: expected List") + ErrCanonInt = errors.New("rlp: non-canonical integer format") + ErrCanonSize = errors.New("rlp: non-canonical size information") + ErrElemTooLarge = errors.New("rlp: element is larger than containing list") + ErrValueTooLarge = errors.New("rlp: value size exceeds available input length") + ErrMoreThanOneValue = errors.New("rlp: input contains more than one value") + ErrWrongTxTypePrefix = errors.New("rlp: only 1-byte tx type prefix is supported") + ErrUnknownTxTypePrefix = errors.New("rlp: unknown tx type prefix") // internal errors errNotInList = errors.New("rlp: call of ListEnd outside of any list") @@ -66,7 +68,9 @@ func IsDecodeError(err error) bool { errors.Is(err, ErrCanonSize) || errors.Is(err, ErrElemTooLarge) || errors.Is(err, ErrValueTooLarge) || - errors.Is(err, ErrMoreThanOneValue) + errors.Is(err, ErrMoreThanOneValue) || + errors.Is(err, ErrWrongTxTypePrefix) || + errors.Is(err, ErrUnknownTxTypePrefix) } // Decoder is implemented by types that require custom RLP decoding rules or need to decode diff --git a/rpc/http.go b/rpc/http.go index c1d0ab0ad16..a2a4a865908 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -144,7 +144,7 @@ func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) e if respBody != nil { buf := new(bytes.Buffer) if _, err2 := buf.ReadFrom(respBody); err2 == nil { - return fmt.Errorf("%v: %v", err, buf.String()) + return fmt.Errorf("%w: %v", err, buf.String()) } } return err diff --git a/rpc/json.go b/rpc/json.go index 4d7fdcb31b2..a0d8b5dc6f9 100644 --- a/rpc/json.go +++ b/rpc/json.go @@ -315,7 +315,7 @@ func parseArgumentArray(dec *json.Decoder, types []reflect.Type) ([]reflect.Valu } argval := reflect.New(types[i]) if err := dec.Decode(argval.Interface()); err != nil { - return args, fmt.Errorf("invalid argument %d: %v", i, err) + return args, fmt.Errorf("invalid argument %d: %w", i, err) } if argval.IsNil() && types[i].Kind() != reflect.Ptr { return args, fmt.Errorf("missing value for required argument %d", i) diff --git a/rpc/subscription_test.go b/rpc/subscription_test.go index 066203a66a0..f2474414a35 100644 --- a/rpc/subscription_test.go +++ b/rpc/subscription_test.go @@ -195,13 +195,13 @@ func waitForMessages(in *json.Decoder, successes chan subConfirmation, notificat func readAndValidateMessage(in *json.Decoder) (*subConfirmation, *subscriptionResult, error) { var msg jsonrpcMessage if err := in.Decode(&msg); err != nil { - return nil, nil, fmt.Errorf("decode error: %v", err) + return nil, nil, fmt.Errorf("decode error: %w", err) } switch { case msg.isNotification(): var res subscriptionResult if err := json.Unmarshal(msg.Params, &res); err != nil { - return nil, nil, fmt.Errorf("invalid subscription result: %v", err) + return nil, nil, fmt.Errorf("invalid subscription result: %w", err) } return nil, &res, nil case msg.isResponse(): @@ -209,7 +209,7 @@ func readAndValidateMessage(in *json.Decoder) (*subConfirmation, *subscriptionRe if msg.Error != nil { return nil, nil, msg.Error } else if err := json.Unmarshal(msg.Result, &c.subid); err != nil { - return nil, nil, fmt.Errorf("invalid response: %v", err) + return nil, nil, fmt.Errorf("invalid response: %w", err) } else { json.Unmarshal(msg.ID, &c.reqid) return &c, nil, nil diff --git a/tests/block_test_util.go b/tests/block_test_util.go index 1500c3606da..bdde498575d 100644 --- a/tests/block_test_util.go +++ b/tests/block_test_util.go @@ -128,7 +128,7 @@ func (t *BlockTest) Run(tst *testing.T, _ bool) error { tx, err1 := m.DB.BeginRo(context.Background()) if err1 != nil { - return fmt.Errorf("blockTest create tx: %v", err1) + return fmt.Errorf("blockTest create tx: %w", err1) } defer tx.Rollback() cmlast := rawdb.ReadHeadBlockHash(tx) @@ -137,7 +137,7 @@ func (t *BlockTest) Run(tst *testing.T, _ bool) error { } newDB := state.New(state.NewPlainStateReader(tx)) if err = t.validatePostState(newDB); err != nil { - return fmt.Errorf("post state validation failed: %v", err) + return fmt.Errorf("post state validation failed: %w", err) } return t.validateImportedHeaders(tx, validBlocks) } @@ -180,7 +180,7 @@ func (t *BlockTest) insertBlocks(m *stages.MockSentry) ([]btBlock, error) { if b.BlockHeader == nil { continue // OK - block is supposed to be invalid, continue with next block } else { - return nil, fmt.Errorf("block RLP decoding failed when expected to succeed: %v", err) + return nil, fmt.Errorf("block RLP decoding failed when expected to succeed: %w", err) } } // RLP decoding worked, try to insert into chain: @@ -189,7 +189,7 @@ func (t *BlockTest) insertBlocks(m *stages.MockSentry) ([]btBlock, error) { if b.BlockHeader == nil { continue // OK - block is supposed to be invalid, continue with next block } else { - return nil, fmt.Errorf("block #%v insertion into chain failed: %v", cb.Number(), err1) + return nil, fmt.Errorf("block #%v insertion into chain failed: %w", cb.Number(), err1) } } else if b.BlockHeader == nil { if err := m.DB.View(context.Background(), func(tx kv.Tx) error { @@ -210,7 +210,7 @@ func (t *BlockTest) insertBlocks(m *stages.MockSentry) ([]btBlock, error) { } // validate RLP decoding by checking all values against test file JSON if err = validateHeader(b.BlockHeader, cb.Header()); err != nil { - return nil, fmt.Errorf("deserialised block header validation failed: %v", err) + return nil, fmt.Errorf("deserialised block header validation failed: %w", err) } validBlocks = append(validBlocks, b) } @@ -305,7 +305,7 @@ func (t *BlockTest) validateImportedHeaders(tx kv.Tx, validBlocks []btBlock) err // be part of the longest chain until last block is imported. for b := rawdb.ReadCurrentBlock(tx); b != nil && b.NumberU64() != 0; { if err := validateHeader(bmap[b.Hash()].BlockHeader, b.Header()); err != nil { - return fmt.Errorf("imported block header validation failed: %v", err) + return fmt.Errorf("imported block header validation failed: %w", err) } b, _ = rawdb.ReadBlockByHash(tx, b.Header().ParentHash) } diff --git a/tests/init_test.go b/tests/init_test.go index 45bfe1ba2ad..547720a06fc 100644 --- a/tests/init_test.go +++ b/tests/init_test.go @@ -47,12 +47,12 @@ var ( func readJSON(reader io.Reader, value interface{}) error { data, err := ioutil.ReadAll(reader) if err != nil { - return fmt.Errorf("error reading JSON file: %v", err) + return fmt.Errorf("error reading JSON file: %w", err) } if err = json.Unmarshal(data, &value); err != nil { if syntaxerr, ok := err.(*json.SyntaxError); ok { line := findLine(data, syntaxerr.Offset) - return fmt.Errorf("JSON syntax error at line %v: %v", line, err) + return fmt.Errorf("JSON syntax error at line %v: %w", line, err) } return err } diff --git a/tests/rlp_test_util.go b/tests/rlp_test_util.go index 5fc99c63641..553de0f8506 100644 --- a/tests/rlp_test_util.go +++ b/tests/rlp_test_util.go @@ -71,7 +71,7 @@ func (t *RLPTest) Run() error { in := translateJSON(t.In) b, err := rlp.EncodeToBytes(in) if err != nil { - return fmt.Errorf("encode failed: %v", err) + return fmt.Errorf("encode failed: %w", err) } if !bytes.Equal(b, outb) { return fmt.Errorf("encode produced %x, want %x", b, outb) @@ -85,7 +85,7 @@ func checkDecodeInterface(b []byte, isValid bool) error { err := rlp.DecodeBytes(b, new(interface{})) switch { case isValid && err != nil: - return fmt.Errorf("decoding failed: %v", err) + return fmt.Errorf("decoding failed: %w", err) case !isValid && err == nil: return fmt.Errorf("decoding of invalid value succeeded") } diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 82cfd4dc2b7..cc1cbca8897 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -285,7 +285,7 @@ func (t *StateTest) RunNoVerify(rules params.Rules, tx kv.RwTx, subtest StateSub root, err := trie.CalcRoot("", tx) if err != nil { - return nil, common.Hash{}, fmt.Errorf("error calculating state root: %v", err) + return nil, common.Hash{}, fmt.Errorf("error calculating state root: %w", err) } return statedb, root, nil @@ -341,7 +341,7 @@ func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (core.Messa if len(tx.PrivateKey) > 0 { key, err := crypto.ToECDSA(tx.PrivateKey) if err != nil { - return nil, fmt.Errorf("invalid private key: %v", err) + return nil, fmt.Errorf("invalid private key: %w", err) } from = crypto.PubkeyToAddress(key.PublicKey) } @@ -350,7 +350,7 @@ func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (core.Messa if tx.To != "" { to = new(common.Address) if err := to.UnmarshalText([]byte(tx.To)); err != nil { - return nil, fmt.Errorf("invalid to address: %v", err) + return nil, fmt.Errorf("invalid to address: %w", err) } } diff --git a/tests/transaction_test_util.go b/tests/transaction_test_util.go index 2d94d10cb1b..9c70b008cd6 100644 --- a/tests/transaction_test_util.go +++ b/tests/transaction_test_util.go @@ -92,7 +92,7 @@ func (tt *TransactionTest) Run(config *params.ChainConfig) error { } // Should resolve the right address if err != nil { - return fmt.Errorf("got error, expected none: %v", err) + return fmt.Errorf("got error, expected none: %w", err) } if sender == nil { return fmt.Errorf("sender was nil, should be %x", common.Address(testcase.fork.Sender)) diff --git a/tests/vm_test_util.go b/tests/vm_test_util.go index 163b1b2f6bc..a2fa376930d 100644 --- a/tests/vm_test_util.go +++ b/tests/vm_test_util.go @@ -83,7 +83,7 @@ type vmExecMarshaling struct { func (t *VMTest) Run(tx kv.RwTx, vmconfig vm.Config, blockNr uint64) error { state, err := MakePreState(params.MainnetChainConfig.Rules(blockNr), tx, t.json.Pre, blockNr) if err != nil { - return fmt.Errorf("error in MakePreState: %v", err) + return fmt.Errorf("error in MakePreState: %w", err) } ret, gasRemaining, err := t.exec(state, vmconfig) // err is not supposed to be checked here, because in VM tests, the failure @@ -117,7 +117,7 @@ func (t *VMTest) Run(tx kv.RwTx, vmconfig vm.Config, blockNr uint64) error { } root, err := trie.CalcRoot("test", tx) if err != nil { - return fmt.Errorf("Error calculating state root: %v", err) + return fmt.Errorf("Error calculating state root: %w", err) } if t.json.PostStateRoot != (common.Hash{}) && root != t.json.PostStateRoot { return fmt.Errorf("post state root mismatch, got %x, want %x", root, t.json.PostStateRoot) diff --git a/turbo/stages/blockchain_test.go b/turbo/stages/blockchain_test.go index a2e6ae5d628..140053e32b9 100644 --- a/turbo/stages/blockchain_test.go +++ b/turbo/stages/blockchain_test.go @@ -733,7 +733,7 @@ func doModesTest(t *testing.T, pm prune.Mode) error { } }, false /* intemediateHashes */) if err != nil { - return fmt.Errorf("generate blocks: %v", err) + return fmt.Errorf("generate blocks: %w", err) } if err = m.InsertChain(chain); err != nil { diff --git a/turbo/stages/genesis_test.go b/turbo/stages/genesis_test.go index 7c181caf283..a1cbc68c86a 100644 --- a/turbo/stages/genesis_test.go +++ b/turbo/stages/genesis_test.go @@ -44,7 +44,7 @@ func TestDefaultGenesisBlock(t *testing.T) { var err error block, _, err = core.DefaultRopstenGenesisBlock().ToBlock() if err != nil { - t.Errorf("error: %w", err) + t.Errorf("error: %v", err) } if block.Hash() != params.RopstenGenesisHash { t.Errorf("wrong ropsten genesis hash, got %v, want %v", block.Hash(), params.RopstenGenesisHash) @@ -52,7 +52,7 @@ func TestDefaultGenesisBlock(t *testing.T) { block, _, err = core.DefaultSokolGenesisBlock().ToBlock() if err != nil { - t.Errorf("error: %w", err) + t.Errorf("error: %v", err) } if block.Root() != params.SokolGenesisStateRoot { t.Errorf("wrong sokol genesis state root, got %v, want %v", block.Root(), params.SokolGenesisStateRoot) @@ -63,7 +63,7 @@ func TestDefaultGenesisBlock(t *testing.T) { block, _, err = core.DefaultKovanGenesisBlock().ToBlock() if err != nil { - t.Errorf("error: %w", err) + t.Errorf("error: %v", err) } if block.Root() != params.KovanGenesisStateRoot { t.Errorf("wrong kovan genesis state root, got %v, want %v", block.Root(), params.KovanGenesisStateRoot) @@ -74,7 +74,7 @@ func TestDefaultGenesisBlock(t *testing.T) { block, _, err = core.DefaultFermionGenesisBlock().ToBlock() if err != nil { - t.Errorf("error: %w", err) + t.Errorf("error: %v", err) } if block.Root() != params.FermionGenesisStateRoot { t.Errorf("wrong fermion genesis state root, got %v, want %v", block.Root(), params.FermionGenesisStateRoot) diff --git a/turbo/transactions/tracing.go b/turbo/transactions/tracing.go index 150b251531e..66ea3420f6c 100644 --- a/turbo/transactions/tracing.go +++ b/turbo/transactions/tracing.go @@ -62,7 +62,7 @@ func ComputeTxEnv(ctx context.Context, block *types.Block, cfg *params.ChainConf vmenv.Reset(TxContext, statedb) // Not yet the searched for transaction, execute on top of the current state if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.GetGas()), true /* refunds */, false /* gasBailout */); err != nil { - return nil, vm.BlockContext{}, vm.TxContext{}, nil, nil, fmt.Errorf("transaction %x failed: %v", tx.Hash(), err) + return nil, vm.BlockContext{}, vm.TxContext{}, nil, nil, fmt.Errorf("transaction %x failed: %w", tx.Hash(), err) } // Ensure any modifications are committed to the state // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect @@ -140,7 +140,7 @@ func TraceTx( stream.WriteArrayEnd() stream.WriteObjectEnd() } - return fmt.Errorf("tracing failed: %v", err) + return fmt.Errorf("tracing failed: %w", err) } // Depending on the tracer type, format and return the output if streaming { diff --git a/turbo/trie/trie.go b/turbo/trie/trie.go index d525ff994d4..c664870aee3 100644 --- a/turbo/trie/trie.go +++ b/turbo/trie/trie.go @@ -720,7 +720,7 @@ func (t *Trie) HookSubTries(subTries SubTries, hooks [][]byte) error { return fmt.Errorf("root==nil for hook %x", hookNibbles) } if err := t.hook(hookNibbles, root, hash[:]); err != nil { - return fmt.Errorf("hook %x: %v", hookNibbles, err) + return fmt.Errorf("hook %x: %w", hookNibbles, err) } } return nil diff --git a/turbo/txpool/p2p.go b/turbo/txpool/p2p.go index a8e380c828f..1243cc4084c 100644 --- a/turbo/txpool/p2p.go +++ b/turbo/txpool/p2p.go @@ -51,7 +51,7 @@ func NewP2PServer(ctx context.Context, sentries []direct.SentryClient, txPool *c func (tp *P2PServer) newPooledTransactionHashes66(ctx context.Context, inreq *proto_sentry.InboundMessage, sentry direct.SentryClient) error { var query eth.NewPooledTransactionHashesPacket if err := rlp.DecodeBytes(inreq.Data, &query); err != nil { - return fmt.Errorf("decoding newPooledTransactionHashes66: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding newPooledTransactionHashes66: %w, data: %x", err, inreq.Data) } return tp.TxFetcher.Notify(string(gointerfaces.ConvertH512ToBytes(inreq.PeerId)), query) } @@ -59,7 +59,7 @@ func (tp *P2PServer) newPooledTransactionHashes66(ctx context.Context, inreq *pr func (tp *P2PServer) newPooledTransactionHashes65(ctx context.Context, inreq *proto_sentry.InboundMessage, sentry direct.SentryClient) error { var query eth.NewPooledTransactionHashesPacket if err := rlp.DecodeBytes(inreq.Data, &query); err != nil { - return fmt.Errorf("decoding newPooledTransactionHashes65: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding newPooledTransactionHashes65: %w, data: %x", err, inreq.Data) } return tp.TxFetcher.Notify(string(gointerfaces.ConvertH512ToBytes(inreq.PeerId)), query) } @@ -67,7 +67,7 @@ func (tp *P2PServer) newPooledTransactionHashes65(ctx context.Context, inreq *pr func (tp *P2PServer) pooledTransactions66(ctx context.Context, inreq *proto_sentry.InboundMessage, sentry direct.SentryClient) error { txs := ð.PooledTransactionsPacket66{} if err := txs.DecodeRLP(rlp.NewStream(bytes.NewReader(inreq.Data), 0)); err != nil { - return fmt.Errorf("decoding pooledTransactions66: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding pooledTransactions66: %w, data: %x", err, inreq.Data) } return tp.TxFetcher.Enqueue(string(gointerfaces.ConvertH512ToBytes(inreq.PeerId)), txs.PooledTransactionsPacket, true) @@ -76,7 +76,7 @@ func (tp *P2PServer) pooledTransactions66(ctx context.Context, inreq *proto_sent func (tp *P2PServer) pooledTransactions65(ctx context.Context, inreq *proto_sentry.InboundMessage, sentry direct.SentryClient) error { txs := ð.PooledTransactionsPacket{} if err := txs.DecodeRLP(rlp.NewStream(bytes.NewReader(inreq.Data), 0)); err != nil { - return fmt.Errorf("decoding pooledTransactions65: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding pooledTransactions65: %w, data: %x", err, inreq.Data) } return tp.TxFetcher.Enqueue(string(gointerfaces.ConvertH512ToBytes(inreq.PeerId)), *txs, true) @@ -92,7 +92,7 @@ func (tp *P2PServer) transactions65(ctx context.Context, inreq *proto_sentry.Inb } var query eth.TransactionsPacket if err := rlp.DecodeBytes(inreq.Data, &query); err != nil { - return fmt.Errorf("decoding TransactionsPacket: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding TransactionsPacket: %w, data: %x", err, inreq.Data) } return tp.TxFetcher.Enqueue(string(gointerfaces.ConvertH512ToBytes(inreq.PeerId)), query, false) } @@ -103,7 +103,7 @@ func (tp *P2PServer) getPooledTransactions66(ctx context.Context, inreq *proto_s } var query eth.GetPooledTransactionsPacket66 if err := rlp.DecodeBytes(inreq.Data, &query); err != nil { - return fmt.Errorf("decoding GetPooledTransactionsPacket66: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding GetPooledTransactionsPacket66: %w, data: %x", err, inreq.Data) } _, txs := eth.AnswerGetPooledTransactions(tp.TxPool, query.GetPooledTransactionsPacket) b, err := rlp.EncodeToBytes(ð.PooledTransactionsRLPPacket66{ @@ -111,7 +111,7 @@ func (tp *P2PServer) getPooledTransactions66(ctx context.Context, inreq *proto_s PooledTransactionsRLPPacket: txs, }) if err != nil { - return fmt.Errorf("encode GetPooledTransactionsPacket66 response: %v", err) + return fmt.Errorf("encode GetPooledTransactionsPacket66 response: %w", err) } // TODO: implement logic from perr.ReplyPooledTransactionsRLP - to remember tx ids outreq := proto_sentry.SendMessageByIdRequest{ @@ -120,7 +120,7 @@ func (tp *P2PServer) getPooledTransactions66(ctx context.Context, inreq *proto_s } _, err = sentry.SendMessageById(ctx, &outreq, &grpc.EmptyCallOption{}) if err != nil { - return fmt.Errorf("send pooled transactions response: %v", err) + return fmt.Errorf("send pooled transactions response: %w", err) } return nil } @@ -131,12 +131,12 @@ func (tp *P2PServer) getPooledTransactions65(ctx context.Context, inreq *proto_s } var query eth.GetPooledTransactionsPacket if err := rlp.DecodeBytes(inreq.Data, &query); err != nil { - return fmt.Errorf("decoding getPooledTransactions65: %v, data: %x", err, inreq.Data) + return fmt.Errorf("decoding getPooledTransactions65: %w, data: %x", err, inreq.Data) } _, txs := eth.AnswerGetPooledTransactions(tp.TxPool, query) b, err := rlp.EncodeToBytes(eth.PooledTransactionsRLPPacket(txs)) if err != nil { - return fmt.Errorf("encode getPooledTransactions65 response: %v", err) + return fmt.Errorf("encode getPooledTransactions65 response: %w", err) } // TODO: implement logic from perr.ReplyPooledTransactionsRLP - to remember tx ids outreq := proto_sentry.SendMessageByIdRequest{ @@ -145,7 +145,7 @@ func (tp *P2PServer) getPooledTransactions65(ctx context.Context, inreq *proto_s } _, err = sentry.SendMessageById(ctx, &outreq, &grpc.EmptyCallOption{}) if err != nil { - return fmt.Errorf("send pooled transactions response: %v", err) + return fmt.Errorf("send pooled transactions response: %w", err) } return nil }