Inner errors (#2774)

This commit is contained in:
Andrea Lanfranchi 2021-10-04 17:16:52 +02:00 committed by GitHub
parent 044aa6748c
commit c913f35c2e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
75 changed files with 193 additions and 191 deletions

View File

@ -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)

View File

@ -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 {

View File

@ -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

View File

@ -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
}

View File

@ -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" {

View File

@ -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)

View File

@ -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)

View File

@ -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)
}
}

View File

@ -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))

View File

@ -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)

View File

@ -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 {

View File

@ -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

View File

@ -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
}

View File

@ -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()

View File

@ -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)
}
}
}

View File

@ -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 {

View File

@ -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 {

View File

@ -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)

View File

@ -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{

View File

@ -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)
}
}

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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(), " "))

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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)

View File

@ -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()
}

View File

@ -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
}
}

View File

@ -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

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

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

View File

@ -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:

View File

@ -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
}

View File

@ -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

View File

@ -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)
}

View File

@ -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

View File

@ -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
}

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -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

View File

@ -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)

View File

@ -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
}

View File

@ -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)

View File

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

View File

@ -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
}

View File

@ -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())

View File

@ -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 {

View File

@ -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

View File

@ -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())

View File

@ -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)
}
}

View File

@ -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()

View File

@ -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)

View File

@ -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
}

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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)
}

View File

@ -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
}

View File

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

View File

@ -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)
}
}

View File

@ -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))

View File

@ -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)

View File

@ -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 {

View File

@ -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)

View File

@ -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 {

View File

@ -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

View File

@ -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 := &eth.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 := &eth.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(&eth.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
}