From 61b6f1aaba0868a6aa8838263894699aa598ad51 Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 22 Jan 2024 09:39:04 -0500 Subject: [PATCH 01/11] rename some pkgerror pkgs --- .../chainlink-cluster/dashboard/dashboard.go | 2 +- core/auth/auth.go | 2 +- core/bridges/external_initiator.go | 5 +- core/bridges/orm.go | 26 ++++----- core/cbor/cbor.go | 4 +- core/chains/evm/assets/wei.go | 12 ++-- core/chains/evm/client/client.go | 4 +- core/chains/evm/client/client_test.go | 4 +- core/chains/evm/client/erroring_node.go | 50 ++++++++--------- core/chains/evm/client/errors.go | 24 ++++---- core/chains/evm/client/errors_test.go | 6 +- core/chains/evm/client/helpers_test.go | 10 ++-- core/chains/evm/client/node.go | 26 ++++----- core/chains/evm/client/node_lifecycle.go | 6 +- core/chains/evm/client/pool.go | 8 +-- core/chains/evm/client/rpc_client.go | 16 +++--- .../evm/forwarders/forwarder_manager.go | 18 +++--- core/chains/evm/forwarders/orm.go | 10 ++-- core/chains/evm/gas/arbitrum_estimator.go | 12 ++-- .../chains/evm/gas/arbitrum_estimator_test.go | 4 +- .../chains/evm/gas/block_history_estimator.go | 56 +++++++++---------- .../evm/gas/block_history_estimator_test.go | 20 +++---- core/chains/evm/gas/fixed_price_estimator.go | 4 +- core/chains/evm/gas/models.go | 22 ++++---- core/chains/evm/gas/models_test.go | 12 ++-- .../evm/gas/suggested_price_estimator.go | 18 +++--- .../evm/gas/suggested_price_estimator_test.go | 4 +- .../evm/headtracker/head_listener_test.go | 4 +- core/chains/evm/headtracker/orm.go | 12 ++-- core/chains/evm/log/broadcaster.go | 8 +-- core/chains/evm/log/orm.go | 26 ++++----- core/chains/evm/log/registrations.go | 14 ++--- core/chains/evm/logpoller/disabled.go | 4 +- core/chains/evm/logpoller/helper_test.go | 4 +- core/chains/evm/logpoller/log_poller.go | 56 +++++++++---------- .../evm/logpoller/log_poller_internal_test.go | 6 +- core/chains/evm/logpoller/orm.go | 10 ++-- core/chains/evm/logpoller/orm_test.go | 14 ++--- core/chains/evm/monitor/balance.go | 4 +- core/chains/evm/monitor/balance_test.go | 4 +- core/chains/evm/txmgr/attempts.go | 40 ++++++------- core/chains/evm/txmgr/attempts_test.go | 6 +- core/chains/evm/txmgr/common.go | 4 +- 43 files changed, 300 insertions(+), 301 deletions(-) diff --git a/charts/chainlink-cluster/dashboard/dashboard.go b/charts/chainlink-cluster/dashboard/dashboard.go index 19a596b63e9..41774b06c96 100644 --- a/charts/chainlink-cluster/dashboard/dashboard.go +++ b/charts/chainlink-cluster/dashboard/dashboard.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" + "cosmossdk.io/errors" "github.com/K-Phoen/grabana" "github.com/K-Phoen/grabana/dashboard" "github.com/K-Phoen/grabana/logs" @@ -14,7 +15,6 @@ import ( "github.com/K-Phoen/grabana/timeseries" "github.com/K-Phoen/grabana/timeseries/axis" "github.com/K-Phoen/grabana/variable/query" - "github.com/pkg/errors" ) /* diff --git a/core/auth/auth.go b/core/auth/auth.go index f881afab736..8fae335dc5f 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -4,9 +4,9 @@ import ( "encoding/hex" "fmt" + "cosmossdk.io/errors" "github.com/smartcontractkit/chainlink/v2/core/utils" - "github.com/pkg/errors" "golang.org/x/crypto/sha3" ) diff --git a/core/bridges/external_initiator.go b/core/bridges/external_initiator.go index 53d00e77bbb..bfab811f337 100644 --- a/core/bridges/external_initiator.go +++ b/core/bridges/external_initiator.go @@ -5,11 +5,10 @@ import ( "strings" "time" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/store/models" "github.com/smartcontractkit/chainlink/v2/core/utils" - - "github.com/pkg/errors" ) // ExternalInitiatorRequest is the incoming record used to create an ExternalInitiator. @@ -42,7 +41,7 @@ func NewExternalInitiator( salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(eia, salt) if err != nil { - return nil, errors.Wrap(err, "error hashing secret for external initiator") + return nil, pkgerrors.Wrap(err, "error hashing secret for external initiator") } return &ExternalInitiator{ diff --git a/core/bridges/orm.go b/core/bridges/orm.go index 8ae6b855c88..f4728ea0662 100644 --- a/core/bridges/orm.go +++ b/core/bridges/orm.go @@ -7,7 +7,7 @@ import ( "time" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -67,7 +67,7 @@ func (o *orm) FindBridge(name BridgeName) (bt BridgeType, err error) { // Expects all bridges to be unique func (o *orm) FindBridges(names []BridgeName) (bts []BridgeType, err error) { if len(names) == 0 { - return nil, errors.Errorf("at least one bridge name is required") + return nil, pkgerrors.Errorf("at least one bridge name is required") } var allFoundBts []BridgeType @@ -99,7 +99,7 @@ func (o *orm) FindBridges(names []BridgeName) (bts []BridgeType, err error) { } allFoundBts = append(allFoundBts, bts...) if len(allFoundBts) != len(names) { - return nil, errors.Errorf("not all bridges exist, asked for %v, exists %v", names, allFoundBts) + return nil, pkgerrors.Errorf("not all bridges exist, asked for %v, exists %v", names, allFoundBts) } return allFoundBts, nil } @@ -128,11 +128,11 @@ func (o *orm) DeleteBridgeType(bt *BridgeType) error { func (o *orm) BridgeTypes(offset int, limit int) (bridges []BridgeType, count int, err error) { err = o.q.Transaction(func(tx pg.Queryer) error { if err = tx.Get(&count, "SELECT COUNT(*) FROM bridge_types"); err != nil { - return errors.Wrap(err, "BridgeTypes failed to get count") + return pkgerrors.Wrap(err, "BridgeTypes failed to get count") } sql := `SELECT * FROM bridge_types ORDER BY name asc LIMIT $1 OFFSET $2;` if err = tx.Select(&bridges, sql, limit, offset); err != nil { - return errors.Wrap(err, "BridgeTypes failed to load bridge_types") + return pkgerrors.Wrap(err, "BridgeTypes failed to load bridge_types") } return nil }, pg.OptReadOnlyTx()) @@ -157,7 +157,7 @@ func (o *orm) CreateBridgeType(bt *BridgeType) error { o.bridgeTypesCache.Store(bt.Name, *bt) } - return errors.Wrap(err, "CreateBridgeType failed") + return pkgerrors.Wrap(err, "CreateBridgeType failed") } // UpdateBridgeType updates the bridge type. @@ -179,7 +179,7 @@ func (o *orm) GetCachedResponse(dotId string, specId int32, maxElapsed time.Dura finished_at > ($3) ORDER BY finished_at DESC LIMIT 1;` - err = errors.Wrap(o.q.Get(&response, sql, dotId, specId, stalenessThreshold), fmt.Sprintf("failed to fetch last good value for task %s spec %d", dotId, specId)) + err = pkgerrors.Wrap(o.q.Get(&response, sql, dotId, specId, stalenessThreshold), fmt.Sprintf("failed to fetch last good value for task %s spec %d", dotId, specId)) return } @@ -190,7 +190,7 @@ func (o *orm) UpsertBridgeResponse(dotId string, specId int32, response []byte) DO UPDATE SET value = $3, finished_at = $4;` err := o.q.ExecQ(sql, dotId, specId, response, time.Now()) - return errors.Wrap(err, "failed to upsert bridge response") + return pkgerrors.Wrap(err, "failed to upsert bridge response") } // --- External Initiator @@ -199,12 +199,12 @@ func (o *orm) UpsertBridgeResponse(dotId string, specId int32, response []byte) func (o *orm) ExternalInitiators(offset int, limit int) (exis []ExternalInitiator, count int, err error) { err = o.q.Transaction(func(tx pg.Queryer) error { if err = tx.Get(&count, "SELECT COUNT(*) FROM external_initiators"); err != nil { - return errors.Wrap(err, "ExternalInitiators failed to get count") + return pkgerrors.Wrap(err, "ExternalInitiators failed to get count") } sql := `SELECT * FROM external_initiators ORDER BY name asc LIMIT $1 OFFSET $2;` if err = tx.Select(&exis, sql, limit, offset); err != nil { - return errors.Wrap(err, "ExternalInitiators failed to load external_initiators") + return pkgerrors.Wrap(err, "ExternalInitiators failed to load external_initiators") } return nil }, pg.OptReadOnlyTx()) @@ -221,12 +221,12 @@ func (o *orm) CreateExternalInitiator(externalInitiator *ExternalInitiator) (err var stmt *sqlx.NamedStmt stmt, err = tx.PrepareNamed(query) if err != nil { - return errors.Wrap(err, "failed to prepare named stmt") + return pkgerrors.Wrap(err, "failed to prepare named stmt") } defer stmt.Close() - return errors.Wrap(stmt.Get(externalInitiator, externalInitiator), "failed to load external_initiator") + return pkgerrors.Wrap(stmt.Get(externalInitiator, externalInitiator), "failed to load external_initiator") }) - return errors.Wrap(err, "CreateExternalInitiator failed") + return pkgerrors.Wrap(err, "CreateExternalInitiator failed") } // DeleteExternalInitiator removes an external initiator diff --git a/core/cbor/cbor.go b/core/cbor/cbor.go index cc3f74e423e..fb6e6c88f95 100644 --- a/core/cbor/cbor.go +++ b/core/cbor/cbor.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/fxamacker/cbor/v2" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // ParseDietCBOR attempts to coerce the input byte array into valid CBOR. @@ -28,7 +28,7 @@ func ParseDietCBOR(b []byte) (map[string]interface{}, error) { output, ok := coerced.(map[string]interface{}) if !ok { - return nil, errors.New("cbor data cannot be coerced to map") + return nil, pkgerrors.New("cbor data cannot be coerced to map") } return output, nil diff --git a/core/chains/evm/assets/wei.go b/core/chains/evm/assets/wei.go index 8bacabfdb4a..3621e4492a4 100644 --- a/core/chains/evm/assets/wei.go +++ b/core/chains/evm/assets/wei.go @@ -6,7 +6,7 @@ import ( "math/big" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" "golang.org/x/exp/constraints" @@ -185,7 +185,7 @@ func (w *Wei) UnmarshalText(b []byte) error { t = strings.TrimSuffix(t, " ") d, err := decimal.NewFromString(t) if err != nil { - return errors.Wrapf(err, "unable to parse %q", s) + return pkgerrors.Wrapf(err, "unable to parse %q", s) } se := suffixExp(suf) if d.IsInteger() { @@ -196,8 +196,8 @@ func (w *Wei) UnmarshalText(b []byte) error { d = d.Mul(decimal.New(1, se)) if !d.IsInteger() { - err := errors.New("maximum precision is wei") - return errors.Wrapf(err, "unable to parse %q", s) + err := pkgerrors.New("maximum precision is wei") + return pkgerrors.Wrapf(err, "unable to parse %q", s) } *w = (Wei)(*d.BigInt()) return nil @@ -206,13 +206,13 @@ func (w *Wei) UnmarshalText(b []byte) error { // unrecognized or missing suffix d, err := decimal.NewFromString(s) if err != nil { - return errors.Wrapf(err, "unable to parse %q", s) + return pkgerrors.Wrapf(err, "unable to parse %q", s) } if d.IsInteger() { *w = (Wei)(*d.BigInt()) return nil } - return errors.Errorf("unable to parse %q", s) + return pkgerrors.Errorf("unable to parse %q", s) } func (w *Wei) ToInt() *big.Int { diff --git a/core/chains/evm/client/client.go b/core/chains/evm/client/client.go index 61635c59c6b..a6c4c8e569d 100644 --- a/core/chains/evm/client/client.go +++ b/core/chains/evm/client/client.go @@ -22,7 +22,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) const queryTimeout = 10 * time.Second @@ -125,7 +125,7 @@ func NewClientWithNodes(lggr logger.Logger, selectionMode string, leaseDuration // node's remote chain ID matches the local one func (client *client) Dial(ctx context.Context) error { if err := client.pool.Dial(ctx); err != nil { - return errors.Wrap(err, "failed to dial pool") + return pkgerrors.Wrap(err, "failed to dial pool") } return nil } diff --git a/core/chains/evm/client/client_test.go b/core/chains/evm/client/client_test.go index 281b8bf4227..62acf146e48 100644 --- a/core/chains/evm/client/client_test.go +++ b/core/chains/evm/client/client_test.go @@ -17,7 +17,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -145,7 +145,7 @@ func TestEthClient_TransactionReceipt(t *testing.T) { hash := common.HexToHash(txHash) _, err = ethClient.TransactionReceipt(testutils.Context(t), hash) - require.Equal(t, ethereum.NotFound, errors.Cause(err)) + require.Equal(t, ethereum.NotFound, pkgerrors.Cause(err)) } }) } diff --git a/core/chains/evm/client/erroring_node.go b/core/chains/evm/client/erroring_node.go index c33891728a7..3a2b71d7401 100644 --- a/core/chains/evm/client/erroring_node.go +++ b/core/chains/evm/client/erroring_node.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) var _ Node = (*erroringNode)(nil) @@ -27,100 +27,100 @@ func (e *erroringNode) SubscribersCount() int32 { func (e *erroringNode) ChainID() (chainID *big.Int) { return nil } -func (e *erroringNode) Start(ctx context.Context) error { return errors.New(e.errMsg) } +func (e *erroringNode) Start(ctx context.Context) error { return pkgerrors.New(e.errMsg) } func (e *erroringNode) Close() error { return nil } func (e *erroringNode) Verify(ctx context.Context, expectedChainID *big.Int) (err error) { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) BatchCallContext(ctx context.Context, b []rpc.BatchElem) error { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) SendTransaction(ctx context.Context, tx *types.Transaction) error { - return errors.New(e.errMsg) + return pkgerrors.New(e.errMsg) } func (e *erroringNode) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) BlockNumber(ctx context.Context) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { - return 0, errors.New(e.errMsg) + return 0, pkgerrors.New(e.errMsg) } func (e *erroringNode) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) HeaderByNumber(_ context.Context, _ *big.Int) (*types.Header, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) HeaderByHash(_ context.Context, _ common.Hash) (*types.Header, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) EthSubscribe(ctx context.Context, channel chan<- *evmtypes.Head, args ...interface{}) (ethereum.Subscription, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) String() string { diff --git a/core/chains/evm/client/errors.go b/core/chains/evm/client/errors.go index bb748cb52fb..e292b59b03d 100644 --- a/core/chains/evm/client/errors.go +++ b/core/chains/evm/client/errors.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" commonclient "github.com/smartcontractkit/chainlink/v2/common/client" @@ -35,7 +35,7 @@ func (s *SendError) Fatal() bool { // CauseStr returns the string of the original error func (s *SendError) CauseStr() string { if s.err != nil { - return errors.Cause(s.err).Error() + return pkgerrors.Cause(s.err).Error() } return "" } @@ -308,18 +308,18 @@ func (s *SendError) IsTimeout() bool { if s.err == nil { return false } - return errors.Is(s.err, context.DeadlineExceeded) + return pkgerrors.Is(s.err, context.DeadlineExceeded) } func NewFatalSendError(e error) *SendError { if e == nil { return nil } - return &SendError{err: errors.WithStack(e), fatal: true} + return &SendError{err: pkgerrors.WithStack(e), fatal: true} } func NewSendErrorS(s string) *SendError { - return NewSendError(errors.New(s)) + return NewSendError(pkgerrors.New(s)) } func NewSendError(e error) *SendError { @@ -327,7 +327,7 @@ func NewSendError(e error) *SendError { return nil } fatal := isFatalSendError(e) - return &SendError{err: errors.WithStack(e), fatal: fatal} + return &SendError{err: pkgerrors.WithStack(e), fatal: fatal} } // Geth/parity returns these errors if the transaction failed in such a way that: @@ -337,7 +337,7 @@ func isFatalSendError(err error) bool { if err == nil { return false } - str := errors.Cause(err).Error() + str := pkgerrors.Cause(err).Error() for _, client := range clients { if _, ok := client[Fatal]; !ok { continue @@ -395,20 +395,20 @@ func ExtractRPCErrorOrNil(err error) *JsonError { // { "error": { "code": 3, "data": "0xABC123...", "message": "execution reverted: hello world" } } // revert reason automatically parsed if a simple require and included in message. func ExtractRPCError(baseErr error) (*JsonError, error) { if baseErr == nil { - return nil, errors.New("no error present") + return nil, pkgerrors.New("no error present") } - cause := errors.Cause(baseErr) + cause := pkgerrors.Cause(baseErr) jsonBytes, err := json.Marshal(cause) if err != nil { - return nil, errors.Wrap(err, "unable to marshal err to json") + return nil, pkgerrors.Wrap(err, "unable to marshal err to json") } jErr := JsonError{} err = json.Unmarshal(jsonBytes, &jErr) if err != nil { - return nil, errors.Wrapf(err, "unable to unmarshal json into jsonError struct (got: %v)", baseErr) + return nil, pkgerrors.Wrapf(err, "unable to unmarshal json into jsonError struct (got: %v)", baseErr) } if jErr.Code == 0 { - return nil, errors.Errorf("not a RPCError because it does not have a code (got: %v)", baseErr) + return nil, pkgerrors.Errorf("not a RPCError because it does not have a code (got: %v)", baseErr) } return &jErr, nil } diff --git a/core/chains/evm/client/errors_test.go b/core/chains/evm/client/errors_test.go index ad8079824ab..99d8fa7009b 100644 --- a/core/chains/evm/client/errors_test.go +++ b/core/chains/evm/client/errors_test.go @@ -3,14 +3,14 @@ package client_test import ( "testing" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" ) func newSendErrorWrapped(s string) *evmclient.SendError { - return evmclient.NewSendError(errors.Wrap(errors.New(s), "wrapped with some old bollocks")) + return evmclient.NewSendError(pkgerrors.Wrap(pkgerrors.New(s), "wrapped with some old bollocks")) } type errorCase struct { @@ -349,7 +349,7 @@ func Test_Eth_Errors_Fatal(t *testing.T) { for _, test := range tests { t.Run(test.message, func(t *testing.T) { - err := evmclient.NewSendError(errors.New(test.message)) + err := evmclient.NewSendError(pkgerrors.New(test.message)) assert.Equal(t, test.expect, err.Fatal()) }) } diff --git a/core/chains/evm/client/helpers_test.go b/core/chains/evm/client/helpers_test.go index c2f60e13f55..ca468122c75 100644 --- a/core/chains/evm/client/helpers_test.go +++ b/core/chains/evm/client/helpers_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" commonclient "github.com/smartcontractkit/chainlink/v2/common/client" @@ -39,7 +39,7 @@ func NewClientWithTestNode(t *testing.T, nodePoolCfg config.NodePool, noNewHeads } if parsed.Scheme != "ws" && parsed.Scheme != "wss" { - return nil, errors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) + return nil, pkgerrors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) } lggr := logger.Sugared(logger.Test(t)) @@ -50,7 +50,7 @@ func NewClientWithTestNode(t *testing.T, nodePoolCfg config.NodePool, noNewHeads var sendonlys []SendOnlyNode for i, url := range sendonlyRPCURLs { if url.Scheme != "http" && url.Scheme != "https" { - return nil, errors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", url.String()) + return nil, pkgerrors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", url.String()) } s := NewSendOnlyNode(lggr, url, fmt.Sprintf("eth-sendonly-%d", i), chainID) sendonlys = append(sendonlys, s) @@ -83,7 +83,7 @@ func NewChainClientWithTestNode( } if parsed.Scheme != "ws" && parsed.Scheme != "wss" { - return nil, errors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) + return nil, pkgerrors.Errorf("ethereum url scheme must be websocket: %s", parsed.String()) } lggr := logger.Test(t) @@ -96,7 +96,7 @@ func NewChainClientWithTestNode( var sendonlys []commonclient.SendOnlyNode[*big.Int, RPCCLient] for i, u := range sendonlyRPCURLs { if u.Scheme != "http" && u.Scheme != "https" { - return nil, errors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", u.String()) + return nil, pkgerrors.Errorf("sendonly ethereum rpc url scheme must be http(s): %s", u.String()) } var empty url.URL rpc := NewRPCClient(lggr, empty, &sendonlyRPCURLs[i], fmt.Sprintf("eth-sendonly-rpc-%d", i), id, chainID, commonclient.Secondary) diff --git a/core/chains/evm/client/node.go b/core/chains/evm/client/node.go index a27321535ed..2e83daa0421 100644 --- a/core/chains/evm/client/node.go +++ b/core/chains/evm/client/node.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/rpc" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -244,7 +244,7 @@ func (n *node) start(startCtx context.Context) { verifyCtx, verifyCancel := n.makeQueryCtx(startCtx) defer verifyCancel() - if err := n.verify(verifyCtx); errors.Is(err, errInvalidChainID) { + if err := n.verify(verifyCtx); pkgerrors.Is(err, errInvalidChainID) { n.lfcLog.Errorw("Verify failed: EVM Node has the wrong chain ID", "err", err) n.declareInvalidChainID() return @@ -273,7 +273,7 @@ func (n *node) dial(callerCtx context.Context) error { wsrpc, err := rpc.DialWebsocket(ctx, n.ws.uri.String(), "") if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(n.chainID.String(), n.name).Inc() - return errors.Wrapf(err, "error while dialing websocket: %v", n.ws.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing websocket: %v", n.ws.uri.Redacted()) } var httprpc *rpc.Client @@ -281,7 +281,7 @@ func (n *node) dial(callerCtx context.Context) error { httprpc, err = rpc.DialHTTP(n.http.uri.String()) if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(n.chainID.String(), n.name).Inc() - return errors.Wrapf(err, "error while dialing HTTP: %v", n.http.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing HTTP: %v", n.http.uri.Redacted()) } } @@ -298,7 +298,7 @@ func (n *node) dial(callerCtx context.Context) error { return nil } -var errInvalidChainID = errors.New("invalid chain id") +var errInvalidChainID = pkgerrors.New("invalid chain id") // verify checks that all connections to eth nodes match the given chain ID // Not thread-safe @@ -322,10 +322,10 @@ func (n *node) verify(callerCtx context.Context) (err error) { var chainID *big.Int if chainID, err = n.ws.geth.ChainID(ctx); err != nil { promFailed() - return errors.Wrapf(err, "failed to verify chain ID for node %s", n.name) + return pkgerrors.Wrapf(err, "failed to verify chain ID for node %s", n.name) } else if chainID.Cmp(n.chainID) != 0 { promFailed() - return errors.Wrapf( + return pkgerrors.Wrapf( errInvalidChainID, "websocket rpc ChainID doesn't match local chain ID: RPC ID=%s, local ID=%s, node name=%s", chainID.String(), @@ -336,10 +336,10 @@ func (n *node) verify(callerCtx context.Context) (err error) { if n.http != nil { if chainID, err = n.http.geth.ChainID(ctx); err != nil { promFailed() - return errors.Wrapf(err, "failed to verify chain ID for node %s", n.name) + return pkgerrors.Wrapf(err, "failed to verify chain ID for node %s", n.name) } else if chainID.Cmp(n.chainID) != 0 { promFailed() - return errors.Wrapf( + return pkgerrors.Wrapf( errInvalidChainID, "http rpc ChainID doesn't match local chain ID: RPC ID=%s, local ID=%s, node name=%s", chainID.String(), @@ -1066,10 +1066,10 @@ func wrap(err error, tp string) error { if err == nil { return nil } - if errors.Cause(err).Error() == "context deadline exceeded" { - err = errors.Wrap(err, "remote eth node timed out") + if pkgerrors.Cause(err).Error() == "context deadline exceeded" { + err = pkgerrors.Wrap(err, "remote eth node timed out") } - return errors.Wrapf(err, "%s call failed", tp) + return pkgerrors.Wrapf(err, "%s call failed", tp) } // makeLiveQueryCtxAndSafeGetClients wraps makeQueryCtx but returns error if node is not NodeStateAlive. @@ -1078,7 +1078,7 @@ func (n *node) makeLiveQueryCtxAndSafeGetClients(parentCtx context.Context) (ctx // context n.stateMu.RLock() if n.state != NodeStateAlive { - err = errors.Errorf("cannot execute RPC call on node with state: %s", n.state) + err = pkgerrors.Errorf("cannot execute RPC call on node with state: %s", n.state) n.stateMu.RUnlock() return } diff --git a/core/chains/evm/client/node_lifecycle.go b/core/chains/evm/client/node_lifecycle.go index f2232a14935..41add532222 100644 --- a/core/chains/evm/client/node_lifecycle.go +++ b/core/chains/evm/client/node_lifecycle.go @@ -7,7 +7,7 @@ import ( "math/big" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -381,7 +381,7 @@ func (n *node) unreachableLoop() { err = n.verify(n.nodeCtx) - if errors.Is(err, errInvalidChainID) { + if pkgerrors.Is(err, errInvalidChainID) { lggr.Errorw("Failed to redial RPC node; remote endpoint returned the wrong chain ID", "err", err) n.declareInvalidChainID() return @@ -426,7 +426,7 @@ func (n *node) invalidChainIDLoop() { return case <-time.After(chainIDRecheckBackoff.Duration()): err := n.verify(n.nodeCtx) - if errors.Is(err, errInvalidChainID) { + if pkgerrors.Is(err, errInvalidChainID) { lggr.Errorw("Failed to verify RPC node; remote endpoint returned the wrong chain ID", "err", err) continue } else if err != nil { diff --git a/core/chains/evm/client/pool.go b/core/chains/evm/client/pool.go index b2d5a4847a5..47650c9e9aa 100644 --- a/core/chains/evm/client/pool.go +++ b/core/chains/evm/client/pool.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -133,12 +133,12 @@ func NewPool(lggr logger.Logger, selectionMode string, leaseDuration time.Durati func (p *Pool) Dial(ctx context.Context) error { return p.StartOnce("Pool", func() (merr error) { if len(p.nodes) == 0 { - return errors.Errorf("no available nodes for chain %s", p.chainID.String()) + return pkgerrors.Errorf("no available nodes for chain %s", p.chainID.String()) } var ms services.MultiStart for _, n := range p.nodes { if n.ChainID().Cmp(p.chainID) != 0 { - return ms.CloseBecause(errors.Errorf("node %s has chain ID %s which does not match pool chain ID of %s", n.String(), n.ChainID().String(), p.chainID.String())) + return ms.CloseBecause(pkgerrors.Errorf("node %s has chain ID %s which does not match pool chain ID of %s", n.String(), n.ChainID().String(), p.chainID.String())) } rawNode, ok := n.(*node) if ok { @@ -155,7 +155,7 @@ func (p *Pool) Dial(ctx context.Context) error { } for _, s := range p.sendonlys { if s.ChainID().Cmp(p.chainID) != 0 { - return ms.CloseBecause(errors.Errorf("sendonly node %s has chain ID %s which does not match pool chain ID of %s", s.String(), s.ChainID().String(), p.chainID.String())) + return ms.CloseBecause(pkgerrors.Errorf("sendonly node %s has chain ID %s which does not match pool chain ID of %s", s.String(), s.ChainID().String(), p.chainID.String())) } if err := ms.Start(ctx, s); err != nil { return err diff --git a/core/chains/evm/client/rpc_client.go b/core/chains/evm/client/rpc_client.go index ce3a67162ed..8082972f10f 100644 --- a/core/chains/evm/client/rpc_client.go +++ b/core/chains/evm/client/rpc_client.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/rpc" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -126,7 +126,7 @@ func (r *rpcClient) Dial(callerCtx context.Context) error { wsrpc, err := rpc.DialWebsocket(ctx, r.ws.uri.String(), "") if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(r.chainID.String(), r.name).Inc() - return errors.Wrapf(err, "error while dialing websocket: %v", r.ws.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing websocket: %v", r.ws.uri.Redacted()) } r.ws.rpc = wsrpc @@ -155,7 +155,7 @@ func (r *rpcClient) DialHTTP() error { httprpc, err := rpc.DialHTTP(r.http.uri.String()) if err != nil { promEVMPoolRPCNodeDialsFailed.WithLabelValues(r.chainID.String(), r.name).Inc() - return errors.Wrapf(err, "error while dialing HTTP: %v", r.http.uri.Redacted()) + return pkgerrors.Wrapf(err, "error while dialing HTTP: %v", r.http.uri.Redacted()) } r.http.rpc = httprpc @@ -582,7 +582,7 @@ func (r *rpcClient) SendTransaction(ctx context.Context, tx *types.Transaction) func (r *rpcClient) SimulateTransaction(ctx context.Context, tx *types.Transaction) error { // Not Implemented - return errors.New("SimulateTransaction not implemented") + return pkgerrors.New("SimulateTransaction not implemented") } func (r *rpcClient) SendEmptyTransaction( @@ -594,7 +594,7 @@ func (r *rpcClient) SendEmptyTransaction( fromAddress common.Address, ) (txhash string, err error) { // Not Implemented - return "", errors.New("SendEmptyTransaction not implemented") + return "", pkgerrors.New("SendEmptyTransaction not implemented") } // PendingSequenceAt returns one higher than the highest nonce from both mempool and mined transactions @@ -988,10 +988,10 @@ func wrapCallError(err error, tp string) error { if err == nil { return nil } - if errors.Cause(err).Error() == "context deadline exceeded" { - err = errors.Wrap(err, "remote node timed out") + if pkgerrors.Cause(err).Error() == "context deadline exceeded" { + err = pkgerrors.Wrap(err, "remote node timed out") } - return errors.Wrapf(err, "%s call failed", tp) + return pkgerrors.Wrapf(err, "%s call failed", tp) } func (r *rpcClient) wrapWS(err error) error { diff --git a/core/chains/evm/forwarders/forwarder_manager.go b/core/chains/evm/forwarders/forwarder_manager.go index cabedf79aee..452bb87cae2 100644 --- a/core/chains/evm/forwarders/forwarder_manager.go +++ b/core/chains/evm/forwarders/forwarder_manager.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -82,7 +82,7 @@ func (f *FwdMgr) Start(ctx context.Context) error { fwdrs, err := f.ORM.FindForwardersByChain(big.Big(*chainId)) if err != nil { - return errors.Wrapf(err, "Failed to retrieve forwarders for chain %d", chainId) + return pkgerrors.Wrapf(err, "Failed to retrieve forwarders for chain %d", chainId) } if len(fwdrs) != 0 { f.initForwardersCache(ctx, fwdrs) @@ -93,12 +93,12 @@ func (f *FwdMgr) Start(ctx context.Context) error { f.authRcvr, err = authorized_receiver.NewAuthorizedReceiver(common.Address{}, f.evmClient) if err != nil { - return errors.Wrap(err, "Failed to init AuthorizedReceiver") + return pkgerrors.Wrap(err, "Failed to init AuthorizedReceiver") } f.offchainAgg, err = offchain_aggregator_wrapper.NewOffchainAggregator(common.Address{}, f.evmClient) if err != nil { - return errors.Wrap(err, "Failed to init OffchainAggregator") + return pkgerrors.Wrap(err, "Failed to init OffchainAggregator") } f.wg.Add(1) @@ -130,7 +130,7 @@ func (f *FwdMgr) ForwarderFor(addr common.Address) (forwarder common.Address, er } } } - return common.Address{}, errors.Errorf("Cannot find forwarder for given EOA") + return common.Address{}, pkgerrors.Errorf("Cannot find forwarder for given EOA") } func (f *FwdMgr) ConvertPayload(dest common.Address, origPayload []byte) ([]byte, error) { @@ -148,7 +148,7 @@ func (f *FwdMgr) ConvertPayload(dest common.Address, origPayload []byte) ([]byte func (f *FwdMgr) getForwardedPayload(dest common.Address, origPayload []byte) ([]byte, error) { callArgs, err := forwardABI.Inputs.Pack(dest, origPayload) if err != nil { - return nil, errors.Wrap(err, "Failed to pack forwarder payload") + return nil, pkgerrors.Wrap(err, "Failed to pack forwarder payload") } dataBytes := append(forwardABI.ID, callArgs...) @@ -161,7 +161,7 @@ func (f *FwdMgr) getContractSenders(addr common.Address) ([]common.Address, erro } senders, err := f.getAuthorizedSenders(f.ctx, addr) if err != nil { - return nil, errors.Wrapf(err, "Failed to call getAuthorizedSenders on %s", addr) + return nil, pkgerrors.Wrapf(err, "Failed to call getAuthorizedSenders on %s", addr) } f.setCachedSenders(addr, senders) if err = f.subscribeSendersChangedLogs(addr); err != nil { @@ -173,7 +173,7 @@ func (f *FwdMgr) getContractSenders(addr common.Address) ([]common.Address, erro func (f *FwdMgr) getAuthorizedSenders(ctx context.Context, addr common.Address) ([]common.Address, error) { c, err := authorized_receiver.NewAuthorizedReceiverCaller(addr, f.evmClient) if err != nil { - return nil, errors.Wrap(err, "Failed to init forwarder caller") + return nil, pkgerrors.Wrap(err, "Failed to init forwarder caller") } opts := bind.CallOpts{Context: ctx, Pending: false} senders, err := c.GetAuthorizedSenders(&opts) @@ -296,7 +296,7 @@ func (f *FwdMgr) handleAuthChange(log evmlogpoller.Log) error { if ethLog.Topics[0] == authChangedTopic { event, err := f.authRcvr.ParseAuthorizedSendersChanged(ethLog) if err != nil { - return errors.New("Failed to parse senders change log") + return pkgerrors.New("Failed to parse senders change log") } f.setCachedSenders(event.Raw.Address, event.Senders) } diff --git a/core/chains/evm/forwarders/orm.go b/core/chains/evm/forwarders/orm.go index 2a455360190..8b4ba5273a3 100644 --- a/core/chains/evm/forwarders/orm.go +++ b/core/chains/evm/forwarders/orm.go @@ -5,7 +5,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" @@ -64,7 +64,7 @@ func (o *orm) DeleteForwarder(id int64, cleanup func(tx pg.Queryer, evmChainID i // If the forwarder wasn't found, we still want to delete the filter. // In that case, the transaction must return nil, even though DeleteForwarder // will return sql.ErrNoRows - if err2 != nil && !errors.Is(err2, sql.ErrNoRows) { + if err2 != nil && !pkgerrors.Is(err2, sql.ErrNoRows) { return err2 } rowsAffected, err2 = result.RowsAffected() @@ -116,19 +116,19 @@ func (o *orm) FindForwardersInListByChain(evmChainId big.Big, addrs []common.Add ) if err != nil { - return nil, errors.Wrap(err, "Failed to format query") + return nil, pkgerrors.Wrap(err, "Failed to format query") } query, args, err = sqlx.In(query, args...) if err != nil { - return nil, errors.Wrap(err, "Failed to run sqlx.IN on query") + return nil, pkgerrors.Wrap(err, "Failed to run sqlx.IN on query") } query = o.q.Rebind(query) err = o.q.Select(&fwdrs, query, args...) if err != nil { - return nil, errors.Wrap(err, "Failed to execute query") + return nil, pkgerrors.Wrap(err, "Failed to execute query") } return fwdrs, nil diff --git a/core/chains/evm/gas/arbitrum_estimator.go b/core/chains/evm/gas/arbitrum_estimator.go index ca819ba04b3..07d2e4175f5 100644 --- a/core/chains/evm/gas/arbitrum_estimator.go +++ b/core/chains/evm/gas/arbitrum_estimator.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -74,7 +74,7 @@ func (a *arbitrumEstimator) Name() string { func (a *arbitrumEstimator) Start(ctx context.Context) error { return a.StartOnce("ArbitrumEstimator", func() error { if err := a.EvmEstimator.Start(ctx); err != nil { - return errors.Wrap(err, "failed to start gas price estimator") + return pkgerrors.Wrap(err, "failed to start gas price estimator") } go a.run() <-a.chInitialised @@ -84,7 +84,7 @@ func (a *arbitrumEstimator) Start(ctx context.Context) error { func (a *arbitrumEstimator) Close() error { return a.StopOnce("ArbitrumEstimator", func() (err error) { close(a.chStop) - err = errors.Wrap(a.EvmEstimator.Close(), "failed to stop gas price estimator") + err = pkgerrors.Wrap(a.EvmEstimator.Close(), "failed to stop gas price estimator") <-a.chDone return }) @@ -115,7 +115,7 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l select { case a.chForceRefetch <- ch: case <-a.chStop: - err = errors.New("estimator stopped") + err = pkgerrors.New("estimator stopped") return case <-ctx.Done(): err = ctx.Err() @@ -124,7 +124,7 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l select { case <-ch: case <-a.chStop: - err = errors.New("estimator stopped") + err = pkgerrors.New("estimator stopped") return case <-ctx.Done(): err = ctx.Err() @@ -137,7 +137,7 @@ func (a *arbitrumEstimator) GetLegacyGas(ctx context.Context, calldata []byte, l "perL1CalldataUnit", perL1CalldataUnit, "chainSpecificGasLimit", chainSpecificGasLimit) }) if !ok { - return nil, 0, errors.New("estimator is not started") + return nil, 0, pkgerrors.New("estimator is not started") } else if err != nil { return } diff --git a/core/chains/evm/gas/arbitrum_estimator_test.go b/core/chains/evm/gas/arbitrum_estimator_test.go index 9d56e2c10ad..4f026faae7f 100644 --- a/core/chains/evm/gas/arbitrum_estimator_test.go +++ b/core/chains/evm/gas/arbitrum_estimator_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -137,7 +137,7 @@ func TestArbitrumEstimator(t *testing.T) { ethClient := mocks.NewETHClient(t) o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{}, client, ethClient) - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) ethClient.On("CallContract", mock.Anything, mock.IsType(ethereum.CallMsg{}), mock.IsType(&big.Int{})).Run(func(args mock.Arguments) { callMsg := args.Get(1).(ethereum.CallMsg) blockNumber := args.Get(2).(*big.Int) diff --git a/core/chains/evm/gas/block_history_estimator.go b/core/chains/evm/gas/block_history_estimator.go index dc95240fd42..6adfe6b3b33 100644 --- a/core/chains/evm/gas/block_history_estimator.go +++ b/core/chains/evm/gas/block_history_estimator.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -204,7 +204,7 @@ func (b *BlockHistoryEstimator) Start(ctx context.Context) error { b.logger.Infof("Inclusion checking enabled, bumping will be prevented on transactions that have been priced above the %d percentile for %d blocks", b.bhConfig.CheckInclusionPercentile(), b.bhConfig.CheckInclusionBlocks()) } if b.bhConfig.BlockHistorySize() == 0 { - return errors.New("BlockHistorySize must be set to a value greater than 0") + return pkgerrors.New("BlockHistorySize must be set to a value greater than 0") } fetchCtx, cancel := context.WithTimeout(ctx, MaxStartTime) @@ -222,7 +222,7 @@ func (b *BlockHistoryEstimator) Start(ctx context.Context) error { // NOTE: This only checks the start context, not the fetch context if ctx.Err() != nil { - return errors.Wrap(ctx.Err(), "failed to start BlockHistoryEstimator due to main context error") + return pkgerrors.Wrap(ctx.Err(), "failed to start BlockHistoryEstimator due to main context error") } b.wg.Add(1) @@ -253,11 +253,11 @@ func (b *BlockHistoryEstimator) GetLegacyGas(_ context.Context, _ []byte, gasLim gasPrice = b.getGasPrice() }) if !ok { - return nil, 0, errors.New("BlockHistoryEstimator is not started; cannot estimate gas") + return nil, 0, pkgerrors.New("BlockHistoryEstimator is not started; cannot estimate gas") } if gasPrice == nil { if !b.initialFetch.Load() { - return nil, 0, errors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") + return nil, 0, pkgerrors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") } b.logger.Warnw("Failed to estimate gas price. This is likely because there aren't any valid transactions to estimate from."+ "Using Evm.GasEstimator.PriceDefault as fallback.", "blocks", b.getBlockHistoryNumbers()) @@ -290,7 +290,7 @@ func (b *BlockHistoryEstimator) getTipCap() *assets.Wei { func (b *BlockHistoryEstimator) BumpLegacyGas(_ context.Context, originalGasPrice *assets.Wei, gasLimit uint32, maxGasPriceWei *assets.Wei, attempts []EvmPriorAttempt) (bumpedGasPrice *assets.Wei, chainSpecificGasLimit uint32, err error) { if b.bhConfig.CheckInclusionBlocks() > 0 { if err = b.checkConnectivity(attempts); err != nil { - if errors.Is(err, commonfee.ErrConnectivity) { + if pkgerrors.Is(err, commonfee.ErrConnectivity) { b.logger.Criticalw(BumpingHaltedLabel, "err", err) b.SvcErrBuffer.Append(err) promBlockHistoryEstimatorConnectivityFailureCount.WithLabelValues(b.chainID.String(), "legacy").Inc() @@ -323,7 +323,7 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er if attempt.BroadcastBeforeBlockNum == nil { // this shouldn't happen; any broadcast attempt ought to have a // BroadcastBeforeBlockNum otherwise its an assumption violation - return errors.Errorf("BroadcastBeforeBlockNum was unexpectedly nil for attempt %s", attempt.TxHash) + return pkgerrors.Errorf("BroadcastBeforeBlockNum was unexpectedly nil for attempt %s", attempt.TxHash) } broadcastBeforeBlockNum := *attempt.BroadcastBeforeBlockNum blocksSinceBroadcast := *latestBlockNum - broadcastBeforeBlockNum @@ -353,11 +353,11 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er case 0x2: eip1559 = true default: - return errors.Errorf("attempt %s has unknown transaction type 0x%d", attempt.TxHash, attempt.TxType) + return pkgerrors.Errorf("attempt %s has unknown transaction type 0x%d", attempt.TxHash, attempt.TxType) } gasPrice, tipCap, err := b.calculatePercentilePrices(blocks, percentile, eip1559, nil, nil) if err != nil { - if errors.Is(err, ErrNoSuitableTransactions) { + if pkgerrors.Is(err, ErrNoSuitableTransactions) { b.logger.Warnf("no suitable transactions found to verify if transaction %s has been included within expected inclusion blocks of %d", attempt.TxHash, expectInclusionWithinBlocks) return nil } @@ -378,11 +378,11 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er } } if sufficientFeeCap && attempt.DynamicFee.TipCap.Cmp(tipCap) > 0 { - return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has tip cap of %s, which is above percentile=%d%% (percentile tip cap: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.DynamicFee.TipCap, percentile, tipCap, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) + return pkgerrors.Wrapf(commonfee.ErrConnectivity, "transaction %s has tip cap of %s, which is above percentile=%d%% (percentile tip cap: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.DynamicFee.TipCap, percentile, tipCap, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) } } else { if attempt.GasPrice.Cmp(gasPrice) > 0 { - return errors.Wrapf(commonfee.ErrConnectivity, "transaction %s has gas price of %s, which is above percentile=%d%% (percentile price: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.GasPrice, percentile, gasPrice, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) + return pkgerrors.Wrapf(commonfee.ErrConnectivity, "transaction %s has gas price of %s, which is above percentile=%d%% (percentile price: %s) for blocks %d thru %d (checking %d blocks)", attempt.TxHash, attempt.GasPrice, percentile, gasPrice, blockHistory[l-1].Number, blockHistory[0].Number, expectInclusionWithinBlocks) } } @@ -392,7 +392,7 @@ func (b *BlockHistoryEstimator) checkConnectivity(attempts []EvmPriorAttempt) er func (b *BlockHistoryEstimator) GetDynamicFee(_ context.Context, gasLimit uint32, maxGasPriceWei *assets.Wei) (fee DynamicFee, chainSpecificGasLimit uint32, err error) { if !b.eConfig.EIP1559DynamicFees() { - return fee, 0, errors.New("Can't get dynamic fee, EIP1559 is disabled") + return fee, 0, pkgerrors.New("Can't get dynamic fee, EIP1559 is disabled") } var feeCap *assets.Wei @@ -407,7 +407,7 @@ func (b *BlockHistoryEstimator) GetDynamicFee(_ context.Context, gasLimit uint32 tipCap = b.tipCap if tipCap == nil { if !b.initialFetch.Load() { - err = errors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") + err = pkgerrors.New("BlockHistoryEstimator has not finished the first gas estimation yet, likely because a failure on start") return } b.logger.Warnw("Failed to estimate gas price. This is likely because there aren't any valid transactions to estimate from."+ @@ -428,12 +428,12 @@ func (b *BlockHistoryEstimator) GetDynamicFee(_ context.Context, gasLimit uint32 // This shouldn't happen on EIP-1559 blocks, since if the tip cap // is set, Start must have succeeded and we would expect an initial // base fee to be set as well - err = errors.New("BlockHistoryEstimator: no value for latest block base fee; cannot estimate EIP-1559 base fee. Are you trying to run with EIP1559 enabled on a non-EIP1559 chain?") + err = pkgerrors.New("BlockHistoryEstimator: no value for latest block base fee; cannot estimate EIP-1559 base fee. Are you trying to run with EIP1559 enabled on a non-EIP1559 chain?") return } }) if !ok { - return fee, 0, errors.New("BlockHistoryEstimator is not started; cannot estimate gas") + return fee, 0, pkgerrors.New("BlockHistoryEstimator is not started; cannot estimate gas") } if err != nil { return fee, 0, err @@ -466,7 +466,7 @@ func calcFeeCap(latestAvailableBaseFeePerGas *assets.Wei, bufferBlocks int, tipC func (b *BlockHistoryEstimator) BumpDynamicFee(_ context.Context, originalFee DynamicFee, originalGasLimit uint32, maxGasPriceWei *assets.Wei, attempts []EvmPriorAttempt) (bumped DynamicFee, chainSpecificGasLimit uint32, err error) { if b.bhConfig.CheckInclusionBlocks() > 0 { if err = b.checkConnectivity(attempts); err != nil { - if errors.Is(err, commonfee.ErrConnectivity) { + if pkgerrors.Is(err, commonfee.ErrConnectivity) { b.logger.Criticalw(BumpingHaltedLabel, "err", err) b.SvcErrBuffer.Append(err) promBlockHistoryEstimatorConnectivityFailureCount.WithLabelValues(b.chainID.String(), "eip1559").Inc() @@ -533,7 +533,7 @@ func (b *BlockHistoryEstimator) Recalculate(head *evmtypes.Head) { } }) if err != nil { - if errors.Is(err, ErrNoSuitableTransactions) { + if pkgerrors.Is(err, ErrNoSuitableTransactions) { lggr.Debug("No suitable transactions, skipping") } else { lggr.Warnw("Cannot calculate percentile prices", "err", err) @@ -588,12 +588,12 @@ func (b *BlockHistoryEstimator) FetchBlocks(ctx context.Context, head *evmtypes. historySize := b.size if historySize <= 0 { - return errors.Errorf("BlockHistoryEstimator: history size must be > 0, got: %d", historySize) + return pkgerrors.Errorf("BlockHistoryEstimator: history size must be > 0, got: %d", historySize) } highestBlockToFetch := head.Number - blockDelay if highestBlockToFetch < 0 { - return errors.Errorf("BlockHistoryEstimator: cannot fetch, current block height %v is lower than EVM.RPCBlockQueryDelay=%v", head.Number, blockDelay) + return pkgerrors.Errorf("BlockHistoryEstimator: cannot fetch, current block height %v is lower than EVM.RPCBlockQueryDelay=%v", head.Number, blockDelay) } lowestBlockToFetch := head.Number - historySize - blockDelay + 1 if lowestBlockToFetch < 0 { @@ -641,7 +641,7 @@ func (b *BlockHistoryEstimator) FetchBlocks(ctx context.Context, head *evmtypes. for _, req := range reqs { result, err := req.Result, req.Error if err != nil { - if errors.Is(err, evmtypes.ErrMissingBlock) { + if pkgerrors.Is(err, evmtypes.ErrMissingBlock) { num := HexToInt64(req.Args[0]) missingBlocks = append(missingBlocks, num) lggr.Debugw( @@ -657,10 +657,10 @@ func (b *BlockHistoryEstimator) FetchBlocks(ctx context.Context, head *evmtypes. block, is := result.(*evmtypes.Block) if !is { - return errors.Errorf("expected result to be a %T, got %T", &evmtypes.Block{}, result) + return pkgerrors.Errorf("expected result to be a %T, got %T", &evmtypes.Block{}, result) } if block == nil { - return errors.New("invariant violation: got nil block") + return pkgerrors.New("invariant violation: got nil block") } if block.Hash == (common.Hash{}) { lggr.Warnw("Block was missing hash", "block", b, "headNum", head.Number, "blockNum", block.Number) @@ -716,26 +716,26 @@ func (b *BlockHistoryEstimator) batchFetch(ctx context.Context, reqs []rpc.Batch b.logger.Tracew(fmt.Sprintf("Batch fetching blocks %v thru %v", HexToInt64(reqs[i].Args[0]), HexToInt64(reqs[j-1].Args[0]))) err := b.ethClient.BatchCallContext(ctx, reqs[i:j]) - if errors.Is(err, context.DeadlineExceeded) { + if pkgerrors.Is(err, context.DeadlineExceeded) { // We ran out of time, return what we have b.logger.Warnf("Batch fetching timed out; loaded %d/%d results", i, len(reqs)) for k := i; k < len(reqs); k++ { if k < j { - reqs[k].Error = errors.Wrap(err, "request failed") + reqs[k].Error = pkgerrors.Wrap(err, "request failed") } else { - reqs[k].Error = errors.Wrap(err, "request skipped; previous request exceeded deadline") + reqs[k].Error = pkgerrors.Wrap(err, "request skipped; previous request exceeded deadline") } } return nil } else if err != nil { - return errors.Wrap(err, "BlockHistoryEstimator#fetchBlocks error fetching blocks with BatchCallContext") + return pkgerrors.Wrap(err, "BlockHistoryEstimator#fetchBlocks error fetching blocks with BatchCallContext") } } return nil } var ( - ErrNoSuitableTransactions = errors.New("no suitable transactions") + ErrNoSuitableTransactions = pkgerrors.New("no suitable transactions") ) func (b *BlockHistoryEstimator) calculatePercentilePrices(blocks []evmtypes.Block, percentile int, eip1559 bool, f func(gasPrices []*assets.Wei), f2 func(tipCaps []*assets.Wei)) (gasPrice, tipCap *assets.Wei, err error) { @@ -797,7 +797,7 @@ func (b *BlockHistoryEstimator) getPricesFromBlocks(blocks []evmtypes.Block, eip func verifyBlock(block evmtypes.Block, eip1559 bool) error { if eip1559 && block.BaseFeePerGas == nil { - return errors.New("EIP-1559 mode was enabled, but block was missing baseFeePerGas") + return pkgerrors.New("EIP-1559 mode was enabled, but block was missing baseFeePerGas") } return nil } diff --git a/core/chains/evm/gas/block_history_estimator_test.go b/core/chains/evm/gas/block_history_estimator_test.go index eae6fbc2ad3..e929cdd64ee 100644 --- a/core/chains/evm/gas/block_history_estimator_test.go +++ b/core/chains/evm/gas/block_history_estimator_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -143,7 +143,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { ethClient.On("BatchCallContext", mock.Anything, mock.MatchedBy(func(b []rpc.BatchElem) bool { return len(b) == 1 && b[0].Method == "eth_getBlockByNumber" && b[0].Args[0] == gas.Int64ToHex(41) && b[0].Args[1].(bool) && reflect.TypeOf(b[0].Result) == reflect.TypeOf(&evmtypes.Block{}) - })).Return(errors.Wrap(context.DeadlineExceeded, "some error message")).Once() + })).Return(pkgerrors.Wrap(context.DeadlineExceeded, "some error message")).Once() err := bhe.Start(testutils.Context(t)) require.NoError(t, err) @@ -177,7 +177,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { bhe := newBlockHistoryEstimator(t, ethClient, cfg, geCfg, bhCfg) - ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(nil, errors.New("something exploded")) + ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(nil, pkgerrors.New("something exploded")) err := bhe.Start(testutils.Context(t)) require.NoError(t, err) @@ -200,7 +200,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { h := &evmtypes.Head{Hash: utils.NewHash(), Number: 42, BaseFeePerGas: assets.NewWeiI(420)} ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h, nil) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("something went wrong")) + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("something went wrong")) err := bhe.Start(testutils.Context(t)) require.NoError(t, err) @@ -223,7 +223,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { h := &evmtypes.Head{Hash: utils.NewHash(), Number: 42, BaseFeePerGas: assets.NewWeiI(420)} ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h, nil) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("this error doesn't matter")) + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("this error doesn't matter")) ctx, cancel := context.WithCancel(testutils.Context(t)) cancel() @@ -239,7 +239,7 @@ func TestBlockHistoryEstimator_Start(t *testing.T) { h := &evmtypes.Head{Hash: utils.NewHash(), Number: 42, BaseFeePerGas: assets.NewWeiI(420)} ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(h, nil) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("this error doesn't matter")).Run(func(_ mock.Arguments) { + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("this error doesn't matter")).Run(func(_ mock.Arguments) { time.Sleep(gas.MaxStartTime + 1*time.Second) }) @@ -342,7 +342,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { bhe := newBlockHistoryEstimator(t, ethClient, cfg, geCfg, bhCfg) - ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(errors.New("something exploded")) + ethClient.On("BatchCallContext", mock.Anything, mock.Anything).Return(pkgerrors.New("something exploded")) err := bhe.FetchBlocks(testutils.Context(t), cltest.Head(42)) require.Error(t, err) @@ -390,7 +390,7 @@ func TestBlockHistoryEstimator_FetchBlocks(t *testing.T) { elems := args.Get(1).([]rpc.BatchElem) elems[0].Result = &b43 // This errored block (42) will be ignored - elems[1].Error = errors.New("something went wrong") + elems[1].Error = pkgerrors.New("something went wrong") }) ethClient.On("BatchCallContext", mock.Anything, mock.MatchedBy(func(b []rpc.BatchElem) bool { return len(b) == 1 && @@ -2363,7 +2363,7 @@ func TestBlockHistoryEstimator_Bumps(t *testing.T) { _, _, err := bhe.BumpLegacyGas(testutils.Context(t), assets.NewWeiI(42), 100000, maxGasPrice, attempts) require.Error(t, err) - assert.True(t, errors.Is(err, commonfee.ErrConnectivity)) + assert.True(t, pkgerrors.Is(err, commonfee.ErrConnectivity)) assert.Contains(t, err.Error(), fmt.Sprintf("transaction %s has gas price of 1 kwei, which is above percentile=10%% (percentile price: 1 wei) for blocks 1 thru 1 (checking 1 blocks)", attempts[0].TxHash)) }) @@ -2476,7 +2476,7 @@ func TestBlockHistoryEstimator_Bumps(t *testing.T) { _, _, err := bhe.BumpDynamicFee(testutils.Context(t), originalFee, 100000, maxGasPrice, attempts) require.Error(t, err) - assert.True(t, errors.Is(err, commonfee.ErrConnectivity)) + assert.True(t, pkgerrors.Is(err, commonfee.ErrConnectivity)) assert.Contains(t, err.Error(), fmt.Sprintf("transaction %s has tip cap of 25 wei, which is above percentile=10%% (percentile tip cap: 1 wei) for blocks 1 thru 1 (checking 1 blocks)", attempts[0].TxHash)) }) diff --git a/core/chains/evm/gas/fixed_price_estimator.go b/core/chains/evm/gas/fixed_price_estimator.go index 4d9f45a1bd4..a69be3b0d05 100644 --- a/core/chains/evm/gas/fixed_price_estimator.go +++ b/core/chains/evm/gas/fixed_price_estimator.go @@ -3,7 +3,7 @@ package gas import ( "context" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" commonfee "github.com/smartcontractkit/chainlink/v2/common/fee" @@ -99,7 +99,7 @@ func (f *fixedPriceEstimator) GetDynamicFee(_ context.Context, originalGasLimit gasTipCap := f.config.TipCapDefault() if gasTipCap == nil { - return d, 0, errors.New("cannot calculate dynamic fee: EthGasTipCapDefault was not set") + return d, 0, pkgerrors.New("cannot calculate dynamic fee: EthGasTipCapDefault was not set") } chainSpecificGasLimit, err = commonfee.ApplyMultiplier(originalGasLimit, f.config.LimitMultiplier()) if err != nil { diff --git a/core/chains/evm/gas/models.go b/core/chains/evm/gas/models.go index 8d977df0991..7935a7f534f 100644 --- a/core/chains/evm/gas/models.go +++ b/core/chains/evm/gas/models.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -187,11 +187,11 @@ func (e *WrappedEvmEstimator) Name() string { func (e *WrappedEvmEstimator) Start(ctx context.Context) error { return e.StartOnce(e.Name(), func() error { if err := e.EvmEstimator.Start(ctx); err != nil { - return errors.Wrap(err, "failed to start EVMEstimator") + return pkgerrors.Wrap(err, "failed to start EVMEstimator") } if e.l1Oracle != nil { if err := e.l1Oracle.Start(ctx); err != nil { - return errors.Wrap(err, "failed to start L1Oracle") + return pkgerrors.Wrap(err, "failed to start L1Oracle") } } return nil @@ -201,9 +201,9 @@ func (e *WrappedEvmEstimator) Close() error { return e.StopOnce(e.Name(), func() error { var errEVM, errOracle error - errEVM = errors.Wrap(e.EvmEstimator.Close(), "failed to stop EVMEstimator") + errEVM = pkgerrors.Wrap(e.EvmEstimator.Close(), "failed to stop EVMEstimator") if e.l1Oracle != nil { - errOracle = errors.Wrap(e.l1Oracle.Close(), "failed to stop L1Oracle") + errOracle = pkgerrors.Wrap(e.l1Oracle.Close(), "failed to stop L1Oracle") } if errEVM != nil { @@ -277,7 +277,7 @@ func (e *WrappedEvmEstimator) GetMaxCost(ctx context.Context, amount assets.Eth, func (e *WrappedEvmEstimator) BumpFee(ctx context.Context, originalFee EvmFee, feeLimit uint32, maxFeePrice *assets.Wei, attempts []EvmPriorAttempt) (bumpedFee EvmFee, chainSpecificFeeLimit uint32, err error) { // validate only 1 fee type is present if (!originalFee.ValidDynamic() && originalFee.Legacy == nil) || (originalFee.ValidDynamic() && originalFee.Legacy != nil) { - err = errors.New("only one dynamic or legacy fee can be defined") + err = pkgerrors.New("only one dynamic or legacy fee can be defined") return } @@ -377,13 +377,13 @@ func bumpGasPrice(cfg bumpConfig, lggr logger.SugaredLogger, currentGasPrice, or bumpedGasPrice = maxBumpedFee(lggr, currentGasPrice, bumpedGasPrice, maxGasPrice, "gas price") if bumpedGasPrice.Cmp(maxGasPrice) > 0 { - return maxGasPrice, errors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped gas price of %s would exceed configured max gas price of %s (original price was %s). %s", + return maxGasPrice, pkgerrors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped gas price of %s would exceed configured max gas price of %s (original price was %s). %s", bumpedGasPrice.String(), maxGasPrice, originalGasPrice.String(), label.NodeConnectivityProblemWarning) } else if bumpedGasPrice.Cmp(originalGasPrice) == 0 { // NOTE: This really shouldn't happen since we enforce minimums for // EVM.GasEstimator.BumpPercent and EVM.GasEstimator.BumpMin in the config validation, // but it's here anyway for a "belts and braces" approach - return bumpedGasPrice, errors.Wrapf(commonfee.ErrBump, "bumped gas price of %s is equal to original gas price of %s."+ + return bumpedGasPrice, pkgerrors.Wrapf(commonfee.ErrBump, "bumped gas price of %s is equal to original gas price of %s."+ " ACTION REQUIRED: This is a configuration error, you must increase either "+ "EVM.GasEstimator.BumpPercent or EVM.GasEstimator.BumpMin", bumpedGasPrice.String(), originalGasPrice.String()) } @@ -419,13 +419,13 @@ func bumpDynamicFee(cfg bumpConfig, feeCapBufferBlocks uint16, lggr logger.Sugar bumpedTipCap = maxBumpedFee(lggr, currentTipCap, bumpedTipCap, maxGasPrice, "tip cap") if bumpedTipCap.Cmp(maxGasPrice) > 0 { - return bumpedFee, errors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped tip cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", + return bumpedFee, pkgerrors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped tip cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", bumpedTipCap.String(), maxGasPrice, originalFee.TipCap.String(), originalFee.FeeCap.String(), label.NodeConnectivityProblemWarning) } else if bumpedTipCap.Cmp(originalFee.TipCap) <= 0 { // NOTE: This really shouldn't happen since we enforce minimums for // EVM.GasEstimator.BumpPercent and EVM.GasEstimator.BumpMin in the config validation, // but it's here anyway for a "belts and braces" approach - return bumpedFee, errors.Wrapf(commonfee.ErrBump, "bumped gas tip cap of %s is less than or equal to original gas tip cap of %s."+ + return bumpedFee, pkgerrors.Wrapf(commonfee.ErrBump, "bumped gas tip cap of %s is less than or equal to original gas tip cap of %s."+ " ACTION REQUIRED: This is a configuration error, you must increase either "+ "EVM.GasEstimator.BumpPercent or EVM.GasEstimator.BumpMin", bumpedTipCap.String(), originalFee.TipCap.String()) } @@ -445,7 +445,7 @@ func bumpDynamicFee(cfg bumpConfig, feeCapBufferBlocks uint16, lggr logger.Sugar } if bumpedFeeCap.Cmp(maxGasPrice) > 0 { - return bumpedFee, errors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped fee cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", + return bumpedFee, pkgerrors.Wrapf(commonfee.ErrBumpFeeExceedsLimit, "bumped fee cap of %s would exceed configured max gas price of %s (original fee: tip cap %s, fee cap %s). %s", bumpedFeeCap.String(), maxGasPrice, originalFee.TipCap.String(), originalFee.FeeCap.String(), label.NodeConnectivityProblemWarning) } diff --git a/core/chains/evm/gas/models_test.go b/core/chains/evm/gas/models_test.go index 95a7a471eba..9c0e63a602b 100644 --- a/core/chains/evm/gas/models_test.go +++ b/core/chains/evm/gas/models_test.go @@ -4,7 +4,7 @@ import ( "math/big" "testing" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -201,9 +201,9 @@ func TestWrappedEvmEstimator(t *testing.T) { oracle := rollupMocks.NewL1Oracle(t) evmEstimatorKey := "evm" - evmEstimatorError := errors.New("evm error") + evmEstimatorError := pkgerrors.New("evm error") oracleKey := "oracle" - oracleError := errors.New("oracle error") + oracleError := pkgerrors.New("oracle error") evmEstimator.On("HealthReport").Return(map[string]error{evmEstimatorKey: evmEstimatorError}).Twice() oracle.On("HealthReport").Return(map[string]error{oracleKey: oracleError}).Once() @@ -211,14 +211,14 @@ func TestWrappedEvmEstimator(t *testing.T) { estimator := gas.NewWrappedEvmEstimator(lggr, getEst, false, nil) report := estimator.HealthReport() - require.True(t, errors.Is(report[evmEstimatorKey], evmEstimatorError)) + require.True(t, pkgerrors.Is(report[evmEstimatorKey], evmEstimatorError)) require.Nil(t, report[oracleKey]) require.NotNil(t, report[mockEstimatorName]) estimator = gas.NewWrappedEvmEstimator(lggr, getEst, false, oracle) report = estimator.HealthReport() - require.True(t, errors.Is(report[evmEstimatorKey], evmEstimatorError)) - require.True(t, errors.Is(report[oracleKey], oracleError)) + require.True(t, pkgerrors.Is(report[evmEstimatorKey], evmEstimatorError)) + require.True(t, pkgerrors.Is(report[oracleKey], oracleError)) require.NotNil(t, report[mockEstimatorName]) }) } diff --git a/core/chains/evm/gas/suggested_price_estimator.go b/core/chains/evm/gas/suggested_price_estimator.go index 3b02b7f4362..08a55bd9b90 100644 --- a/core/chains/evm/gas/suggested_price_estimator.go +++ b/core/chains/evm/gas/suggested_price_estimator.go @@ -7,7 +7,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -125,12 +125,12 @@ func (o *SuggestedPriceEstimator) refreshPrice() (t *time.Timer) { func (o *SuggestedPriceEstimator) OnNewLongestChain(context.Context, *evmtypes.Head) {} func (*SuggestedPriceEstimator) GetDynamicFee(_ context.Context, _ uint32, _ *assets.Wei) (fee DynamicFee, chainSpecificGasLimit uint32, err error) { - err = errors.New("dynamic fees are not implemented for this layer 2") + err = pkgerrors.New("dynamic fees are not implemented for this layer 2") return } func (*SuggestedPriceEstimator) BumpDynamicFee(_ context.Context, _ DynamicFee, _ uint32, _ *assets.Wei, _ []EvmPriorAttempt) (bumped DynamicFee, chainSpecificGasLimit uint32, err error) { - err = errors.New("dynamic fees are not implemented for this layer 2") + err = pkgerrors.New("dynamic fees are not implemented for this layer 2") return } @@ -143,7 +143,7 @@ func (o *SuggestedPriceEstimator) GetLegacyGas(ctx context.Context, _ []byte, Ga select { case o.chForceRefetch <- ch: case <-o.chStop: - err = errors.New("estimator stopped") + err = pkgerrors.New("estimator stopped") return case <-ctx.Done(): err = ctx.Err() @@ -152,7 +152,7 @@ func (o *SuggestedPriceEstimator) GetLegacyGas(ctx context.Context, _ []byte, Ga select { case <-ch: case <-o.chStop: - err = errors.New("estimator stopped") + err = pkgerrors.New("estimator stopped") return case <-ctx.Done(): err = ctx.Err() @@ -160,25 +160,25 @@ func (o *SuggestedPriceEstimator) GetLegacyGas(ctx context.Context, _ []byte, Ga } } if gasPrice = o.getGasPrice(); gasPrice == nil { - err = errors.New("failed to estimate gas; gas price not set") + err = pkgerrors.New("failed to estimate gas; gas price not set") return } o.logger.Debugw("GetLegacyGas", "GasPrice", gasPrice, "GasLimit", GasLimit) }) if !ok { - return nil, 0, errors.New("estimator is not started") + return nil, 0, pkgerrors.New("estimator is not started") } else if err != nil { return } // For L2 chains, submitting a transaction that is not priced high enough will cause the call to fail, so if the cap is lower than the RPC suggested gas price, this transaction cannot succeed if gasPrice != nil && gasPrice.Cmp(maxGasPriceWei) > 0 { - return nil, 0, errors.Errorf("estimated gas price: %s is greater than the maximum gas price configured: %s", gasPrice.String(), maxGasPriceWei.String()) + return nil, 0, pkgerrors.Errorf("estimated gas price: %s is greater than the maximum gas price configured: %s", gasPrice.String(), maxGasPriceWei.String()) } return } func (o *SuggestedPriceEstimator) BumpLegacyGas(_ context.Context, _ *assets.Wei, _ uint32, _ *assets.Wei, _ []EvmPriorAttempt) (bumpedGasPrice *assets.Wei, chainSpecificGasLimit uint32, err error) { - return nil, 0, errors.New("bump gas is not supported for this chain") + return nil, 0, pkgerrors.New("bump gas is not supported for this chain") } func (o *SuggestedPriceEstimator) getGasPrice() (GasPrice *assets.Wei) { diff --git a/core/chains/evm/gas/suggested_price_estimator_test.go b/core/chains/evm/gas/suggested_price_estimator_test.go index 8e45f5b759a..d2a0271df6d 100644 --- a/core/chains/evm/gas/suggested_price_estimator_test.go +++ b/core/chains/evm/gas/suggested_price_estimator_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -92,7 +92,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { client := mocks.NewRPCClient(t) o := gas.NewSuggestedPriceEstimator(logger.Test(t), client) - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) servicetest.RunHealthy(t, o) diff --git a/core/chains/evm/headtracker/head_listener_test.go b/core/chains/evm/headtracker/head_listener_test.go index 3ba9c0863da..e5131aca422 100644 --- a/core/chains/evm/headtracker/head_listener_test.go +++ b/core/chains/evm/headtracker/head_listener_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -155,7 +155,7 @@ func Test_HeadListener_SubscriptionErr(t *testing.T) { closeErr bool }{ {"nil error", nil, false}, - {"socket error", errors.New("close 1006 (abnormal closure): unexpected EOF"), false}, + {"socket error", pkgerrors.New("close 1006 (abnormal closure): unexpected EOF"), false}, {"close Err channel", nil, true}, } diff --git a/core/chains/evm/headtracker/orm.go b/core/chains/evm/headtracker/orm.go index 859f6764b63..a1957388b9b 100644 --- a/core/chains/evm/headtracker/orm.go +++ b/core/chains/evm/headtracker/orm.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -47,7 +47,7 @@ func (orm *orm) IdempotentInsertHead(ctx context.Context, head *evmtypes.Head) e :hash, :number, :parent_hash, :created_at, :timestamp, :l1_block_number, :evm_chain_id, :base_fee_per_gas) ON CONFLICT (evm_chain_id, hash) DO NOTHING` err := q.ExecQNamed(query, head) - return errors.Wrap(err, "IdempotentInsertHead failed to insert head") + return pkgerrors.Wrap(err, "IdempotentInsertHead failed to insert head") } func (orm *orm) TrimOldHeads(ctx context.Context, n uint) (err error) { @@ -69,17 +69,17 @@ func (orm *orm) LatestHead(ctx context.Context) (head *evmtypes.Head, err error) head = new(evmtypes.Head) q := orm.q.WithOpts(pg.WithParentCtx(ctx)) err = q.Get(head, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT 1`, orm.chainID) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } - err = errors.Wrap(err, "LatestHead failed") + err = pkgerrors.Wrap(err, "LatestHead failed") return } func (orm *orm) LatestHeads(ctx context.Context, limit uint) (heads []*evmtypes.Head, err error) { q := orm.q.WithOpts(pg.WithParentCtx(ctx)) err = q.Select(&heads, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT $2`, orm.chainID, limit) - err = errors.Wrap(err, "LatestHeads failed") + err = pkgerrors.Wrap(err, "LatestHeads failed") return } @@ -87,7 +87,7 @@ func (orm *orm) HeadByHash(ctx context.Context, hash common.Hash) (head *evmtype q := orm.q.WithOpts(pg.WithParentCtx(ctx)) head = new(evmtypes.Head) err = q.Get(head, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 AND hash = $2`, orm.chainID, hash) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } return head, err diff --git a/core/chains/evm/log/broadcaster.go b/core/chains/evm/log/broadcaster.go index 8321dd30bfe..c4db2a4826c 100644 --- a/core/chains/evm/log/broadcaster.go +++ b/core/chains/evm/log/broadcaster.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -773,13 +773,13 @@ func (n *NullBroadcaster) TrackedAddressesCount() uint32 { return 0 } func (n *NullBroadcaster) WasAlreadyConsumed(lb Broadcast, qopts ...pg.QOpt) (bool, error) { - return false, errors.New(n.ErrMsg) + return false, pkgerrors.New(n.ErrMsg) } func (n *NullBroadcaster) MarkConsumed(lb Broadcast, qopts ...pg.QOpt) error { - return errors.New(n.ErrMsg) + return pkgerrors.New(n.ErrMsg) } func (n *NullBroadcaster) MarkManyConsumed(lbs []Broadcast, qopts ...pg.QOpt) error { - return errors.New(n.ErrMsg) + return pkgerrors.New(n.ErrMsg) } func (n *NullBroadcaster) AddDependents(int) {} diff --git a/core/chains/evm/log/orm.go b/core/chains/evm/log/orm.go index 51ed9f2f132..25012d5c8e0 100644 --- a/core/chains/evm/log/orm.go +++ b/core/chains/evm/log/orm.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -75,7 +75,7 @@ func (o *orm) WasBroadcastConsumed(blockHash common.Hash, logIndex uint, jobID i } q := o.q.WithOpts(qopts...) err = q.Get(&consumed, query, args...) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return false, nil } return consumed, err @@ -91,7 +91,7 @@ func (o *orm) FindBroadcasts(fromBlockNum int64, toBlockNum int64) ([]LogBroadca ` err := o.q.Select(&broadcasts, query, fromBlockNum, toBlockNum, o.evmChainID) if err != nil { - return nil, errors.Wrap(err, "failed to find log broadcasts") + return nil, pkgerrors.Wrap(err, "failed to find log broadcasts") } return broadcasts, err } @@ -102,7 +102,7 @@ func (o *orm) CreateBroadcast(blockHash common.Hash, blockNumber uint64, logInde INSERT INTO log_broadcasts (block_hash, block_number, log_index, job_id, created_at, updated_at, consumed, evm_chain_id) VALUES ($1, $2, $3, $4, NOW(), NOW(), false, $5) `, blockHash, blockNumber, logIndex, jobID, o.evmChainID) - return errors.Wrap(err, "failed to create log broadcast") + return pkgerrors.Wrap(err, "failed to create log broadcast") } func (o *orm) MarkBroadcastConsumed(blockHash common.Hash, blockNumber uint64, logIndex uint, jobID int32, qopts ...pg.QOpt) error { @@ -113,7 +113,7 @@ func (o *orm) MarkBroadcastConsumed(blockHash common.Hash, blockNumber uint64, l ON CONFLICT (job_id, block_hash, log_index, evm_chain_id) DO UPDATE SET consumed = true, updated_at = NOW() `, blockHash, blockNumber, logIndex, jobID, o.evmChainID) - return errors.Wrap(err, "failed to mark log broadcast as consumed") + return pkgerrors.Wrap(err, "failed to mark log broadcast as consumed") } // MarkBroadcastsConsumed marks many broadcasts as consumed. @@ -150,7 +150,7 @@ SET consumed = true, updated_at = NOW(); } q := o.q.WithOpts(qopts...) _, err := q.NamedExec(query, inputs) - return errors.Wrap(err, "mark broadcasts consumed") + return pkgerrors.Wrap(err, "mark broadcasts consumed") } // MarkBroadcastsUnconsumed implements the ORM interface. @@ -162,7 +162,7 @@ func (o *orm) MarkBroadcastsUnconsumed(fromBlock int64, qopts ...pg.QOpt) error WHERE block_number >= $1 AND evm_chain_id = $2 `, fromBlock, o.evmChainID) - return errors.Wrap(err, "failed to mark broadcasts unconsumed") + return pkgerrors.Wrap(err, "failed to mark broadcasts unconsumed") } func (o *orm) Reinitialize(qopts ...pg.QOpt) (*int64, error) { @@ -201,7 +201,7 @@ func (o *orm) SetPendingMinBlock(blockNumber *int64, qopts ...pg.QOpt) error { INSERT INTO log_broadcasts_pending (evm_chain_id, block_number, created_at, updated_at) VALUES ($1, $2, NOW(), NOW()) ON CONFLICT (evm_chain_id) DO UPDATE SET block_number = $3, updated_at = NOW() `, o.evmChainID, blockNumber, blockNumber) - return errors.Wrap(err, "failed to set pending broadcast block number") + return pkgerrors.Wrap(err, "failed to set pending broadcast block number") } func (o *orm) GetPendingMinBlock(qopts ...pg.QOpt) (*int64, error) { @@ -210,10 +210,10 @@ func (o *orm) GetPendingMinBlock(qopts ...pg.QOpt) (*int64, error) { err := q.Get(&blockNumber, ` SELECT block_number FROM log_broadcasts_pending WHERE evm_chain_id = $1 `, o.evmChainID) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } else if err != nil { - return nil, errors.Wrap(err, "failed to get broadcasts pending number") + return nil, pkgerrors.Wrap(err, "failed to get broadcasts pending number") } return blockNumber, nil } @@ -227,10 +227,10 @@ func (o *orm) getUnconsumedMinBlock(qopts ...pg.QOpt) (*int64, error) { AND consumed = false AND block_number IS NOT NULL `, o.evmChainID) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } else if err != nil { - return nil, errors.Wrap(err, "failed to get unconsumed broadcasts min block number") + return nil, pkgerrors.Wrap(err, "failed to get unconsumed broadcasts min block number") } return blockNumber, nil } @@ -243,7 +243,7 @@ func (o *orm) removeUnconsumed(qopts ...pg.QOpt) error { AND consumed = false AND block_number IS NOT NULL `, o.evmChainID) - return errors.Wrap(err, "failed to delete unconsumed broadcasts") + return pkgerrors.Wrap(err, "failed to delete unconsumed broadcasts") } // LogBroadcast - data from log_broadcasts table columns diff --git a/core/chains/evm/log/registrations.go b/core/chains/evm/log/registrations.go index 346a6776e86..1bb6c8c59c0 100644 --- a/core/chains/evm/log/registrations.go +++ b/core/chains/evm/log/registrations.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" @@ -119,12 +119,12 @@ func (r *registrations) handlersWithGreaterConfs(confs uint32) (handlersWithGrea // maps modified are only used for checks func (r *registrations) checkAddSubscriber(sub *subscriber) error { if sub.opts.MinIncomingConfirmations <= 0 { - return errors.Errorf("LogBroadcaster requires that MinIncomingConfirmations must be at least 1 (got %v). Logs must have been confirmed in at least 1 block, it does not support reading logs from the mempool before they have been mined", sub.opts.MinIncomingConfirmations) + return pkgerrors.Errorf("LogBroadcaster requires that MinIncomingConfirmations must be at least 1 (got %v). Logs must have been confirmed in at least 1 block, it does not support reading logs from the mempool before they have been mined", sub.opts.MinIncomingConfirmations) } jobID := sub.listener.JobID() if _, exists := r.registeredSubs[sub]; exists { - return errors.Errorf("Cannot add subscriber %p for job ID %v: already added", sub, jobID) + return pkgerrors.Errorf("Cannot add subscriber %p for job ID %v: already added", sub, jobID) } r.registeredSubs[sub] = struct{}{} addrs, exists := r.jobIDAddrs[jobID] @@ -132,7 +132,7 @@ func (r *registrations) checkAddSubscriber(sub *subscriber) error { r.jobIDAddrs[jobID] = make(map[common.Address]struct{}) } if _, exists := addrs[sub.opts.Contract]; exists { - return errors.Errorf("Cannot add subscriber %p: only one subscription is allowed per jobID/contract address. There is already a subscription with job ID %v listening on %s", sub, jobID, sub.opts.Contract.Hex()) + return pkgerrors.Errorf("Cannot add subscriber %p: only one subscription is allowed per jobID/contract address. There is already a subscription with job ID %v listening on %s", sub, jobID, sub.opts.Contract.Hex()) } r.jobIDAddrs[jobID][sub.opts.Contract] = struct{}{} return nil @@ -165,16 +165,16 @@ func (r *registrations) removeSubscriber(sub *subscriber) (needsResubscribe bool func (r *registrations) checkRemoveSubscriber(sub *subscriber) error { jobID := sub.listener.JobID() if _, exists := r.registeredSubs[sub]; !exists { - return errors.Errorf("Cannot remove subscriber %p for job ID %v: not registered", sub, jobID) + return pkgerrors.Errorf("Cannot remove subscriber %p for job ID %v: not registered", sub, jobID) } delete(r.registeredSubs, sub) addrs, exists := r.jobIDAddrs[jobID] if !exists { - return errors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing job ID %v", sub, jobID) + return pkgerrors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing job ID %v", sub, jobID) } _, exists = addrs[sub.opts.Contract] if !exists { - return errors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing address %s", sub, sub.opts.Contract.Hex()) + return pkgerrors.Errorf("Cannot remove subscriber %p: jobIDAddrs was missing address %s", sub, sub.opts.Contract.Hex()) } delete(r.jobIDAddrs[jobID], sub.opts.Contract) if len(r.jobIDAddrs[jobID]) == 0 { diff --git a/core/chains/evm/logpoller/disabled.go b/core/chains/evm/logpoller/disabled.go index 05d591042f4..8d92b8d29f6 100644 --- a/core/chains/evm/logpoller/disabled.go +++ b/core/chains/evm/logpoller/disabled.go @@ -5,13 +5,13 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/services/pg" ) var ( - ErrDisabled = errors.New("log poller disabled") + ErrDisabled = pkgerrors.New("log poller disabled") LogPollerDisabled LogPoller = disabled{} ) diff --git a/core/chains/evm/logpoller/helper_test.go b/core/chains/evm/logpoller/helper_test.go index 9e48690a249..01c73a184eb 100644 --- a/core/chains/evm/logpoller/helper_test.go +++ b/core/chains/evm/logpoller/helper_test.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/ethdb" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -98,7 +98,7 @@ func (th *TestHarness) PollAndSaveLogs(ctx context.Context, currentBlockNumber i func (th *TestHarness) assertDontHave(t *testing.T, start, end int) { for i := start; i < end; i++ { _, err := th.ORM.SelectBlockByNumber(int64(i)) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) } } diff --git a/core/chains/evm/logpoller/log_poller.go b/core/chains/evm/logpoller/log_poller.go index 7006c1762ef..a65f6860a66 100644 --- a/core/chains/evm/logpoller/log_poller.go +++ b/core/chains/evm/logpoller/log_poller.go @@ -17,7 +17,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "golang.org/x/exp/maps" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -89,9 +89,9 @@ type Client interface { var ( _ LogPollerTest = &logPoller{} - ErrReplayRequestAborted = errors.New("aborted, replay request cancelled") - ErrReplayInProgress = errors.New("replay request cancelled, but replay is already in progress") - ErrLogPollerShutdown = errors.New("replay aborted due to log poller shutdown") + ErrReplayRequestAborted = pkgerrors.New("aborted, replay request cancelled") + ErrReplayInProgress = pkgerrors.New("replay request cancelled, but replay is already in progress") + ErrLogPollerShutdown = pkgerrors.New("replay aborted due to log poller shutdown") ) type logPoller struct { @@ -220,20 +220,20 @@ func (filter *Filter) Contains(other *Filter) bool { // Warnings/debug information is keyed by filter name. func (lp *logPoller) RegisterFilter(filter Filter, qopts ...pg.QOpt) error { if len(filter.Addresses) == 0 { - return errors.Errorf("at least one address must be specified") + return pkgerrors.Errorf("at least one address must be specified") } if len(filter.EventSigs) == 0 { - return errors.Errorf("at least one event must be specified") + return pkgerrors.Errorf("at least one event must be specified") } for _, eventSig := range filter.EventSigs { if eventSig == [common.HashLength]byte{} { - return errors.Errorf("empty event sig") + return pkgerrors.Errorf("empty event sig") } } for _, addr := range filter.Addresses { if addr == [common.AddressLength]byte{} { - return errors.Errorf("empty address") + return pkgerrors.Errorf("empty address") } } @@ -250,7 +250,7 @@ func (lp *logPoller) RegisterFilter(filter Filter, qopts ...pg.QOpt) error { } if err := lp.orm.InsertFilter(filter, qopts...); err != nil { - return errors.Wrap(err, "error inserting filter") + return pkgerrors.Wrap(err, "error inserting filter") } lp.filters[filter.Name] = filter lp.filterDirty = true @@ -271,7 +271,7 @@ func (lp *logPoller) UnregisterFilter(name string, qopts ...pg.QOpt) error { } if err := lp.orm.DeleteFilter(name, qopts...); err != nil { - return errors.Wrap(err, "error deleting filter") + return pkgerrors.Wrap(err, "error deleting filter") } delete(lp.filters, name) lp.filterDirty = true @@ -346,13 +346,13 @@ func (lp *logPoller) Replay(ctx context.Context, fromBlock int64) error { return err } if fromBlock < 1 || fromBlock > latest.Number { - return errors.Errorf("Invalid replay block number %v, acceptable range [1, %v]", fromBlock, latest.Number) + return pkgerrors.Errorf("Invalid replay block number %v, acceptable range [1, %v]", fromBlock, latest.Number) } // Block until replay notification accepted or cancelled. select { case lp.replayStart <- fromBlock: case <-ctx.Done(): - return errors.Wrap(ErrReplayRequestAborted, ctx.Err().Error()) + return pkgerrors.Wrap(ErrReplayRequestAborted, ctx.Err().Error()) } // Block until replay complete or cancelled. select { @@ -416,7 +416,7 @@ func (lp *logPoller) HealthReport() map[string]error { func (lp *logPoller) GetReplayFromBlock(ctx context.Context, requested int64) (int64, error) { lastProcessed, err := lp.orm.SelectLatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { // Real DB error return 0, err } @@ -444,7 +444,7 @@ func (lp *logPoller) run() { filters, err := lp.orm.LoadFilters(pg.WithParentCtx(lp.ctx)) if err != nil { - return errors.Wrapf(err, "Failed to load initial filters from db, retrying") + return pkgerrors.Wrapf(err, "Failed to load initial filters from db, retrying") } lp.filters = filters @@ -498,7 +498,7 @@ func (lp *logPoller) run() { var start int64 lastProcessed, err := lp.orm.SelectLatestBlock(pg.WithParentCtx(lp.ctx)) if err != nil { - if !errors.Is(err, sql.ErrNoRows) { + if !pkgerrors.Is(err, sql.ErrNoRows) { // Assume transient db reading issue, retry forever. lp.lggr.Errorw("unable to get starting block", "err", err) continue @@ -558,7 +558,7 @@ func (lp *logPoller) BackupPollAndSaveLogs(ctx context.Context, backupPollerBloc if lp.backupPollerNextBlock == 0 { lastProcessed, err := lp.orm.SelectLatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { lp.lggr.Warnw("Backup log poller ran before first successful log poller run, skipping") } else { lp.lggr.Errorw("Backup log poller unable to get starting block", "err", err) @@ -659,7 +659,7 @@ func (lp *logPoller) backfill(ctx context.Context, start, end int64) error { gethLogs, err := lp.ec.FilterLogs(ctx, lp.Filter(big.NewInt(from), big.NewInt(to), nil)) if err != nil { var rpcErr client.JsonError - if errors.As(err, &rpcErr) { + if pkgerrors.As(err, &rpcErr) { if rpcErr.Code != jsonRpcLimitExceeded { lp.lggr.Errorw("Unable to query for logs", "err", err, "from", from, "to", to) return err @@ -712,20 +712,20 @@ func (lp *logPoller) getCurrentBlockMaybeHandleReorg(ctx context.Context, curren // Additional sanity checks, don't necessarily trust the RPC. if currentBlock == nil { lp.lggr.Errorf("Unexpected nil block from RPC", "currentBlockNumber", currentBlockNumber) - return nil, errors.Errorf("Got nil block for %d", currentBlockNumber) + return nil, pkgerrors.Errorf("Got nil block for %d", currentBlockNumber) } if currentBlock.Number != currentBlockNumber { lp.lggr.Warnw("Unable to get currentBlock, rpc returned incorrect block", "currentBlockNumber", currentBlockNumber, "got", currentBlock.Number) - return nil, errors.Errorf("Block mismatch have %d want %d", currentBlock.Number, currentBlockNumber) + return nil, pkgerrors.Errorf("Block mismatch have %d want %d", currentBlock.Number, currentBlockNumber) } } // Does this currentBlock point to the same parent that we have saved? // If not, there was a reorg, so we need to rewind. expectedParent, err1 := lp.orm.SelectBlockByNumber(currentBlockNumber-1, pg.WithParentCtx(ctx)) - if err1 != nil && !errors.Is(err1, sql.ErrNoRows) { + if err1 != nil && !pkgerrors.Is(err1, sql.ErrNoRows) { // If err is not a 'no rows' error, assume transient db issue and retry lp.lggr.Warnw("Unable to read latestBlockNumber currentBlock saved", "err", err1, "currentBlockNumber", currentBlockNumber) - return nil, errors.New("Unable to read latestBlockNumber currentBlock saved") + return nil, pkgerrors.New("Unable to read latestBlockNumber currentBlock saved") } // We will not have the previous currentBlock on initial poll. havePreviousBlock := err1 == nil @@ -741,7 +741,7 @@ func (lp *logPoller) getCurrentBlockMaybeHandleReorg(ctx context.Context, curren blockAfterLCA, err2 := lp.findBlockAfterLCA(ctx, currentBlock, expectedParent.FinalizedBlockNumber) if err2 != nil { lp.lggr.Warnw("Unable to find LCA after reorg, retrying", "err", err2) - return nil, errors.New("Unable to find LCA after reorg, retrying") + return nil, pkgerrors.New("Unable to find LCA after reorg, retrying") } lp.lggr.Infow("Reorg detected", "blockAfterLCA", blockAfterLCA.Number, "currentBlockNumber", currentBlockNumber) @@ -922,7 +922,7 @@ func (lp *logPoller) findBlockAfterLCA(ctx context.Context, current *evmtypes.He } } lp.lggr.Criticalw("Reorg greater than finality depth detected", "finalityTag", lp.useFinalityTag, "current", current.Number, "latestFinalized", latestFinalizedBlockNumber) - rerr := errors.New("Reorg greater than finality depth") + rerr := pkgerrors.New("Reorg greater than finality depth") lp.SvcErrBuffer.Append(rerr) return nil, rerr } @@ -1092,7 +1092,7 @@ func (lp *logPoller) GetBlocksRange(ctx context.Context, numbers []uint64, qopts } if len(blocksNotFound) > 0 { - return nil, errors.Errorf("blocks were not found in db or RPC call: %v", blocksNotFound) + return nil, pkgerrors.Errorf("blocks were not found in db or RPC call: %v", blocksNotFound) } return blocks, nil @@ -1164,16 +1164,16 @@ func (lp *logPoller) batchFetchBlocks(ctx context.Context, blocksRequested []str block, is := r.Result.(*evmtypes.Head) if !is { - return nil, errors.Errorf("expected result to be a %T, got %T", &evmtypes.Head{}, r.Result) + return nil, pkgerrors.Errorf("expected result to be a %T, got %T", &evmtypes.Head{}, r.Result) } if block == nil { - return nil, errors.New("invariant violation: got nil block") + return nil, pkgerrors.New("invariant violation: got nil block") } if block.Hash == (common.Hash{}) { - return nil, errors.Errorf("missing block hash for block number: %d", block.Number) + return nil, pkgerrors.Errorf("missing block hash for block number: %d", block.Number) } if block.Number < 0 { - return nil, errors.Errorf("expected block number to be >= to 0, got %d", block.Number) + return nil, pkgerrors.Errorf("expected block number to be >= to 0, got %d", block.Number) } blocks = append(blocks, block) } diff --git a/core/chains/evm/logpoller/log_poller_internal_test.go b/core/chains/evm/logpoller/log_poller_internal_test.go index 863ab0fddea..633dca0461e 100644 --- a/core/chains/evm/logpoller/log_poller_internal_test.go +++ b/core/chains/evm/logpoller/log_poller_internal_test.go @@ -14,7 +14,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -286,7 +286,7 @@ func TestLogPoller_Replay(t *testing.T) { // Replay() should return error code received from replayComplete t.Run("returns error code on replay complete", func(t *testing.T) { ctx := testutils.Context(t) - anyErr := errors.New("any error") + anyErr := pkgerrors.New("any error") done := make(chan struct{}) go func() { defer close(done) @@ -412,7 +412,7 @@ func TestLogPoller_Replay(t *testing.T) { t.Cleanup(lp.reset) servicetest.Run(t, lp) - anyErr := errors.New("async error") + anyErr := pkgerrors.New("async error") observedLogs.TakeAll() lp.ReplayAsync(4) diff --git a/core/chains/evm/logpoller/orm.go b/core/chains/evm/logpoller/orm.go index 663c56d10ed..391a6ab7d12 100644 --- a/core/chains/evm/logpoller/orm.go +++ b/core/chains/evm/logpoller/orm.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" ubig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" @@ -292,7 +292,7 @@ func (o *DbORM) insertLogsWithinTx(logs []Log, tx pg.Queryer) error { ) if err != nil { - if errors.Is(err, context.DeadlineExceeded) && batchInsertSize > 500 { + if pkgerrors.Is(err, context.DeadlineExceeded) && batchInsertSize > 500 { // In case of DB timeouts, try to insert again with a smaller batch upto a limit batchInsertSize /= 2 i -= batchInsertSize // counteract +=batchInsertSize on next loop iteration @@ -307,7 +307,7 @@ func (o *DbORM) insertLogsWithinTx(logs []Log, tx pg.Queryer) error { func (o *DbORM) validateLogs(logs []Log) error { for _, log := range logs { if o.chainID.Cmp(log.EvmChainId.ToInt()) != 0 { - return errors.Errorf("invalid chainID in log got %v want %v", log.EvmChainId.ToInt(), o.chainID) + return pkgerrors.Errorf("invalid chainID in log got %v want %v", log.EvmChainId.ToInt(), o.chainID) } } return nil @@ -406,7 +406,7 @@ func (o *DbORM) SelectLogsWithSigs(start, end int64, address common.Address, eve AND event_sig = ANY(:event_sig_array) AND block_number BETWEEN :start_block AND :end_block ORDER BY (block_number, log_index)`, args) - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return nil, nil } return logs, err @@ -457,7 +457,7 @@ func (o *DbORM) SelectLatestLogEventSigsAddrsWithConfs(fromBlock int64, addresse ORDER BY block_number ASC`, nestedBlockNumberQuery(confs)) var logs []Log if err := o.q.WithOpts(qopts...).SelectNamed(&logs, query, args); err != nil { - return nil, errors.Wrap(err, "failed to execute query") + return nil, pkgerrors.Wrap(err, "failed to execute query") } return logs, nil } diff --git a/core/chains/evm/logpoller/orm_test.go b/core/chains/evm/logpoller/orm_test.go index 0af62ebd547..d0474b8fc91 100644 --- a/core/chains/evm/logpoller/orm_test.go +++ b/core/chains/evm/logpoller/orm_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -203,17 +203,17 @@ func TestORM(t *testing.T) { require.NoError(t, o1.DeleteLogsAndBlocksAfter(10)) _, err = o1.SelectBlockByHash(common.HexToHash("0x1234")) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Delete blocks from another chain. require.NoError(t, o2.DeleteLogsAndBlocksAfter(11)) _, err = o2.SelectBlockByHash(common.HexToHash("0x1234")) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Delete blocks after should also delete block 12. _, err = o2.SelectBlockByHash(common.HexToHash("0x1235")) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Should be able to insert and read back a log. topic := common.HexToHash("0x1599") @@ -329,7 +329,7 @@ func TestORM(t *testing.T) { // With no blocks, should be an error _, err = o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 0) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // With block 10, only 0 confs should work require.NoError(t, o1.InsertBlock(common.HexToHash("0x1234"), 10, time.Now(), 0)) log, err := o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 0) @@ -337,7 +337,7 @@ func TestORM(t *testing.T) { assert.Equal(t, int64(10), log.BlockNumber) _, err = o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 1) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // With block 12, anything <=2 should work require.NoError(t, o1.InsertBlock(common.HexToHash("0x1234"), 11, time.Now(), 0)) require.NoError(t, o1.InsertBlock(common.HexToHash("0x1235"), 12, time.Now(), 0)) @@ -349,7 +349,7 @@ func TestORM(t *testing.T) { require.NoError(t, err) _, err = o1.SelectLatestLogByEventSigWithConfs(topic, common.HexToAddress("0x1234"), 3) require.Error(t, err) - assert.True(t, errors.Is(err, sql.ErrNoRows)) + assert.True(t, pkgerrors.Is(err, sql.ErrNoRows)) // Required for confirmations to work require.NoError(t, o1.InsertBlock(common.HexToHash("0x1234"), 13, time.Now(), 0)) diff --git a/core/chains/evm/monitor/balance.go b/core/chains/evm/monitor/balance.go index b0f0fbc9c91..5755773acb7 100644 --- a/core/chains/evm/monitor/balance.go +++ b/core/chains/evm/monitor/balance.go @@ -9,7 +9,7 @@ import ( "time" gethCommon "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -231,7 +231,7 @@ func ApproximateFloat64(e *assets.Eth) (float64, error) { bf := new(big.Float).Quo(ef, weif) f64, _ := bf.Float64() if f64 == math.Inf(1) || f64 == math.Inf(-1) { - return math.Inf(1), errors.New("assets.Eth.Float64: Could not approximate Eth value into float") + return math.Inf(1), pkgerrors.New("assets.Eth.Float64: Could not approximate Eth value into float") } return f64, nil } diff --git a/core/chains/evm/monitor/balance_test.go b/core/chains/evm/monitor/balance_test.go index 246d5d0759f..85e0ec669bf 100644 --- a/core/chains/evm/monitor/balance_test.go +++ b/core/chains/evm/monitor/balance_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/onsi/gomega" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -123,7 +123,7 @@ func TestBalanceMonitor_Start(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt). Once(). - Return(nil, errors.New("a little easter egg for the 4chan link marines error")) + Return(nil, pkgerrors.New("a little easter egg for the 4chan link marines error")) servicetest.RunHealthy(t, bm) diff --git a/core/chains/evm/txmgr/attempts.go b/core/chains/evm/txmgr/attempts.go index 91645bae6f6..fbf5c73e9f2 100644 --- a/core/chains/evm/txmgr/attempts.go +++ b/core/chains/evm/txmgr/attempts.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" feetypes "github.com/smartcontractkit/chainlink/v2/common/fee/types" @@ -59,7 +59,7 @@ func (c *evmTxAttemptBuilder) NewTxAttemptWithType(ctx context.Context, etx Tx, keySpecificMaxGasPriceWei := c.feeConfig.PriceMaxKey(etx.FromAddress) fee, feeLimit, err = c.EvmFeeEstimator.GetFee(ctx, etx.EncodedPayload, etx.FeeLimit, keySpecificMaxGasPriceWei, opts...) if err != nil { - return attempt, fee, feeLimit, true, errors.Wrap(err, "failed to get fee") // estimator errors are retryable + return attempt, fee, feeLimit, true, pkgerrors.Wrap(err, "failed to get fee") // estimator errors are retryable } attempt, retryable, err = c.NewCustomTxAttempt(etx, fee, feeLimit, txType, lggr) @@ -73,7 +73,7 @@ func (c *evmTxAttemptBuilder) NewBumpTxAttempt(ctx context.Context, etx Tx, prev bumpedFee, bumpedFeeLimit, err = c.EvmFeeEstimator.BumpFee(ctx, previousAttempt.TxFee, etx.FeeLimit, keySpecificMaxGasPriceWei, newEvmPriorAttempts(priorAttempts)) if err != nil { - return attempt, bumpedFee, bumpedFeeLimit, true, errors.Wrap(err, "failed to bump fee") // estimator errors are retryable + return attempt, bumpedFee, bumpedFeeLimit, true, pkgerrors.Wrap(err, "failed to bump fee") // estimator errors are retryable } attempt, retryable, err = c.NewCustomTxAttempt(etx, bumpedFee, bumpedFeeLimit, previousAttempt.TxType, lggr) @@ -86,7 +86,7 @@ func (c *evmTxAttemptBuilder) NewCustomTxAttempt(etx Tx, fee gas.EvmFee, gasLimi switch txType { case 0x0: // legacy if fee.Legacy == nil { - err = errors.Errorf("Attempt %v is a type 0 transaction but estimator did not return legacy fee bump", attempt.ID) + err = pkgerrors.Errorf("Attempt %v is a type 0 transaction but estimator did not return legacy fee bump", attempt.ID) logger.Sugared(lggr).AssumptionViolation(err.Error()) return attempt, false, err // not retryable } @@ -94,7 +94,7 @@ func (c *evmTxAttemptBuilder) NewCustomTxAttempt(etx Tx, fee gas.EvmFee, gasLimi return attempt, true, err case 0x2: // dynamic, EIP1559 if !fee.ValidDynamic() { - err = errors.Errorf("Attempt %v is a type 2 transaction but estimator did not return dynamic fee bump", attempt.ID) + err = pkgerrors.Errorf("Attempt %v is a type 2 transaction but estimator did not return dynamic fee bump", attempt.ID) logger.Sugared(lggr).AssumptionViolation(err.Error()) return attempt, false, err // not retryable } @@ -104,7 +104,7 @@ func (c *evmTxAttemptBuilder) NewCustomTxAttempt(etx Tx, fee gas.EvmFee, gasLimi }, gasLimit) return attempt, true, err default: - err = errors.Errorf("invariant violation: Attempt %v had unrecognised transaction type %v"+ + err = pkgerrors.Errorf("invariant violation: Attempt %v had unrecognised transaction type %v"+ "This is a bug! Please report to https://github.com/smartcontractkit/chainlink/issues", attempt.ID, attempt.TxType) logger.Sugared(lggr).AssumptionViolation(err.Error()) return attempt, false, err // not retryable @@ -117,7 +117,7 @@ func (c *evmTxAttemptBuilder) NewEmptyTxAttempt(nonce evmtypes.Nonce, feeLimit u payload := []byte{} if fee.Legacy == nil { - return attempt, errors.New("NewEmptyTranscation: legacy fee cannot be nil") + return attempt, pkgerrors.New("NewEmptyTranscation: legacy fee cannot be nil") } tx := newLegacyTransaction( @@ -132,7 +132,7 @@ func (c *evmTxAttemptBuilder) NewEmptyTxAttempt(nonce evmtypes.Nonce, feeLimit u transaction := types.NewTx(&tx) hash, signedTxBytes, err := c.SignTx(fromAddress, transaction) if err != nil { - return attempt, errors.Wrapf(err, "error using account %s to sign empty transaction", fromAddress.String()) + return attempt, pkgerrors.Wrapf(err, "error using account %s to sign empty transaction", fromAddress.String()) } attempt.SignedRawTx = signedTxBytes @@ -143,7 +143,7 @@ func (c *evmTxAttemptBuilder) NewEmptyTxAttempt(nonce evmtypes.Nonce, feeLimit u func (c *evmTxAttemptBuilder) newDynamicFeeAttempt(etx Tx, fee gas.DynamicFee, gasLimit uint32) (attempt TxAttempt, err error) { if err = validateDynamicFeeGas(c.feeConfig, c.feeConfig.TipCapMin(), fee, gasLimit, etx); err != nil { - return attempt, errors.Wrap(err, "error validating gas") + return attempt, pkgerrors.Wrap(err, "error validating gas") } d := newDynamicFeeTransaction( @@ -190,25 +190,25 @@ func validateDynamicFeeGas(kse keySpecificEstimator, tipCapMinimum *assets.Wei, // Assertions from: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md // Prevent impossibly large numbers if gasFeeCap.ToInt().Cmp(Max256BitUInt) > 0 { - return errors.New("impossibly large fee cap") + return pkgerrors.New("impossibly large fee cap") } if gasTipCap.ToInt().Cmp(Max256BitUInt) > 0 { - return errors.New("impossibly large tip cap") + return pkgerrors.New("impossibly large tip cap") } // The total must be at least as large as the tip if gasFeeCap.Cmp(gasTipCap) < 0 { - return errors.Errorf("gas fee cap must be greater than or equal to gas tip cap (fee cap: %s, tip cap: %s)", gasFeeCap.String(), gasTipCap.String()) + return pkgerrors.Errorf("gas fee cap must be greater than or equal to gas tip cap (fee cap: %s, tip cap: %s)", gasFeeCap.String(), gasTipCap.String()) } // Configuration sanity-check max := kse.PriceMaxKey(etx.FromAddress) if gasFeeCap.Cmp(max) > 0 { - return errors.Errorf("cannot create tx attempt: specified gas fee cap of %s would exceed max configured gas price of %s for key %s", gasFeeCap.String(), max.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas fee cap of %s would exceed max configured gas price of %s for key %s", gasFeeCap.String(), max.String(), etx.FromAddress.String()) } // Tip must be above minimum minTip := tipCapMinimum if gasTipCap.Cmp(minTip) < 0 { - return errors.Errorf("cannot create tx attempt: specified gas tip cap of %s is below min configured gas tip of %s for key %s", gasTipCap.String(), minTip.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas tip cap of %s is below min configured gas tip of %s for key %s", gasTipCap.String(), minTip.String(), etx.FromAddress.String()) } return nil } @@ -228,7 +228,7 @@ func newDynamicFeeTransaction(nonce uint64, to common.Address, value *big.Int, g func (c *evmTxAttemptBuilder) newLegacyAttempt(etx Tx, gasPrice *assets.Wei, gasLimit uint32) (attempt TxAttempt, err error) { if err = validateLegacyGas(c.feeConfig, c.feeConfig.PriceMin(), gasPrice, gasLimit, etx); err != nil { - return attempt, errors.Wrap(err, "error validating gas") + return attempt, pkgerrors.Wrap(err, "error validating gas") } tx := newLegacyTransaction( @@ -243,7 +243,7 @@ func (c *evmTxAttemptBuilder) newLegacyAttempt(etx Tx, gasPrice *assets.Wei, gas transaction := types.NewTx(&tx) hash, signedTxBytes, err := c.SignTx(etx.FromAddress, transaction) if err != nil { - return attempt, errors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress, etx.ID) + return attempt, pkgerrors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress, etx.ID) } attempt.State = txmgrtypes.TxAttemptInProgress @@ -266,11 +266,11 @@ func validateLegacyGas(kse keySpecificEstimator, minGasPriceWei, gasPrice *asset } max := kse.PriceMaxKey(etx.FromAddress) if gasPrice.Cmp(max) > 0 { - return errors.Errorf("cannot create tx attempt: specified gas price of %s would exceed max configured gas price of %s for key %s", gasPrice.String(), max.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas price of %s would exceed max configured gas price of %s for key %s", gasPrice.String(), max.String(), etx.FromAddress.String()) } min := minGasPriceWei if gasPrice.Cmp(min) < 0 { - return errors.Errorf("cannot create tx attempt: specified gas price of %s is below min configured gas price of %s for key %s", gasPrice.String(), min.String(), etx.FromAddress.String()) + return pkgerrors.Errorf("cannot create tx attempt: specified gas price of %s is below min configured gas price of %s for key %s", gasPrice.String(), min.String(), etx.FromAddress.String()) } return nil } @@ -278,7 +278,7 @@ func validateLegacyGas(kse keySpecificEstimator, minGasPriceWei, gasPrice *asset func (c *evmTxAttemptBuilder) newSignedAttempt(etx Tx, tx *types.Transaction) (attempt TxAttempt, err error) { hash, signedTxBytes, err := c.SignTx(etx.FromAddress, tx) if err != nil { - return attempt, errors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress.String(), etx.ID) + return attempt, pkgerrors.Wrapf(err, "error using account %s to sign transaction %v", etx.FromAddress.String(), etx.ID) } attempt.State = txmgrtypes.TxAttemptInProgress @@ -308,7 +308,7 @@ func (c *evmTxAttemptBuilder) SignTx(address common.Address, tx *types.Transacti } rlp := new(bytes.Buffer) if err := signedTx.EncodeRLP(rlp); err != nil { - return common.Hash{}, nil, errors.Wrap(err, "SignTx failed") + return common.Hash{}, nil, pkgerrors.Wrap(err, "SignTx failed") } txHash := signedTx.Hash() return txHash, rlp.Bytes(), nil diff --git a/core/chains/evm/txmgr/attempts_test.go b/core/chains/evm/txmgr/attempts_test.go index c7373e2c4f6..15ad17f8fe6 100644 --- a/core/chains/evm/txmgr/attempts_test.go +++ b/core/chains/evm/txmgr/attempts_test.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" gethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -257,8 +257,8 @@ func TestTxm_NewCustomTxAttempt_NonRetryableErrors(t *testing.T) { func TestTxm_EvmTxAttemptBuilder_RetryableEstimatorError(t *testing.T) { est := gasmocks.NewEvmFeeEstimator(t) - est.On("GetFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), errors.New("fail")) - est.On("BumpFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), errors.New("fail")) + est.On("GetFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), pkgerrors.New("fail")) + est.On("BumpFee", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(gas.EvmFee{}, uint32(0), pkgerrors.New("fail")) kst := ksmocks.NewEth(t) lggr := logger.Test(t) diff --git a/core/chains/evm/txmgr/common.go b/core/chains/evm/txmgr/common.go index d1e851f0c21..75fd3628ed5 100644 --- a/core/chains/evm/txmgr/common.go +++ b/core/chains/evm/txmgr/common.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" @@ -74,7 +74,7 @@ func batchSendTransactions( logger.Debugw(fmt.Sprintf("Batch sending transactions %v thru %v", i, j)) if err := ethClient.BatchCallContextAll(ctx, reqs[i:j]); err != nil { - return reqs, now, successfulBroadcast, errors.Wrap(err, "failed to batch send transactions") + return reqs, now, successfulBroadcast, pkgerrors.Wrap(err, "failed to batch send transactions") } successfulBroadcast = append(successfulBroadcast, ethTxIDs[i:j]...) } From 78657153b5dd9c6361afaca0def258822d1bd066 Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 22 Jan 2024 17:10:11 -0500 Subject: [PATCH 02/11] rename pkgerrors in evm codebase --- core/chains/evm/txmgr/nonce_syncer.go | 8 +++--- core/chains/evm/txmgr/nonce_syncer_test.go | 4 +-- core/chains/evm/txmgr/resender_test.go | 4 +-- core/chains/evm/txmgr/transmitchecker.go | 26 +++++++++---------- core/chains/evm/txmgr/transmitchecker_test.go | 14 +++++----- .../evm/types/internal/blocks/transactions.go | 4 +-- core/chains/evm/types/models.go | 14 +++++----- core/chains/evm/types/models_test.go | 6 ++--- core/chains/evm/types/types.go | 20 +++++++------- core/chains/evm/utils/ethabi.go | 4 +-- core/chains/evm/utils/ethabi_test.go | 4 +-- core/services/relay/evm/address.go | 8 +++--- core/services/relay/evm/config_poller.go | 8 +++--- core/services/relay/evm/config_poller_test.go | 6 ++--- .../relay/evm/contract_transmitter.go | 14 +++++----- core/services/relay/evm/functions.go | 18 ++++++------- .../relay/evm/functions/config_poller.go | 14 +++++----- .../evm/functions/contract_transmitter.go | 22 ++++++++-------- .../relay/evm/functions/logpoller_wrapper.go | 8 +++--- core/services/relay/evm/median.go | 10 +++---- .../relay/evm/mercury/config_poller.go | 6 ++--- .../relay/evm/mercury/config_poller_test.go | 4 +-- .../evm/mercury/offchain_config_digester.go | 8 +++--- .../relay/evm/mercury/transmitter_test.go | 10 +++---- .../relay/evm/mercury/v1/data_source_test.go | 8 +++--- .../relay/evm/mercury/v2/data_source_test.go | 14 +++++----- .../relay/evm/mercury/v3/data_source_test.go | 14 +++++----- .../relay/evm/mercury/wsrpc/client.go | 16 ++++++------ core/services/relay/evm/ocr2keeper.go | 6 ++--- core/services/relay/evm/ocr2vrf.go | 4 +-- core/services/relay/evm/relayer_extender.go | 6 ++--- core/services/relay/evm/request_round_db.go | 14 +++++----- .../relay/evm/request_round_tracker.go | 4 +-- .../relay/evm/request_round_tracker_test.go | 4 +-- 34 files changed, 167 insertions(+), 167 deletions(-) diff --git a/core/chains/evm/txmgr/nonce_syncer.go b/core/chains/evm/txmgr/nonce_syncer.go index 2936736b3b3..0cb52a1321e 100644 --- a/core/chains/evm/txmgr/nonce_syncer.go +++ b/core/chains/evm/txmgr/nonce_syncer.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/common/txmgr" @@ -76,13 +76,13 @@ func NewNonceSyncer( // Calling it later is not safe and could lead to races. func (s nonceSyncerImpl) Sync(ctx context.Context, addr common.Address, localNonce types.Nonce) (nonce types.Nonce, err error) { nonce, err = s.fastForwardNonceIfNecessary(ctx, addr, localNonce) - return nonce, errors.Wrap(err, "NonceSyncer#fastForwardNoncesIfNecessary failed") + return nonce, pkgerrors.Wrap(err, "NonceSyncer#fastForwardNoncesIfNecessary failed") } func (s nonceSyncerImpl) fastForwardNonceIfNecessary(ctx context.Context, address common.Address, localNonce types.Nonce) (types.Nonce, error) { chainNonce, err := s.pendingNonceFromEthClient(ctx, address) if err != nil { - return localNonce, errors.Wrap(err, "GetNextNonce failed to loadInitialNonceFromEthClient") + return localNonce, pkgerrors.Wrap(err, "GetNextNonce failed to loadInitialNonceFromEthClient") } if chainNonce == 0 { return localNonce, nil @@ -102,5 +102,5 @@ func (s nonceSyncerImpl) fastForwardNonceIfNecessary(ctx context.Context, addres func (s nonceSyncerImpl) pendingNonceFromEthClient(ctx context.Context, account common.Address) (types.Nonce, error) { nextNonce, err := s.client.PendingSequenceAt(ctx, account) - return nextNonce, errors.WithStack(err) + return nextNonce, pkgerrors.WithStack(err) } diff --git a/core/chains/evm/txmgr/nonce_syncer_test.go b/core/chains/evm/txmgr/nonce_syncer_test.go index f757b8863d1..d9a741fb3c5 100644 --- a/core/chains/evm/txmgr/nonce_syncer_test.go +++ b/core/chains/evm/txmgr/nonce_syncer_test.go @@ -12,7 +12,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -32,7 +32,7 @@ func Test_NonceSyncer_Sync(t *testing.T) { ns := txmgr.NewNonceSyncer(txStore, logger.Test(t), ethClient) - ethClient.On("PendingNonceAt", mock.Anything, from).Return(uint64(0), errors.New("something exploded")) + ethClient.On("PendingNonceAt", mock.Anything, from).Return(uint64(0), pkgerrors.New("something exploded")) _, err := ns.Sync(testutils.Context(t), from, types.Nonce(0)) require.Error(t, err) assert.Contains(t, err.Error(), "something exploded") diff --git a/core/chains/evm/txmgr/resender_test.go b/core/chains/evm/txmgr/resender_test.go index fd3d1745010..b5c6add6d37 100644 --- a/core/chains/evm/txmgr/resender_test.go +++ b/core/chains/evm/txmgr/resender_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -176,7 +176,7 @@ func Test_EthResender_Start(t *testing.T) { })).Return(nil).Run(func(args mock.Arguments) { elems := args.Get(1).([]rpc.BatchElem) // It should update BroadcastAt even if there is an error here - elems[0].Error = errors.New("kaboom") + elems[0].Error = pkgerrors.New("kaboom") }) func() { diff --git a/core/chains/evm/txmgr/transmitchecker.go b/core/chains/evm/txmgr/transmitchecker.go index 5a5cc3dbcd4..8956f2ae626 100644 --- a/core/chains/evm/txmgr/transmitchecker.go +++ b/core/chains/evm/txmgr/transmitchecker.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" gethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/logger" bigmath "github.com/smartcontractkit/chainlink-common/pkg/utils/big_math" @@ -53,11 +53,11 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker return &SimulateChecker{c.Client}, nil case TransmitCheckerTypeVRFV1: if spec.VRFCoordinatorAddress == nil { - return nil, errors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) + return nil, pkgerrors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) } coord, err := v1.NewVRFCoordinator(*spec.VRFCoordinatorAddress, c.Client) if err != nil { - return nil, errors.Wrapf(err, + return nil, pkgerrors.Wrapf(err, "failed to create VRF V1 coordinator at address %v", spec.VRFCoordinatorAddress) } return &VRFV1Checker{ @@ -66,15 +66,15 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker }, nil case TransmitCheckerTypeVRFV2: if spec.VRFCoordinatorAddress == nil { - return nil, errors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) + return nil, pkgerrors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) } coord, err := v2.NewVRFCoordinatorV2(*spec.VRFCoordinatorAddress, c.Client) if err != nil { - return nil, errors.Wrapf(err, + return nil, pkgerrors.Wrapf(err, "failed to create VRF V2 coordinator at address %v", spec.VRFCoordinatorAddress) } if spec.VRFRequestBlockNumber == nil { - return nil, errors.New("VRFRequestBlockNumber parameter must be non-nil") + return nil, pkgerrors.New("VRFRequestBlockNumber parameter must be non-nil") } return &VRFV2Checker{ GetCommitment: coord.GetCommitment, @@ -83,15 +83,15 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker }, nil case TransmitCheckerTypeVRFV2Plus: if spec.VRFCoordinatorAddress == nil { - return nil, errors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) + return nil, pkgerrors.Errorf("malformed checker, expected non-nil VRFCoordinatorAddress, got: %v", spec) } coord, err := vrf_coordinator_v2plus_interface.NewIVRFCoordinatorV2PlusInternal(*spec.VRFCoordinatorAddress, c.Client) if err != nil { - return nil, errors.Wrapf(err, + return nil, pkgerrors.Wrapf(err, "failed to create VRF V2 coordinator plus at address %v", spec.VRFCoordinatorAddress) } if spec.VRFRequestBlockNumber == nil { - return nil, errors.New("VRFRequestBlockNumber parameter must be non-nil") + return nil, pkgerrors.New("VRFRequestBlockNumber parameter must be non-nil") } return &VRFV2Checker{ GetCommitment: coord.SRequestCommitments, @@ -101,7 +101,7 @@ func (c *CheckerFactory) BuildChecker(spec TransmitCheckerSpec) (TransmitChecker case "": return NoChecker, nil default: - return nil, errors.Errorf("unrecognized checker type: %s", spec.CheckerType) + return nil, pkgerrors.Errorf("unrecognized checker type: %s", spec.CheckerType) } } @@ -150,7 +150,7 @@ func (s *SimulateChecker) Check( if jErr := evmclient.ExtractRPCErrorOrNil(err); jErr != nil { l.Criticalw("Transaction reverted during simulation", "ethTxAttemptID", a.ID, "txHash", a.Hash, "err", err, "rpcErr", jErr.String(), "returnValue", b.String()) - return errors.Errorf("transaction reverted during simulation: %s", jErr.String()) + return pkgerrors.Errorf("transaction reverted during simulation: %s", jErr.String()) } l.Warnw("Transaction simulation failed, will attempt to send anyway", "ethTxAttemptID", a.ID, "txHash", a.Hash, "err", err, "returnValue", b.String()) @@ -259,7 +259,7 @@ func (v *VRFV1Checker) Check( "ethTxID", tx.ID, "meta", tx.Meta, "reqID", reqID) - return errors.New("request already fulfilled") + return pkgerrors.New("request already fulfilled") } // Request not fulfilled return nil @@ -350,7 +350,7 @@ func (v *VRFV2Checker) Check( "ethTxID", tx.ID, "meta", tx.Meta, "vrfRequestId", vrfRequestID) - return errors.New("request already fulfilled") + return pkgerrors.New("request already fulfilled") } l.Debugw("Request not yet fulfilled", "ethTxID", tx.ID, diff --git a/core/chains/evm/txmgr/transmitchecker_test.go b/core/chains/evm/txmgr/transmitchecker_test.go index d2f668da11b..2fce9cf7aac 100644 --- a/core/chains/evm/txmgr/transmitchecker_test.go +++ b/core/chains/evm/txmgr/transmitchecker_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rpc" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/mock" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -165,7 +165,7 @@ func TestTransmitCheckers(t *testing.T) { mock.AnythingOfType("*hexutil.Bytes"), "eth_call", mock.MatchedBy(func(callarg map[string]interface{}) bool { return fmt.Sprintf("%s", callarg["value"]) == "0x282" // 642 - }), "latest").Return(errors.New("error")).Once() + }), "latest").Return(pkgerrors.New("error")).Once() // Non-revert errors are logged but should not prevent transmission, and do not need // to be passed to the caller @@ -221,7 +221,7 @@ func TestTransmitCheckers(t *testing.T) { Callbacks: func(opts *bind.CallOpts, reqID [32]byte) (v1.Callbacks, error) { if opts.BlockNumber.Cmp(big.NewInt(6)) != 0 { // Ensure correct logic is applied to get callbacks. - return v1.Callbacks{}, errors.New("error getting callback") + return v1.Callbacks{}, pkgerrors.New("error getting callback") } if reqID == r1 { // Request 1 is already fulfilled @@ -230,7 +230,7 @@ func TestTransmitCheckers(t *testing.T) { }, nil } else if reqID == r2 { // Request 2 errors - return v1.Callbacks{}, errors.New("error getting commitment") + return v1.Callbacks{}, pkgerrors.New("error getting commitment") } return v1.Callbacks{ SeedAndBlockNum: [32]byte{1}, @@ -277,7 +277,7 @@ func TestTransmitCheckers(t *testing.T) { t.Run("failure fetching tx receipt and block head", func(t *testing.T) { tx, attempt := txRequest(t, r1, false) - mockBatch.Return(errors.New("could not fetch")) + mockBatch.Return(pkgerrors.New("could not fetch")) err := checker.Check(ctx, log, tx, attempt) require.NoError(t, err) }) @@ -324,7 +324,7 @@ func TestTransmitCheckers(t *testing.T) { return [32]byte{}, nil } else if requestID.String() == "2" { // Request 2 errors - return [32]byte{}, errors.New("error getting commitment") + return [32]byte{}, pkgerrors.New("error getting commitment") } // All other requests are unfulfilled return [32]byte{1}, nil @@ -355,7 +355,7 @@ func TestTransmitCheckers(t *testing.T) { t.Run("can't get header", func(t *testing.T) { checker.HeadByNumber = func(ctx context.Context, n *big.Int) (*evmtypes.Head, error) { - return nil, errors.New("can't get head") + return nil, pkgerrors.New("can't get head") } tx, attempt := txRequest(t, big.NewInt(3)) require.NoError(t, checker.Check(ctx, log, tx, attempt)) diff --git a/core/chains/evm/types/internal/blocks/transactions.go b/core/chains/evm/types/internal/blocks/transactions.go index b607e2dcfd1..887a16f99d1 100644 --- a/core/chains/evm/types/internal/blocks/transactions.go +++ b/core/chains/evm/types/internal/blocks/transactions.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) type TxType uint8 @@ -22,7 +22,7 @@ func (txt *TxType) UnmarshalJSON(data []byte) error { return err } if hx > math.MaxUint8 { - return errors.Errorf("expected 'type' to fit into a single byte, got: '%s'", data) + return pkgerrors.Errorf("expected 'type' to fit into a single byte, got: '%s'", data) } *txt = TxType(hx) return nil diff --git a/core/chains/evm/types/models.go b/core/chains/evm/types/models.go index 44e150b6541..923dc830440 100644 --- a/core/chains/evm/types/models.go +++ b/core/chains/evm/types/models.go @@ -13,7 +13,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/ugorji/go/codec" "github.com/smartcontractkit/chainlink-common/pkg/utils/hex" @@ -360,7 +360,7 @@ func (b Block) MarshalJSON() ([]byte, error) { return buf.Bytes(), nil } -var ErrMissingBlock = errors.New("missing block") +var ErrMissingBlock = pkgerrors.New("missing block") // UnmarshalJSON unmarshals to a Block func (b *Block) UnmarshalJSON(data []byte) error { @@ -375,12 +375,12 @@ func (b *Block) UnmarshalJSON(data []byte) error { return err } if bi.Empty() { - return errors.WithStack(ErrMissingBlock) + return pkgerrors.WithStack(ErrMissingBlock) } n, err := hexutil.DecodeBig(bi.Number) if err != nil { - return errors.Wrapf(err, "failed to decode block number while unmarshalling block, got: '%s' in '%s'", bi.Number, data) + return pkgerrors.Wrapf(err, "failed to decode block number while unmarshalling block, got: '%s' in '%s'", bi.Number, data) } *b = Block{ Number: n.Int64(), @@ -426,7 +426,7 @@ func (t *Transaction) UnmarshalJSON(data []byte) error { } if ti.Gas == nil { - return errors.Errorf("expected 'gas' to not be null, got: '%s'", data) + return pkgerrors.Errorf("expected 'gas' to not be null, got: '%s'", data) } if ti.Type == nil { tpe := LegacyTxType @@ -507,7 +507,7 @@ func unmarshalFromString(s string, f *FunctionSelector) error { } bytes := common.FromHex(s) if len(bytes) != FunctionSelectorLength { - return errors.New("function ID must be 4 bytes in length") + return pkgerrors.New("function ID must be 4 bytes in length") } f.SetBytes(bytes) } else { @@ -564,7 +564,7 @@ type UntrustedBytes []byte func (ary UntrustedBytes) SafeByteSlice(start int, end int) ([]byte, error) { if end > len(ary) || start > end || start < 0 || end < 0 { var empty []byte - return empty, errors.New("out of bounds slice access") + return empty, pkgerrors.New("out of bounds slice access") } return ary[start:end], nil } diff --git a/core/chains/evm/types/models_test.go b/core/chains/evm/types/models_test.go index a32deba697d..7663090d070 100644 --- a/core/chains/evm/types/models_test.go +++ b/core/chains/evm/types/models_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -676,8 +676,8 @@ func TestBlock_UnmarshalJSON(t *testing.T) { b := new(evmtypes.Block) err := b.UnmarshalJSON([]byte("null")) assert.Error(t, err) - assert.Equal(t, errors.Cause(err), evmtypes.ErrMissingBlock) - assert.True(t, errors.Is(err, evmtypes.ErrMissingBlock)) + assert.Equal(t, pkgerrors.Cause(err), evmtypes.ErrMissingBlock) + assert.True(t, pkgerrors.Is(err, evmtypes.ErrMissingBlock)) }) } diff --git a/core/chains/evm/types/types.go b/core/chains/evm/types/types.go index 987fd987d3f..65e604be36a 100644 --- a/core/chains/evm/types/types.go +++ b/core/chains/evm/types/types.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" gethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/jackc/pgtype" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink-common/pkg/types" @@ -143,7 +143,7 @@ func (r *Receipt) UnmarshalJSON(input []byte) error { } var dec Receipt if err := json.Unmarshal(input, &dec); err != nil { - return errors.Wrap(err, "could not unmarshal receipt") + return pkgerrors.Wrap(err, "could not unmarshal receipt") } if dec.PostState != nil { r.PostState = *dec.PostState @@ -182,7 +182,7 @@ func (r *Receipt) UnmarshalJSON(input []byte) error { func (r *Receipt) Scan(value interface{}) error { b, ok := value.([]byte) if !ok { - return errors.New("type assertion to []byte failed") + return pkgerrors.New("type assertion to []byte failed") } return json.Unmarshal(b, r) @@ -294,7 +294,7 @@ func (l *Log) UnmarshalJSON(input []byte) error { } var dec Log if err := json.Unmarshal(input, &dec); err != nil { - return errors.Wrap(err, "could not unmarshal log") + return pkgerrors.Wrap(err, "could not unmarshal log") } if dec.Address != nil { l.Address = *dec.Address @@ -330,16 +330,16 @@ func (a *AddressArray) Scan(src interface{}) error { baArray := pgtype.ByteaArray{} err := baArray.Scan(src) if err != nil { - return errors.Wrap(err, "Expected BYTEA[] column for AddressArray") + return pkgerrors.Wrap(err, "Expected BYTEA[] column for AddressArray") } if baArray.Status != pgtype.Present || len(baArray.Dimensions) > 1 { - return errors.Errorf("Expected AddressArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) + return pkgerrors.Errorf("Expected AddressArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) } for i, ba := range baArray.Elements { addr := common.Address{} if ba.Status != pgtype.Present { - return errors.Errorf("Expected all addresses in AddressArray to be non-NULL. Got AddressArray[%d] = NULL", i) + return pkgerrors.Errorf("Expected all addresses in AddressArray to be non-NULL. Got AddressArray[%d] = NULL", i) } err = addr.Scan(ba.Bytes) if err != nil { @@ -357,16 +357,16 @@ func (h *HashArray) Scan(src interface{}) error { baArray := pgtype.ByteaArray{} err := baArray.Scan(src) if err != nil { - return errors.Wrap(err, "Expected BYTEA[] column for HashArray") + return pkgerrors.Wrap(err, "Expected BYTEA[] column for HashArray") } if baArray.Status != pgtype.Present || len(baArray.Dimensions) > 1 { - return errors.Errorf("Expected HashArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) + return pkgerrors.Errorf("Expected HashArray to be 1-dimensional. Dimensions = %v", baArray.Dimensions) } for i, ba := range baArray.Elements { hash := common.Hash{} if ba.Status != pgtype.Present { - return errors.Errorf("Expected all addresses in HashArray to be non-NULL. Got HashArray[%d] = NULL", i) + return pkgerrors.Errorf("Expected all addresses in HashArray to be non-NULL. Got HashArray[%d] = NULL", i) } err = hash.Scan(ba.Bytes) if err != nil { diff --git a/core/chains/evm/utils/ethabi.go b/core/chains/evm/utils/ethabi.go index 61d365933d2..08dfd54f430 100644 --- a/core/chains/evm/utils/ethabi.go +++ b/core/chains/evm/utils/ethabi.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/shopspring/decimal" "github.com/tidwall/gjson" @@ -222,7 +222,7 @@ func EVMWordSignedBigInt(val *big.Int) ([]byte, error) { // a signed representation. Returns error on overflow. func EVMWordBigInt(val *big.Int) ([]byte, error) { if val.Sign() == -1 { - return nil, errors.New("Uint256 cannot be negative") + return nil, pkgerrors.New("Uint256 cannot be negative") } bytes := val.Bytes() if len(bytes) > EVMWordByteLen { diff --git a/core/chains/evm/utils/ethabi_test.go b/core/chains/evm/utils/ethabi_test.go index b99d906eae7..f28a083ff01 100644 --- a/core/chains/evm/utils/ethabi_test.go +++ b/core/chains/evm/utils/ethabi_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -636,7 +636,7 @@ func EVMTranscodeBytes(value gjson.Result) ([]byte, error) { vInt, _ := v.Int(nil) word, err := EVMWordSignedBigInt(vInt) if err != nil { - return nil, errors.Wrap(err, "while converting float to int256") + return nil, pkgerrors.Wrap(err, "while converting float to int256") } return EVMEncodeBytes(word), nil default: diff --git a/core/services/relay/evm/address.go b/core/services/relay/evm/address.go index 1a3e93ed3ca..0a78270c714 100644 --- a/core/services/relay/evm/address.go +++ b/core/services/relay/evm/address.go @@ -5,7 +5,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ) @@ -13,10 +13,10 @@ func AccountToAddress(accounts []types.Account) (addresses []common.Address, err for _, signer := range accounts { bytes, err := hexutil.Decode(string(signer)) if err != nil { - return []common.Address{}, errors.Wrap(err, fmt.Sprintf("given address is not valid %s", signer)) + return []common.Address{}, pkgerrors.Wrap(err, fmt.Sprintf("given address is not valid %s", signer)) } if len(bytes) != 20 { - return []common.Address{}, errors.Errorf("address is not 20 bytes %s", signer) + return []common.Address{}, pkgerrors.Errorf("address is not 20 bytes %s", signer) } addresses = append(addresses, common.BytesToAddress(bytes)) } @@ -26,7 +26,7 @@ func AccountToAddress(accounts []types.Account) (addresses []common.Address, err func OnchainPublicKeyToAddress(publicKeys []types.OnchainPublicKey) (addresses []common.Address, err error) { for _, signer := range publicKeys { if len(signer) != 20 { - return []common.Address{}, errors.Errorf("address is not 20 bytes %s", signer) + return []common.Address{}, pkgerrors.Errorf("address is not 20 bytes %s", signer) } addresses = append(addresses, common.BytesToAddress(signer)) } diff --git a/core/services/relay/evm/config_poller.go b/core/services/relay/evm/config_poller.go index dc75fe037fe..ef9934f4e10 100644 --- a/core/services/relay/evm/config_poller.go +++ b/core/services/relay/evm/config_poller.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -57,7 +57,7 @@ func unpackLogData(d []byte) (*ocr2aggregator.OCR2AggregatorConfigSet, error) { unpacked := new(ocr2aggregator.OCR2AggregatorConfigSet) err := defaultABI.UnpackIntoInterface(unpacked, configSetEventName, d) if err != nil { - return nil, errors.Wrap(err, "failed to unpack log data") + return nil, pkgerrors.Wrap(err, "failed to unpack log data") } return unpacked, nil } @@ -166,7 +166,7 @@ func (cp *configPoller) Replay(ctx context.Context, fromBlock int64) error { func (cp *configPoller) LatestConfigDetails(ctx context.Context) (changedInBlock uint64, configDigest ocrtypes.ConfigDigest, err error) { latest, err := cp.destChainLogPoller.LatestLogByEventSigWithConfs(ConfigSet, cp.aggregatorContractAddr, 1, pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { if cp.isConfigStoreAvailable() { // Fallback to RPC call in case logs have been pruned and configStoreContract is available return cp.callLatestConfigDetails(ctx) @@ -208,7 +208,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) func (cp *configPoller) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { latest, err := cp.destChainLogPoller.LatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return 0, nil } return 0, err diff --git a/core/services/relay/evm/config_poller_test.go b/core/services/relay/evm/config_poller_test.go index 79533a06f01..28687573760 100644 --- a/core/services/relay/evm/config_poller_test.go +++ b/core/services/relay/evm/config_poller_test.go @@ -14,7 +14,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/onsi/gomega" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -208,7 +208,7 @@ func TestConfigPoller(t *testing.T) { t.Run("returns error if callLatestConfigDetails fails", func(t *testing.T) { failingClient := new(evmClientMocks.Client) failingClient.On("ConfiguredChainID").Return(big.NewInt(42)) - failingClient.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("something exploded")) + failingClient.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Return(nil, pkgerrors.New("something exploded")) cp, err := newConfigPoller(lggr, failingClient, mp, ocrAddress, &configStoreContractAddr) require.NoError(t, err) @@ -309,7 +309,7 @@ func TestConfigPoller(t *testing.T) { failingClient.On("CallContract", mock.Anything, mock.MatchedBy(func(callArgs ethereum.CallMsg) bool { // initial call to retrieve config store address from aggregator return *callArgs.To == ocrAddress - }), mock.Anything).Return(nil, errors.New("something exploded")).Once() + }), mock.Anything).Return(nil, pkgerrors.New("something exploded")).Once() cp, err := newConfigPoller(lggr, failingClient, mp, ocrAddress, &configStoreContractAddr) require.NoError(t, err) diff --git a/core/services/relay/evm/contract_transmitter.go b/core/services/relay/evm/contract_transmitter.go index 76360e34e1a..767a8f98a6d 100644 --- a/core/services/relay/evm/contract_transmitter.go +++ b/core/services/relay/evm/contract_transmitter.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" gethcommon "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -66,7 +66,7 @@ func NewOCRContractTransmitter( ) (*contractTransmitter, error) { transmitted, ok := contractABI.Events["Transmitted"] if !ok { - return nil, errors.New("invalid ABI, missing transmitted") + return nil, pkgerrors.New("invalid ABI, missing transmitted") } err := lp.RegisterFilter(logpoller.Filter{Name: transmitterFilterName(address), EventSigs: []common.Hash{transmitted.ID}, Addresses: []common.Address{address}}) @@ -94,7 +94,7 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. var ss [][32]byte var vs [32]byte if len(signatures) > 32 { - return errors.New("too many signatures, maximum is 32") + return pkgerrors.New("too many signatures, maximum is 32") } for i, as := range signatures { r, s, v, err := evmutil.SplitSignature(as.Signature) @@ -116,10 +116,10 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. payload, err := oc.contractABI.Pack("transmit", rawReportCtx, []byte(report), rs, ss, vs) if err != nil { - return errors.Wrap(err, "abi.Pack failed") + return pkgerrors.Wrap(err, "abi.Pack failed") } - return errors.Wrap(oc.transmitter.CreateEthTransaction(ctx, oc.contractAddress, payload, txMeta), "failed to send Eth transaction") + return pkgerrors.Wrap(oc.transmitter.CreateEthTransaction(ctx, oc.contractAddress, payload, txMeta), "failed to send Eth transaction") } type contractReader interface { @@ -142,7 +142,7 @@ func parseTransmitted(log []byte) ([32]byte, uint32, error) { return [32]byte{}, 0, err } if len(transmitted) < 2 { - return [32]byte{}, 0, errors.New("transmitted event log has too few arguments") + return [32]byte{}, 0, pkgerrors.New("transmitted event log has too few arguments") } configDigest := *abi.ConvertType(transmitted[0], new([32]byte)).(*[32]byte) epoch := *abi.ConvertType(transmitted[1], new(uint32)).(*uint32) @@ -184,7 +184,7 @@ func (oc *contractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) ( latest, err := oc.lp.LatestLogByEventSigWithConfs( oc.transmittedEventSig, oc.contractAddress, 1, pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { // No transmissions yet return configDigest, 0, nil } diff --git a/core/services/relay/evm/functions.go b/core/services/relay/evm/functions.go index f1d652fd6f8..26bbf09ff04 100644 --- a/core/services/relay/evm/functions.go +++ b/core/services/relay/evm/functions.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" @@ -104,7 +104,7 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa return nil, err } if !common.IsHexAddress(rargs.ContractID) { - return nil, errors.Errorf("invalid contractID, expected hex address") + return nil, pkgerrors.Errorf("invalid contractID, expected hex address") } var pluginConfig config.PluginConfig if err2 := json.Unmarshal(pargs.PluginConfig, &pluginConfig); err2 != nil { @@ -137,13 +137,13 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa func newFunctionsConfigProvider(pluginType functionsRelay.FunctionsPluginType, chain legacyevm.Chain, args commontypes.RelayArgs, fromBlock uint64, logPollerWrapper evmRelayTypes.LogPollerWrapper, lggr logger.Logger) (*configWatcher, error) { if !common.IsHexAddress(args.ContractID) { - return nil, errors.Errorf("invalid contractID, expected hex address") + return nil, pkgerrors.Errorf("invalid contractID, expected hex address") } routerContractAddress := common.HexToAddress(args.ContractID) contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) if err != nil { - return nil, errors.Wrap(err, "could not get contract ABI JSON") + return nil, pkgerrors.Wrap(err, "could not get contract ABI JSON") } cp, err := functionsRelay.NewFunctionsConfigPoller(pluginType, chain.LogPoller(), lggr) @@ -166,23 +166,23 @@ func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.R var fromAddresses []common.Address sendingKeys := relayConfig.SendingKeys if !relayConfig.EffectiveTransmitterID.Valid { - return nil, errors.New("EffectiveTransmitterID must be specified") + return nil, pkgerrors.New("EffectiveTransmitterID must be specified") } effectiveTransmitterAddress := common.HexToAddress(relayConfig.EffectiveTransmitterID.String) sendingKeysLength := len(sendingKeys) if sendingKeysLength == 0 { - return nil, errors.New("no sending keys provided") + return nil, pkgerrors.New("no sending keys provided") } // If we are using multiple sending keys, then a forwarder is needed to rotate transmissions. // Ensure that this forwarder is not set to a local sending key, and ensure our sending keys are enabled. for _, s := range sendingKeys { if sendingKeysLength > 1 && s == effectiveTransmitterAddress.String() { - return nil, errors.New("the transmitter is a local sending key with transaction forwarding enabled") + return nil, pkgerrors.New("the transmitter is a local sending key with transaction forwarding enabled") } if err := ethKeystore.CheckEnabled(common.HexToAddress(s), configWatcher.chain.Config().EVM().ChainID()); err != nil { - return nil, errors.Wrap(err, "one of the sending keys given is not enabled") + return nil, pkgerrors.Wrap(err, "one of the sending keys given is not enabled") } fromAddresses = append(fromAddresses, common.HexToAddress(s)) } @@ -213,7 +213,7 @@ func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.R ) if err != nil { - return nil, errors.Wrap(err, "failed to create transmitter") + return nil, pkgerrors.Wrap(err, "failed to create transmitter") } functionsTransmitter, err := functionsRelay.NewFunctionsContractTransmitter( diff --git a/core/services/relay/evm/functions/config_poller.go b/core/services/relay/evm/functions/config_poller.go index 7a59d499898..a1975171fd7 100644 --- a/core/services/relay/evm/functions/config_poller.go +++ b/core/services/relay/evm/functions/config_poller.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2/types" @@ -58,7 +58,7 @@ func unpackLogData(d []byte) (*ocr2aggregator.OCR2AggregatorConfigSet, error) { unpacked := new(ocr2aggregator.OCR2AggregatorConfigSet) err := defaultABI.UnpackIntoInterface(unpacked, configSetEventName, d) if err != nil { - return nil, errors.Wrap(err, "failed to unpack log data") + return nil, pkgerrors.Wrap(err, "failed to unpack log data") } return unpacked, nil } @@ -88,7 +88,7 @@ func configFromLog(logData []byte, pluginType FunctionsPluginType) (ocrtypes.Con case S4Plugin: binary.BigEndian.PutUint16(unpacked.ConfigDigest[:2], uint16(S4DigestPrefix)) default: - return ocrtypes.ContractConfig{}, errors.New("unknown plugin type") + return ocrtypes.ContractConfig{}, pkgerrors.New("unknown plugin type") } return ocrtypes.ContractConfig{ @@ -138,7 +138,7 @@ func (cp *configPoller) LatestConfigDetails(ctx context.Context) (changedInBlock latest, err := cp.destChainLogPoller.LatestLogByEventSigWithConfs(ConfigSet, *contractAddr, 1, pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return 0, ocrtypes.ConfigDigest{}, nil } return 0, ocrtypes.ConfigDigest{}, err @@ -155,7 +155,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) // (unlikely), we'll return an error here and libocr will re-try. contractAddr := cp.targetContract.Load() if contractAddr == nil { - return ocrtypes.ContractConfig{}, errors.New("no target contract address set yet") + return ocrtypes.ContractConfig{}, pkgerrors.New("no target contract address set yet") } lgs, err := cp.destChainLogPoller.Logs(int64(changedInBlock), int64(changedInBlock), ConfigSet, *contractAddr, pg.WithParentCtx(ctx)) @@ -163,7 +163,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) return ocrtypes.ContractConfig{}, err } if len(lgs) == 0 { - return ocrtypes.ContractConfig{}, errors.New("no logs found") + return ocrtypes.ContractConfig{}, pkgerrors.New("no logs found") } latestConfigSet, err := configFromLog(lgs[len(lgs)-1].Data, cp.pluginType) if err != nil { @@ -176,7 +176,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) func (cp *configPoller) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { latest, err := cp.destChainLogPoller.LatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return 0, nil } return 0, err diff --git a/core/services/relay/evm/functions/contract_transmitter.go b/core/services/relay/evm/functions/contract_transmitter.go index 2a62db31a8c..672179c2506 100644 --- a/core/services/relay/evm/functions/contract_transmitter.go +++ b/core/services/relay/evm/functions/contract_transmitter.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -73,7 +73,7 @@ func NewFunctionsContractTransmitter( ) (*contractTransmitter, error) { transmitted, ok := contractABI.Events["Transmitted"] if !ok { - return nil, errors.New("invalid ABI, missing transmitted") + return nil, pkgerrors.New("invalid ABI, missing transmitted") } if contractVersion != 1 { @@ -106,7 +106,7 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. var ss [][32]byte var vs [32]byte if len(signatures) > 32 { - return errors.New("too many signatures, maximum is 32") + return pkgerrors.New("too many signatures, maximum is 32") } for i, as := range signatures { r, s, v, err := evmutil.SplitSignature(as.Signature) @@ -129,17 +129,17 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. oc.lggr.Debugw("FunctionsContractTransmitter: start", "reportLenBytes", len(report)) requests, err2 := oc.reportCodec.DecodeReport(report) if err2 != nil { - return errors.Wrap(err2, "FunctionsContractTransmitter: DecodeReport failed") + return pkgerrors.Wrap(err2, "FunctionsContractTransmitter: DecodeReport failed") } if len(requests) == 0 { - return errors.New("FunctionsContractTransmitter: no requests in report") + return pkgerrors.New("FunctionsContractTransmitter: no requests in report") } if len(requests[0].CoordinatorContract) != common.AddressLength { return fmt.Errorf("FunctionsContractTransmitter: incorrect length of CoordinatorContract field: %d", len(requests[0].CoordinatorContract)) } destinationContract.SetBytes(requests[0].CoordinatorContract) if destinationContract == (common.Address{}) { - return errors.New("FunctionsContractTransmitter: destination coordinator contract is zero") + return pkgerrors.New("FunctionsContractTransmitter: destination coordinator contract is zero") } // Sanity check - every report should contain requests with the same coordinator contract. for _, req := range requests[1:] { @@ -157,11 +157,11 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. } payload, err := oc.contractABI.Pack("transmit", rawReportCtx, []byte(report), rs, ss, vs) if err != nil { - return errors.Wrap(err, "abi.Pack failed") + return pkgerrors.Wrap(err, "abi.Pack failed") } oc.lggr.Debugw("FunctionsContractTransmitter: transmitting report", "contractAddress", destinationContract, "txMeta", txMeta, "payloadSize", len(payload)) - return errors.Wrap(oc.transmitter.CreateEthTransaction(ctx, destinationContract, payload, txMeta), "failed to send Eth transaction") + return pkgerrors.Wrap(oc.transmitter.CreateEthTransaction(ctx, destinationContract, payload, txMeta), "failed to send Eth transaction") } type contractReader interface { @@ -184,7 +184,7 @@ func parseTransmitted(log []byte) ([32]byte, uint32, error) { return [32]byte{}, 0, err } if len(transmitted) < 2 { - return [32]byte{}, 0, errors.New("transmitted event log has too few arguments") + return [32]byte{}, 0, pkgerrors.New("transmitted event log has too few arguments") } configDigest := *abi.ConvertType(transmitted[0], new([32]byte)).(*[32]byte) epoch := *abi.ConvertType(transmitted[1], new(uint32)).(*uint32) @@ -209,7 +209,7 @@ func callContract(ctx context.Context, addr common.Address, contractABI abi.ABI, func (oc *contractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) (ocrtypes.ConfigDigest, uint32, error) { contractAddr := oc.contractAddress.Load() if contractAddr == nil { - return ocrtypes.ConfigDigest{}, 0, errors.New("destination contract address not set") + return ocrtypes.ConfigDigest{}, 0, pkgerrors.New("destination contract address not set") } latestConfigDigestAndEpoch, err := callContract(ctx, *contractAddr, oc.contractABI, "latestConfigDigestAndEpoch", nil, oc.contractReader) if err != nil { @@ -230,7 +230,7 @@ func (oc *contractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) ( latest, err := oc.lp.LatestLogByEventSigWithConfs( oc.transmittedEventSig, *contractAddr, 1, pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { // No transmissions yet return configDigest, 0, nil } diff --git a/core/services/relay/evm/functions/logpoller_wrapper.go b/core/services/relay/evm/functions/logpoller_wrapper.go index e76b567b42b..1bb3a00445e 100644 --- a/core/services/relay/evm/functions/logpoller_wrapper.go +++ b/core/services/relay/evm/functions/logpoller_wrapper.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -92,7 +92,7 @@ func NewLogPollerWrapper(routerContractAddress common.Address, pluginConfig conf } if blockOffset >= pastBlocksToPoll || requestBlockOffset >= pastBlocksToPoll || responseBlockOffset >= pastBlocksToPoll { lggr.Errorw("invalid config: number of required confirmation blocks >= pastBlocksToPoll", "pastBlocksToPoll", pastBlocksToPoll, "minIncomingConfirmations", pluginConfig.MinIncomingConfirmations, "minRequestConfirmations", pluginConfig.MinRequestConfirmations, "minResponseConfirmations", pluginConfig.MinResponseConfirmations) - return nil, errors.Errorf("invalid config: number of required confirmation blocks >= pastBlocksToPoll") + return nil, pkgerrors.Errorf("invalid config: number of required confirmation blocks >= pastBlocksToPoll") } return &logPollerWrapper{ @@ -118,7 +118,7 @@ func (l *logPollerWrapper) Start(context.Context) error { l.mu.Lock() defer l.mu.Unlock() if l.pluginConfig.ContractVersion != 1 { - return errors.New("only contract version 1 is supported") + return pkgerrors.New("only contract version 1 is supported") } l.closeWait.Add(1) go l.checkForRouteUpdates() @@ -168,7 +168,7 @@ func (l *logPollerWrapper) LatestEvents() ([]evmRelayTypes.OracleRequest, []evmR resultsResp := []evmRelayTypes.OracleResponse{} if len(coordinators) == 0 { l.lggr.Debug("LatestEvents: no non-zero coordinators to check") - return resultsReq, resultsResp, errors.New("no non-zero coordinators to check") + return resultsReq, resultsResp, pkgerrors.New("no non-zero coordinators to check") } for _, coordinator := range coordinators { diff --git a/core/services/relay/evm/median.go b/core/services/relay/evm/median.go index e3200d8e867..756dc56371f 100644 --- a/core/services/relay/evm/median.go +++ b/core/services/relay/evm/median.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2/reportingplugin/median" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -34,17 +34,17 @@ func newMedianContract(configTracker types.ContractConfigTracker, contractAddres lggr = lggr.Named("MedianContract") contract, err := offchain_aggregator_wrapper.NewOffchainAggregator(contractAddress, chain.Client()) if err != nil { - return nil, errors.Wrap(err, "could not instantiate NewOffchainAggregator") + return nil, pkgerrors.Wrap(err, "could not instantiate NewOffchainAggregator") } contractFilterer, err := ocr2aggregator.NewOCR2AggregatorFilterer(contractAddress, chain.Client()) if err != nil { - return nil, errors.Wrap(err, "could not instantiate NewOffchainAggregatorFilterer") + return nil, pkgerrors.Wrap(err, "could not instantiate NewOffchainAggregatorFilterer") } contractCaller, err := ocr2aggregator.NewOCR2AggregatorCaller(contractAddress, chain.Client()) if err != nil { - return nil, errors.Wrap(err, "could not instantiate NewOffchainAggregatorCaller") + return nil, pkgerrors.Wrap(err, "could not instantiate NewOffchainAggregatorCaller") } return &medianContract{ @@ -86,7 +86,7 @@ func (oc *medianContract) HealthReport() map[string]error { func (oc *medianContract) LatestTransmissionDetails(ctx context.Context) (ocrtypes.ConfigDigest, uint32, uint8, *big.Int, time.Time, error) { opts := bind.CallOpts{Context: ctx, Pending: false} result, err := oc.contractCaller.LatestTransmissionDetails(&opts) - return result.ConfigDigest, result.Epoch, result.Round, result.LatestAnswer, time.Unix(int64(result.LatestTimestamp), 0), errors.Wrap(err, "error getting LatestTransmissionDetails") + return result.ConfigDigest, result.Epoch, result.Round, result.LatestAnswer, time.Unix(int64(result.LatestTimestamp), 0), pkgerrors.Wrap(err, "error getting LatestTransmissionDetails") } // LatestRoundRequested returns the configDigest, epoch, and round from the latest diff --git a/core/services/relay/evm/mercury/config_poller.go b/core/services/relay/evm/mercury/config_poller.go index 98ef78020c7..dbc29754fed 100644 --- a/core/services/relay/evm/mercury/config_poller.go +++ b/core/services/relay/evm/mercury/config_poller.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" @@ -48,7 +48,7 @@ func unpackLogData(d []byte) (*verifier.VerifierConfigSet, error) { err := verifierABI.UnpackIntoInterface(unpacked, configSetEventName, d) if err != nil { - return nil, errors.Wrap(err, "failed to unpack log data") + return nil, pkgerrors.Wrap(err, "failed to unpack log data") } return unpacked, nil @@ -168,7 +168,7 @@ func (cp *ConfigPoller) LatestConfig(ctx context.Context, changedInBlock uint64) func (cp *ConfigPoller) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { latest, err := cp.destChainLogPoller.LatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { return 0, nil } return 0, err diff --git a/core/services/relay/evm/mercury/config_poller_test.go b/core/services/relay/evm/mercury/config_poller_test.go index f828938f954..44c61712b6d 100644 --- a/core/services/relay/evm/mercury/config_poller_test.go +++ b/core/services/relay/evm/mercury/config_poller_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/onsi/gomega" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" confighelper2 "github.com/smartcontractkit/libocr/offchainreporting2plus/confighelper" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -115,7 +115,7 @@ func TestMercuryConfigPoller(t *testing.T) { func onchainPublicKeyToAddress(publicKeys []types.OnchainPublicKey) (addresses []common.Address, err error) { for _, signer := range publicKeys { if len(signer) != 20 { - return []common.Address{}, errors.Errorf("address is not 20 bytes %s", signer) + return []common.Address{}, pkgerrors.Errorf("address is not 20 bytes %s", signer) } addresses = append(addresses, common.BytesToAddress(signer)) } diff --git a/core/services/relay/evm/mercury/offchain_config_digester.go b/core/services/relay/evm/mercury/offchain_config_digester.go index a12198738a9..1654ea2b8f2 100644 --- a/core/services/relay/evm/mercury/offchain_config_digester.go +++ b/core/services/relay/evm/mercury/offchain_config_digester.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/wsrpc/credentials" @@ -31,7 +31,7 @@ func (d OffchainConfigDigester) ConfigDigest(cc ocrtypes.ContractConfig) (ocrtyp signers := []common.Address{} for i, signer := range cc.Signers { if len(signer) != 20 { - return ocrtypes.ConfigDigest{}, errors.Errorf("%v-th evm signer should be a 20 byte address, but got %x", i, signer) + return ocrtypes.ConfigDigest{}, pkgerrors.Errorf("%v-th evm signer should be a 20 byte address, but got %x", i, signer) } a := common.BytesToAddress(signer) signers = append(signers, a) @@ -39,12 +39,12 @@ func (d OffchainConfigDigester) ConfigDigest(cc ocrtypes.ContractConfig) (ocrtyp transmitters := []credentials.StaticSizedPublicKey{} for i, transmitter := range cc.Transmitters { if len(transmitter) != 2*ed25519.PublicKeySize { - return ocrtypes.ConfigDigest{}, errors.Errorf("%v-th evm transmitter should be a 64 character hex-encoded ed25519 public key, but got '%v' (%d chars)", i, transmitter, len(transmitter)) + return ocrtypes.ConfigDigest{}, pkgerrors.Errorf("%v-th evm transmitter should be a 64 character hex-encoded ed25519 public key, but got '%v' (%d chars)", i, transmitter, len(transmitter)) } var t credentials.StaticSizedPublicKey b, err := hex.DecodeString(string(transmitter)) if err != nil { - return ocrtypes.ConfigDigest{}, errors.Wrapf(err, "%v-th evm transmitter is not valid hex, got: %q", i, transmitter) + return ocrtypes.ConfigDigest{}, pkgerrors.Wrapf(err, "%v-th evm transmitter is not valid hex, got: %q", i, transmitter) } copy(t[:], b) diff --git a/core/services/relay/evm/mercury/transmitter_test.go b/core/services/relay/evm/mercury/transmitter_test.go index c8a68d41a16..3be9fa0f407 100644 --- a/core/services/relay/evm/mercury/transmitter_test.go +++ b/core/services/relay/evm/mercury/transmitter_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -126,7 +126,7 @@ func Test_MercuryTransmitter_LatestTimestamp(t *testing.T) { t.Run("failing query", func(t *testing.T) { c := mocks.MockWSRPCClient{ LatestReportF: func(ctx context.Context, in *pb.LatestReportRequest) (out *pb.LatestReportResponse, err error) { - return nil, errors.New("something exploded") + return nil, pkgerrors.New("something exploded") }, } mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) @@ -180,7 +180,7 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { }) t.Run("BenchmarkPriceFromReport fails", func(t *testing.T) { codec.val = nil - codec.err = errors.New("something exploded") + codec.err = pkgerrors.New("something exploded") _, err := mt.LatestPrice(testutils.Context(t), sampleFeedID) require.Error(t, err) @@ -207,7 +207,7 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { t.Run("failing query", func(t *testing.T) { c := mocks.MockWSRPCClient{ LatestReportF: func(ctx context.Context, in *pb.LatestReportRequest) (out *pb.LatestReportResponse, err error) { - return nil, errors.New("something exploded") + return nil, pkgerrors.New("something exploded") }, } mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) @@ -259,7 +259,7 @@ func Test_MercuryTransmitter_FetchInitialMaxFinalizedBlockNumber(t *testing.T) { t.Run("failing query", func(t *testing.T) { c := mocks.MockWSRPCClient{ LatestReportF: func(ctx context.Context, in *pb.LatestReportRequest) (out *pb.LatestReportResponse, err error) { - return nil, errors.New("something exploded") + return nil, pkgerrors.New("something exploded") }, } mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) diff --git a/core/services/relay/evm/mercury/v1/data_source_test.go b/core/services/relay/evm/mercury/v1/data_source_test.go index e02efd8d9a4..82ec03c7891 100644 --- a/core/services/relay/evm/mercury/v1/data_source_test.go +++ b/core/services/relay/evm/mercury/v1/data_source_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -140,7 +140,7 @@ func TestMercury_Observe(t *testing.T) { }) t.Run("if querying latest report fails", func(t *testing.T) { orm.report = nil - orm.err = errors.New("something exploded") + orm.err = pkgerrors.New("something exploded") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -164,7 +164,7 @@ func TestMercury_Observe(t *testing.T) { t.Run("without latest report in database", func(t *testing.T) { t.Run("if FetchInitialMaxFinalizedBlockNumber returns error", func(t *testing.T) { - fetcher.err = errors.New("mock fetcher error") + fetcher.err = pkgerrors.New("mock fetcher error") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -228,7 +228,7 @@ func TestMercury_Observe(t *testing.T) { t.Cleanup(func() { runner.Err = nil }) - runner.Err = errors.New("run execution failed") + runner.Err = pkgerrors.New("run execution failed") _, err := ds.Observe(ctx, repts, false) assert.EqualError(t, err, "Observe failed while executing run: error executing run for spec ID 0: run execution failed") diff --git a/core/services/relay/evm/mercury/v2/data_source_test.go b/core/services/relay/evm/mercury/v2/data_source_test.go index c9ae37ae018..df736f76428 100644 --- a/core/services/relay/evm/mercury/v2/data_source_test.go +++ b/core/services/relay/evm/mercury/v2/data_source_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -111,7 +111,7 @@ func Test_Datasource(t *testing.T) { }) t.Run("if querying latest report fails", func(t *testing.T) { orm.report = nil - orm.err = errors.New("something exploded") + orm.err = pkgerrors.New("something exploded") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -134,7 +134,7 @@ func Test_Datasource(t *testing.T) { orm.err = nil t.Run("if LatestTimestamp returns error", func(t *testing.T) { - fetcher.tsErr = errors.New("some error") + fetcher.tsErr = pkgerrors.New("some error") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -202,7 +202,7 @@ func Test_Datasource(t *testing.T) { ds.pipelineRunner = &mercurymocks.MockRunner{ Trrs: goodTrrs, - Err: errors.New("run execution failed"), + Err: pkgerrors.New("run execution failed"), } _, err := ds.Observe(ctx, repts, false) @@ -221,7 +221,7 @@ func Test_Datasource(t *testing.T) { badTrrs := []pipeline.TaskRunResult{ { // benchmark price - Result: pipeline.Result{Error: errors.New("some error with bp")}, + Result: pipeline.Result{Error: pkgerrors.New("some error with bp")}, Task: &mercurymocks.MockTask{}, }, } @@ -263,8 +263,8 @@ func Test_Datasource(t *testing.T) { fetcher.nativePriceErr = nil }) - fetcher.linkPriceErr = errors.New("some error fetching link price") - fetcher.nativePriceErr = errors.New("some error fetching native price") + fetcher.linkPriceErr = pkgerrors.New("some error fetching link price") + fetcher.nativePriceErr = pkgerrors.New("some error fetching native price") obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) diff --git a/core/services/relay/evm/mercury/v3/data_source_test.go b/core/services/relay/evm/mercury/v3/data_source_test.go index 4ff713abb21..27b3c0d62cf 100644 --- a/core/services/relay/evm/mercury/v3/data_source_test.go +++ b/core/services/relay/evm/mercury/v3/data_source_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" mercurytypes "github.com/smartcontractkit/chainlink-common/pkg/types/mercury" @@ -121,7 +121,7 @@ func Test_Datasource(t *testing.T) { }) t.Run("if querying latest report fails", func(t *testing.T) { orm.report = nil - orm.err = errors.New("something exploded") + orm.err = pkgerrors.New("something exploded") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -144,7 +144,7 @@ func Test_Datasource(t *testing.T) { orm.err = nil t.Run("if LatestTimestamp returns error", func(t *testing.T) { - fetcher.tsErr = errors.New("some error") + fetcher.tsErr = pkgerrors.New("some error") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -216,7 +216,7 @@ func Test_Datasource(t *testing.T) { ds.pipelineRunner = &mercurymocks.MockRunner{ Trrs: goodTrrs, - Err: errors.New("run execution failed"), + Err: pkgerrors.New("run execution failed"), } _, err := ds.Observe(ctx, repts, false) @@ -245,7 +245,7 @@ func Test_Datasource(t *testing.T) { }, { // ask - Result: pipeline.Result{Error: errors.New("some error with ask")}, + Result: pipeline.Result{Error: pkgerrors.New("some error with ask")}, Task: &mercurymocks.MockTask{}, }, } @@ -291,8 +291,8 @@ func Test_Datasource(t *testing.T) { fetcher.nativePriceErr = nil }) - fetcher.linkPriceErr = errors.New("some error fetching link price") - fetcher.nativePriceErr = errors.New("some error fetching native price") + fetcher.linkPriceErr = pkgerrors.New("some error fetching link price") + fetcher.nativePriceErr = pkgerrors.New("some error fetching native price") obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) diff --git a/core/services/relay/evm/mercury/wsrpc/client.go b/core/services/relay/evm/mercury/wsrpc/client.go index c9533717757..6812dd44c11 100644 --- a/core/services/relay/evm/mercury/wsrpc/client.go +++ b/core/services/relay/evm/mercury/wsrpc/client.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -156,7 +156,7 @@ func (w *client) dial(ctx context.Context, opts ...wsrpc.DialOption) error { if err != nil { w.dialErrorCountMetric.Inc() setLivenessMetric(false) - return errors.Wrap(err, "failed to dial wsrpc client") + return pkgerrors.Wrap(err, "failed to dial wsrpc client") } w.dialSuccessCountMetric.Inc() setLivenessMetric(true) @@ -231,7 +231,7 @@ func (w *client) Healthy() (err error) { } state := w.conn.GetState() if state != connectivity.Ready { - return errors.Errorf("client state should be %s; got %s", connectivity.Ready, state) + return pkgerrors.Errorf("client state should be %s; got %s", connectivity.Ready, state) } return nil } @@ -239,12 +239,12 @@ func (w *client) Healthy() (err error) { func (w *client) waitForReady(ctx context.Context) (err error) { ok := w.IfStarted(func() { if ready := w.conn.WaitForReady(ctx); !ready { - err = errors.Errorf("websocket client not ready; got state: %v", w.conn.GetState()) + err = pkgerrors.Errorf("websocket client not ready; got state: %v", w.conn.GetState()) return } }) if !ok { - return errors.New("client is not started") + return pkgerrors.New("client is not started") } return } @@ -253,7 +253,7 @@ func (w *client) Transmit(ctx context.Context, req *pb.TransmitRequest) (resp *p w.logger.Trace("Transmit") start := time.Now() if err = w.waitForReady(ctx); err != nil { - return nil, errors.Wrap(err, "Transmit call failed") + return nil, pkgerrors.Wrap(err, "Transmit call failed") } resp, err = w.rawClient.Transmit(ctx, req) w.handleTimeout(err) @@ -269,7 +269,7 @@ func (w *client) Transmit(ctx context.Context, req *pb.TransmitRequest) (resp *p } func (w *client) handleTimeout(err error) { - if errors.Is(err, context.DeadlineExceeded) { + if pkgerrors.Is(err, context.DeadlineExceeded) { w.timeoutCountMetric.Inc() cnt := w.consecutiveTimeoutCnt.Add(1) if cnt == MaxConsecutiveRequestFailures { @@ -305,7 +305,7 @@ func (w *client) LatestReport(ctx context.Context, req *pb.LatestReportRequest) lggr := w.logger.With("req.FeedId", hexutil.Encode(req.FeedId)) lggr.Trace("LatestReport") if err = w.waitForReady(ctx); err != nil { - return nil, errors.Wrap(err, "LatestReport failed") + return nil, pkgerrors.Wrap(err, "LatestReport failed") } var cached bool if w.cache == nil { diff --git a/core/services/relay/evm/ocr2keeper.go b/core/services/relay/evm/ocr2keeper.go index 34daf55b835..778d48adf55 100644 --- a/core/services/relay/evm/ocr2keeper.go +++ b/core/services/relay/evm/ocr2keeper.go @@ -20,7 +20,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" @@ -219,7 +219,7 @@ func newOCR2KeeperConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rarg contractAddress := common.HexToAddress(rargs.ContractID) contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) if err != nil { - return nil, errors.Wrap(err, "could not get OCR2Aggregator ABI JSON") + return nil, pkgerrors.Wrap(err, "could not get OCR2Aggregator ABI JSON") } configPoller, err := NewConfigPoller( @@ -231,7 +231,7 @@ func newOCR2KeeperConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rarg nil, ) if err != nil { - return nil, errors.Wrap(err, "failed to create config poller") + return nil, pkgerrors.Wrap(err, "failed to create config poller") } offchainConfigDigester := evmutil.EVMOffchainConfigDigester{ diff --git a/core/services/relay/evm/ocr2vrf.go b/core/services/relay/evm/ocr2vrf.go index 1e05f89d9de..0c10b18876f 100644 --- a/core/services/relay/evm/ocr2vrf.go +++ b/core/services/relay/evm/ocr2vrf.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" @@ -140,7 +140,7 @@ func newOCR2VRFConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rargs c contractAddress := common.HexToAddress(rargs.ContractID) contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorABI)) if err != nil { - return nil, errors.Wrap(err, "could not get OCR2Aggregator ABI JSON") + return nil, pkgerrors.Wrap(err, "could not get OCR2Aggregator ABI JSON") } configPoller, err := NewConfigPoller( lggr.With("contractID", rargs.ContractID), diff --git a/core/services/relay/evm/relayer_extender.go b/core/services/relay/evm/relayer_extender.go index 83f03b47f9e..79800a14b1a 100644 --- a/core/services/relay/evm/relayer_extender.go +++ b/core/services/relay/evm/relayer_extender.go @@ -5,7 +5,7 @@ import ( "fmt" "math/big" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/loop" @@ -16,7 +16,7 @@ import ( ) // ErrNoChains indicates that no EVM chains have been started -var ErrNoChains = errors.New("no EVM chains loaded") +var ErrNoChains = pkgerrors.New("no EVM chains loaded") type EVMChainRelayerExtender interface { loop.RelayerExt @@ -94,7 +94,7 @@ func (s *ChainRelayerExt) Chain() legacyevm.Chain { return s.chain } -var ErrCorruptEVMChain = errors.New("corrupt evm chain") +var ErrCorruptEVMChain = pkgerrors.New("corrupt evm chain") func (s *ChainRelayerExt) Start(ctx context.Context) error { return s.chain.Start(ctx) diff --git a/core/services/relay/evm/request_round_db.go b/core/services/relay/evm/request_round_db.go index b3a5b01bc2c..a28c24837a3 100644 --- a/core/services/relay/evm/request_round_db.go +++ b/core/services/relay/evm/request_round_db.go @@ -4,7 +4,7 @@ import ( "database/sql" "encoding/json" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -35,7 +35,7 @@ func NewRoundRequestedDB(sqldb *sql.DB, oracleSpecID int32, lggr logger.Logger) func (d *requestRoundDB) SaveLatestRoundRequested(tx pg.Queryer, rr ocr2aggregator.OCR2AggregatorRoundRequested) error { rawLog, err := json.Marshal(rr.Raw) if err != nil { - return errors.Wrap(err, "could not marshal log as JSON") + return pkgerrors.Wrap(err, "could not marshal log as JSON") } _, err = tx.Exec(` INSERT INTO ocr2_latest_round_requested (ocr2_oracle_spec_id, requester, config_digest, epoch, round, raw) @@ -47,7 +47,7 @@ VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (ocr2_oracle_spec_id) DO UPDATE SET raw = EXCLUDED.raw `, d.oracleSpecID, rr.Requester, rr.ConfigDigest[:], rr.Epoch, rr.Round, rawLog) - return errors.Wrap(err, "could not save latest round requested") + return pkgerrors.Wrap(err, "could not save latest round requested") } func (d *requestRoundDB) LoadLatestRoundRequested() (ocr2aggregator.OCR2AggregatorRoundRequested, error) { @@ -59,7 +59,7 @@ WHERE ocr2_oracle_spec_id = $1 LIMIT 1 `, d.oracleSpecID) if err != nil { - return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to query rows") + return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to query rows") } defer rows.Close() @@ -69,17 +69,17 @@ LIMIT 1 err = rows.Scan(&rr.Requester, &configDigest, &rr.Epoch, &rr.Round, &rawLog) if err != nil { - return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to scan row") + return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to scan row") } rr.ConfigDigest, err = ocrtypes.BytesToConfigDigest(configDigest) if err != nil { - return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to decode config digest") + return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to decode config digest") } err = json.Unmarshal(rawLog, &rr.Raw) if err != nil { - return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to unmarshal raw log") + return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to unmarshal raw log") } } diff --git a/core/services/relay/evm/request_round_tracker.go b/core/services/relay/evm/request_round_tracker.go index 1f1ed71fc31..6fe105adcd3 100644 --- a/core/services/relay/evm/request_round_tracker.go +++ b/core/services/relay/evm/request_round_tracker.go @@ -7,7 +7,7 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" gethTypes "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -83,7 +83,7 @@ func (t *RequestRoundTracker) Start() error { return t.StartOnce("RequestRoundTracker", func() (err error) { t.latestRoundRequested, err = t.odb.LoadLatestRoundRequested() if err != nil { - return errors.Wrap(err, "RequestRoundTracker#Start: failed to load latest round requested") + return pkgerrors.Wrap(err, "RequestRoundTracker#Start: failed to load latest round requested") } t.unsubscribeLogs = t.logBroadcaster.Register(t, log.ListenerOpts{ diff --git a/core/services/relay/evm/request_round_tracker_test.go b/core/services/relay/evm/request_round_tracker_test.go index cb2ee2a8d72..cd9eca822aa 100644 --- a/core/services/relay/evm/request_round_tracker_test.go +++ b/core/services/relay/evm/request_round_tracker_test.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common" gethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -244,7 +244,7 @@ func Test_OCRContractTracker_HandleLog_OCRContractLatestRoundRequested(t *testin logBroadcast.On("String").Return("").Maybe() uni.lb.On("WasAlreadyConsumed", mock.Anything, mock.Anything).Return(false, nil) - uni.db.On("SaveLatestRoundRequested", mock.Anything, mock.Anything).Return(errors.New("something exploded")) + uni.db.On("SaveLatestRoundRequested", mock.Anything, mock.Anything).Return(pkgerrors.New("something exploded")) uni.requestRoundTracker.HandleLog(logBroadcast) From fd4146f74b845ba2a28bced129f9d324f9757c4e Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 22 Jan 2024 17:46:34 -0500 Subject: [PATCH 03/11] fix bad import --- charts/chainlink-cluster/dashboard/dashboard.go | 6 +++--- core/auth/auth.go | 6 +++--- integration-tests/universal/log_poller/config.go | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/charts/chainlink-cluster/dashboard/dashboard.go b/charts/chainlink-cluster/dashboard/dashboard.go index 41774b06c96..54b59ae25e6 100644 --- a/charts/chainlink-cluster/dashboard/dashboard.go +++ b/charts/chainlink-cluster/dashboard/dashboard.go @@ -5,7 +5,6 @@ import ( "fmt" "net/http" - "cosmossdk.io/errors" "github.com/K-Phoen/grabana" "github.com/K-Phoen/grabana/dashboard" "github.com/K-Phoen/grabana/logs" @@ -15,6 +14,7 @@ import ( "github.com/K-Phoen/grabana/timeseries" "github.com/K-Phoen/grabana/timeseries/axis" "github.com/K-Phoen/grabana/variable/query" + pkgerrors "github.com/pkg/errors" ) /* @@ -954,10 +954,10 @@ func (m *CLClusterDashboard) Deploy(ctx context.Context) error { client := grabana.NewClient(&http.Client{}, m.GrafanaURL, grabana.WithAPIToken(m.GrafanaToken)) folder, err := client.FindOrCreateFolder(ctx, m.Folder) if err != nil { - return errors.Wrap(err, ErrFailedToCreateFolder) + return pkgerrors.Wrap(err, ErrFailedToCreateFolder) } if _, err := client.UpsertDashboard(ctx, folder, m.builder); err != nil { - return errors.Wrap(err, ErrFailedToCreateDashboard) + return pkgerrors.Wrap(err, ErrFailedToCreateDashboard) } return nil } diff --git a/core/auth/auth.go b/core/auth/auth.go index 8fae335dc5f..d6e6a107df9 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "fmt" - "cosmossdk.io/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/utils" "golang.org/x/crypto/sha3" @@ -14,7 +14,7 @@ var ( // ErrorAuthFailed is a generic authentication failed - but not because of // some system failure on our behalf (i.e. HTTP 5xx), more detail is not // given - ErrorAuthFailed = errors.New("Authentication failed") + ErrorAuthFailed = pkgerrors.New("Authentication failed") ) // Token is used for API authentication. @@ -57,7 +57,7 @@ func HashedSecret(ta *Token, salt string) (string, error) { hasher := sha3.New256() _, err := hasher.Write(hashInput(ta, salt)) if err != nil { - return "", errors.Wrap(err, "error writing external initiator authentication to hasher") + return "", pkgerrors.Wrap(err, "error writing external initiator authentication to hasher") } return hex.EncodeToString(hasher.Sum(nil)), nil } diff --git a/integration-tests/universal/log_poller/config.go b/integration-tests/universal/log_poller/config.go index d42520397e8..c2f992bad42 100644 --- a/integration-tests/universal/log_poller/config.go +++ b/integration-tests/universal/log_poller/config.go @@ -5,9 +5,9 @@ import ( "os" "strconv" - "cosmossdk.io/errors" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/pelletier/go-toml/v2" + pkgerrors "github.com/pkg/errors" "github.com/rs/zerolog/log" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" @@ -76,11 +76,11 @@ func ReadConfig(configName string) (*Config, error) { var cfg *Config d, err := os.ReadFile(configName) if err != nil { - return nil, errors.Wrap(err, ErrReadPerfConfig) + return nil, pkgerrors.Wrap(err, ErrReadPerfConfig) } err = toml.Unmarshal(d, &cfg) if err != nil { - return nil, errors.Wrap(err, ErrUnmarshalPerfConfig) + return nil, pkgerrors.Wrap(err, ErrUnmarshalPerfConfig) } if err := cfg.validate(); err != nil { From b34f27f616332cda5f88e85dba5dfe52304d3655 Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 22 Jan 2024 17:47:19 -0500 Subject: [PATCH 04/11] run go mod tidy --- integration-tests/go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 53135cfea7c..b90d51e3f1b 100644 --- a/integration-tests/go.mod +++ b/integration-tests/go.mod @@ -6,7 +6,6 @@ go 1.21.4 replace github.com/smartcontractkit/chainlink/v2 => ../ require ( - cosmossdk.io/errors v1.0.0 github.com/K-Phoen/grabana v0.21.17 github.com/cli/go-gh/v2 v2.0.0 github.com/ethereum/go-ethereum v1.13.8 @@ -60,6 +59,7 @@ require ( cosmossdk.io/api v0.3.1 // indirect cosmossdk.io/core v0.5.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect + cosmossdk.io/errors v1.0.0 // indirect cosmossdk.io/math v1.0.1 // indirect dario.cat/mergo v1.0.0 // indirect filippo.io/edwards25519 v1.0.0 // indirect From 3a9fdfdb31f7102a2464fe99c87ee2e43a982593 Mon Sep 17 00:00:00 2001 From: James Walker Date: Tue, 23 Jan 2024 10:42:15 -0500 Subject: [PATCH 05/11] rename more pkgs --- core/cmd/app.go | 8 +-- core/cmd/blocks_commands.go | 4 +- core/cmd/csa_keys_commands.go | 22 +++--- core/cmd/eth_keys_commands.go | 34 ++++----- core/cmd/eth_keys_commands_test.go | 6 +- core/cmd/forwarders_commands.go | 8 +-- core/cmd/jobs_commands.go | 10 +-- core/cmd/key_store_authenticator.go | 6 +- core/cmd/keys_commands.go | 24 +++---- core/cmd/ocr2_keys_commands.go | 26 +++---- core/cmd/ocr2vrf_configure_commands.go | 44 ++++++------ core/cmd/ocr_keys_commands.go | 24 +++---- core/cmd/p2p_keys_commands.go | 24 +++---- core/cmd/shell.go | 44 ++++++------ core/cmd/shell_local.go | 74 ++++++++++---------- core/cmd/shell_remote.go | 36 +++++----- core/cmd/solana_transaction_commands.go | 10 +-- core/cmd/vrf_keys_commands.go | 26 +++---- core/config/app_config.go | 4 +- core/config/docs/docs_test.go | 4 +- core/config/parse/parsers.go | 4 +- core/gethwrappers/versions.go | 28 ++++---- core/internal/testutils/httptest/httptest.go | 4 +- core/internal/testutils/keystest/keystest.go | 4 +- core/logger/zap.go | 4 +- core/sessions/localauth/orm.go | 32 ++++----- core/sessions/session.go | 4 +- core/sessions/user.go | 10 +-- core/sessions/webauthn.go | 2 +- core/store/migrate/migrate.go | 8 +-- 30 files changed, 269 insertions(+), 269 deletions(-) diff --git a/core/cmd/app.go b/core/cmd/app.go index 8e61380156c..f87d0a863fb 100644 --- a/core/cmd/app.go +++ b/core/cmd/app.go @@ -7,7 +7,7 @@ import ( "path/filepath" "regexp" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "github.com/smartcontractkit/chainlink/v2/core/build" @@ -98,7 +98,7 @@ func NewApp(s *Shell) *cli.App { urlStr := c.String("remote-node-url") remoteNodeURL, err := url.Parse(urlStr) if err != nil { - return errors.Wrapf(err, "%s is not a valid URL", urlStr) + return pkgerrors.Wrapf(err, "%s is not a valid URL", urlStr) } insecureSkipVerify := c.Bool("insecure-skip-verify") @@ -108,8 +108,8 @@ func NewApp(s *Shell) *cli.App { credentialsFile := c.String("admin-credentials-file") sr, err := sessionRequestBuilder.Build(credentialsFile) - if err != nil && !errors.Is(errors.Cause(err), ErrNoCredentialFile) && !os.IsNotExist(err) { - return errors.Wrapf(err, "failed to load API credentials from file %s", credentialsFile) + if err != nil && !pkgerrors.Is(pkgerrors.Cause(err), ErrNoCredentialFile) && !os.IsNotExist(err) { + return pkgerrors.Wrapf(err, "failed to load API credentials from file %s", credentialsFile) } s.HTTP = NewAuthenticatedHTTPClient(s.Logger, clientOpts, cookieAuth, sr) diff --git a/core/cmd/blocks_commands.go b/core/cmd/blocks_commands.go index 72b0523e18d..8570826c8b6 100644 --- a/core/cmd/blocks_commands.go +++ b/core/cmd/blocks_commands.go @@ -6,7 +6,7 @@ import ( "net/url" "strconv" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" ) @@ -41,7 +41,7 @@ func initBlocksSubCmds(s *Shell) []cli.Command { func (s *Shell) ReplayFromBlock(c *cli.Context) (err error) { blockNumber := c.Int64("block-number") if blockNumber <= 0 { - return s.errorOut(errors.New("Must pass a positive value in '--block-number' parameter")) + return s.errorOut(pkgerrors.New("Must pass a positive value in '--block-number' parameter")) } v := url.Values{} diff --git a/core/cmd/csa_keys_commands.go b/core/cmd/csa_keys_commands.go index 1c0fe54ab09..35e7b25d29d 100644 --- a/core/cmd/csa_keys_commands.go +++ b/core/cmd/csa_keys_commands.go @@ -8,7 +8,7 @@ import ( "net/url" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -139,16 +139,16 @@ func (s *Shell) CreateCSAKey(_ *cli.Context) (err error) { // ImportCSAKey imports and stores a CSA key. Path to key must be passed. func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -181,22 +181,22 @@ func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { // ExportCSAKey exports a CSA key. Key ID must be passed. func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -210,7 +210,7 @@ func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { exportUrl.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), exportUrl.String(), nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -224,12 +224,12 @@ func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported P2P key %s to %s\n", ID, filepath)) diff --git a/core/cmd/eth_keys_commands.go b/core/cmd/eth_keys_commands.go index 5adac3b382b..52243000ff1 100644 --- a/core/cmd/eth_keys_commands.go +++ b/core/cmd/eth_keys_commands.go @@ -10,7 +10,7 @@ import ( "os" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -223,7 +223,7 @@ func (s *Shell) CreateETHKey(c *cli.Context) (err error) { // address of key must be passed func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the address of the key to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the address of the key to be deleted")) } address := c.Args().Get(0) @@ -244,14 +244,14 @@ func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Failed to read request response")) + return s.errorOut(pkgerrors.Wrap(err, "Failed to read request response")) } var result *models.JSONAPIErrors err = json.Unmarshal(body, &result) if err != nil { - return s.errorOut(errors.Wrapf(err, "Unable to unmarshal json from body '%s'", string(body))) + return s.errorOut(pkgerrors.Wrapf(err, "Unable to unmarshal json from body '%s'", string(body))) } - return s.errorOut(errors.Errorf("Delete ETH key failed: %s", result.Error())) + return s.errorOut(pkgerrors.Errorf("Delete ETH key failed: %s", result.Error())) } return s.renderAPIResponse(resp, &EthKeyPresenter{}, fmt.Sprintf("🔑 Deleted ETH key: %s\n", address)) } @@ -260,16 +260,16 @@ func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { // file path must be passed func (s *Shell) ImportETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -307,21 +307,21 @@ func (s *Shell) ImportETHKey(c *cli.Context) (err error) { // address must be passed func (s *Shell) ExportETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the address of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the address of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(newPassword) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } address := c.Args().Get(0) @@ -334,7 +334,7 @@ func (s *Shell) ExportETHKey(c *cli.Context) (err error) { exportUrl.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), exportUrl.String(), nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -348,12 +348,12 @@ func (s *Shell) ExportETHKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString("🔑 Exported ETH key " + address + " to " + filepath + "\n") @@ -377,7 +377,7 @@ func (s *Shell) UpdateChainEVMKey(c *cli.Context) (err error) { query.Set("abandon", abandon) if c.IsSet("enable") && c.IsSet("disable") { - return s.errorOut(errors.New("cannot set both --enable and --disable simultaneously")) + return s.errorOut(pkgerrors.New("cannot set both --enable and --disable simultaneously")) } else if c.Bool("enable") { query.Set("enabled", "true") } else if c.Bool("disable") { @@ -387,7 +387,7 @@ func (s *Shell) UpdateChainEVMKey(c *cli.Context) (err error) { chainURL.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), chainURL.String(), nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { diff --git a/core/cmd/eth_keys_commands_test.go b/core/cmd/eth_keys_commands_test.go index de40a5bf873..88b1e194208 100644 --- a/core/cmd/eth_keys_commands_test.go +++ b/core/cmd/eth_keys_commands_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" "github.com/smartcontractkit/chainlink-common/pkg/utils" @@ -116,8 +116,8 @@ func TestShell_ListETHKeys_Error(t *testing.T) { t.Parallel() ethClient := newEthMock(t) - ethClient.On("BalanceAt", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("fake error")) - ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("fake error")) + ethClient.On("BalanceAt", mock.Anything, mock.Anything, mock.Anything).Return(nil, pkgerrors.New("fake error")) + ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(nil, pkgerrors.New("fake error")) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].Enabled = ptr(true) diff --git a/core/cmd/forwarders_commands.go b/core/cmd/forwarders_commands.go index 2445be5bfec..f6d40de7b25 100644 --- a/core/cmd/forwarders_commands.go +++ b/core/cmd/forwarders_commands.go @@ -10,7 +10,7 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -100,7 +100,7 @@ func (s *Shell) ListForwarders(c *cli.Context) (err error) { // DeleteForwarder deletes forwarder address from node db by id. func (s *Shell) DeleteForwarder(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("must pass the forwarder id to be archived")) + return s.errorOut(pkgerrors.New("must pass the forwarder id to be archived")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/nodes/evm/forwarders/"+c.Args().First()) if err != nil { @@ -122,7 +122,7 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { addressBytes, err := hexutil.Decode(addressHex) if err != nil { - return s.errorOut(errors.Wrap(err, "could not decode address")) + return s.errorOut(pkgerrors.Wrap(err, "could not decode address")) } address := gethCommon.BytesToAddress(addressBytes) @@ -131,7 +131,7 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { var ok bool chainID, ok = big.NewInt(0).SetString(chainIDStr, 10) if !ok { - return s.errorOut(errors.Wrap(err, "invalid evm-chain-id")) + return s.errorOut(pkgerrors.Wrap(err, "invalid evm-chain-id")) } } diff --git a/core/cmd/jobs_commands.go b/core/cmd/jobs_commands.go index 1f9ca33c78e..f46f5c11e9b 100644 --- a/core/cmd/jobs_commands.go +++ b/core/cmd/jobs_commands.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -209,7 +209,7 @@ func (s *Shell) ListJobs(c *cli.Context) (err error) { // ShowJob displays the details of a job func (s *Shell) ShowJob(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("must provide the id of the job")) + return s.errorOut(pkgerrors.New("must provide the id of the job")) } id := c.Args().First() resp, err := s.HTTP.Get(s.ctx(), "/v2/jobs/"+id) @@ -229,7 +229,7 @@ func (s *Shell) ShowJob(c *cli.Context) (err error) { // Valid input is a TOML string or a path to TOML file func (s *Shell) CreateJob(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("must pass in TOML or filepath")) + return s.errorOut(pkgerrors.New("must pass in TOML or filepath")) } tomlString, err := getTOMLString(c.Args().First()) @@ -271,7 +271,7 @@ func (s *Shell) CreateJob(c *cli.Context) (err error) { // DeleteJob deletes a job func (s *Shell) DeleteJob(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("must pass the job id to be archived")) + return s.errorOut(pkgerrors.New("must pass the job id to be archived")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/jobs/"+c.Args().First()) if err != nil { @@ -289,7 +289,7 @@ func (s *Shell) DeleteJob(c *cli.Context) error { // TriggerPipelineRun triggers a job run based on a job ID func (s *Shell) TriggerPipelineRun(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the job id to trigger a run")) + return s.errorOut(pkgerrors.New("Must pass the job id to trigger a run")) } resp, err := s.HTTP.Post(s.ctx(), "/v2/jobs/"+c.Args().First()+"/runs", nil) if err != nil { diff --git a/core/cmd/key_store_authenticator.go b/core/cmd/key_store_authenticator.go index 0707aa5087d..4a0b429b5cd 100644 --- a/core/cmd/key_store_authenticator.go +++ b/core/cmd/key_store_authenticator.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -23,7 +23,7 @@ type keystorePassword interface { func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, password keystorePassword) error { isEmpty, err := keyStore.IsEmpty() if err != nil { - return errors.Wrap(err, "error determining if keystore is empty") + return pkgerrors.Wrap(err, "error determining if keystore is empty") } pw := password.Keystore() @@ -38,7 +38,7 @@ func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, } interactive := auth.Prompter.IsTerminal() if !interactive { - return errors.New("no password provided") + return pkgerrors.New("no password provided") } else if !isEmpty { pw = auth.promptExistingPassword() } else { diff --git a/core/cmd/keys_commands.go b/core/cmd/keys_commands.go index 7408d168887..8d6c964b310 100644 --- a/core/cmd/keys_commands.go +++ b/core/cmd/keys_commands.go @@ -8,7 +8,7 @@ import ( "os" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -139,7 +139,7 @@ func (cli *keysClient[K, P, P2]) CreateKey(_ *cli.Context) (err error) { // key ID must be passed func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(errors.New("Must pass the key ID to be deleted")) + return cli.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id := c.Args().Get(0) @@ -170,16 +170,16 @@ func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { // path to key must be passed func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return cli.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return cli.errorOut(errors.New("Must specify --old-password/-p flag")) + return cli.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not read password file")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -207,21 +207,21 @@ func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { // key ID must be passed func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(errors.New("Must pass the ID of the key to export")) + return cli.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return cli.errorOut(errors.New("Must specify --new-password/-p flag")) + return cli.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not read password file")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return cli.errorOut(errors.New("Must specify --output/-o flag")) + return cli.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -229,7 +229,7 @@ func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := cli.HTTP.Post(cli.ctx(), cli.path+"/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -243,12 +243,12 @@ func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return cli.errorOut(errors.Wrap(err, "Could not read response body")) + return cli.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0600) if err != nil { - return cli.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return cli.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported %s key %s to %s\n", cli.typ, ID, filepath)) diff --git a/core/cmd/ocr2_keys_commands.go b/core/cmd/ocr2_keys_commands.go index 1d469024878..ee5f821294c 100644 --- a/core/cmd/ocr2_keys_commands.go +++ b/core/cmd/ocr2_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -145,7 +145,7 @@ func (s *Shell) ListOCR2KeyBundles(_ *cli.Context) error { func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { if !c.Args().Present() { return s.errorOut( - errors.Errorf(`must pass the type to create, options are: %s`, chaintype.SupportedChainTypes.String()), + pkgerrors.Errorf(`must pass the type to create, options are: %s`, chaintype.SupportedChainTypes.String()), ) } chainType := c.Args().Get(0) @@ -166,7 +166,7 @@ func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { // DeleteOCR2KeyBundle deletes an OCR2 key bundle func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id, err := models.Sha256HashFromHex(c.Args().Get(0)) if err != nil { @@ -199,16 +199,16 @@ func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { // ImportOCR2Key imports OCR2 key bundle func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -235,21 +235,21 @@ func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { // ExportOCR2Key exports an OCR2 key bundle by ID func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -257,7 +257,7 @@ func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr2/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -271,12 +271,12 @@ func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported OCR key bundle %s to %s", ID, filepath)) diff --git a/core/cmd/ocr2vrf_configure_commands.go b/core/cmd/ocr2vrf_configure_commands.go index 06f26ddb6a4..cde341c4c48 100644 --- a/core/cmd/ocr2vrf_configure_commands.go +++ b/core/cmd/ocr2vrf_configure_commands.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/pelletier/go-toml" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "github.com/jmoiron/sqlx" @@ -137,14 +137,14 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e if passwordFile := c.String("password"); passwordFile != "" { p, err := utils.PasswordFromFile(passwordFile) if err != nil { - return nil, errors.Wrap(err, "error reading password from file") + return nil, pkgerrors.Wrap(err, "error reading password from file") } pwd = &p } if vrfPasswordFile := c.String("vrfpassword"); len(vrfPasswordFile) != 0 { p, err := utils.PasswordFromFile(vrfPasswordFile) if err != nil { - return nil, errors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) + return nil, pkgerrors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) } vrfpwd = &p } @@ -153,20 +153,20 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e err := s.Config.Validate() if err != nil { - return nil, s.errorOut(errors.Wrap(err, "config validation failed")) + return nil, s.errorOut(pkgerrors.Wrap(err, "config validation failed")) } cfg := s.Config ldb := pg.NewLockedDB(cfg.AppID(), cfg.Database(), cfg.Database().Lock(), lggr) if err = ldb.Open(ctx); err != nil { - return nil, s.errorOut(errors.Wrap(err, "opening db")) + return nil, s.errorOut(pkgerrors.Wrap(err, "opening db")) } defer lggr.ErrorIfFn(ldb.Close, "Error closing db") app, err := s.AppFactory.NewApplication(ctx, s.Config, lggr, ldb.DB()) if err != nil { - return nil, s.errorOut(errors.Wrap(err, "fatal error instantiating application")) + return nil, s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) } chainID := c.Int64("chainID") @@ -236,7 +236,7 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e } } if ocr2 == nil { - return nil, s.errorOut(errors.Wrap(job.ErrNoSuchKeyBundle, "evm OCR2 key bundle not found")) + return nil, s.errorOut(pkgerrors.Wrap(job.ErrNoSuchKeyBundle, "evm OCR2 key bundle not found")) } offChainPublicKey := ocr2.OffchainPublicKey() configPublicKey := ocr2.ConfigEncryptionPublicKey() @@ -353,7 +353,7 @@ func (s *Shell) authorizeForwarder(c *cli.Context, db *sqlx.DB, lggr logger.Logg func setupKeystore(cli *Shell, app chainlink.Application, keyStore keystore.Master) error { if err := cli.KeyStoreAuthenticator.authenticate(keyStore, cli.Config.Password()); err != nil { - return errors.Wrap(err, "error authenticating keystore") + return pkgerrors.Wrap(err, "error authenticating keystore") } if cli.Config.EVMEnabled() { @@ -363,7 +363,7 @@ func setupKeystore(cli *Shell, app chainlink.Application, keyStore keystore.Mast } for _, ch := range chains { if err = keyStore.Eth().EnsureKeys(ch.ID()); err != nil { - return errors.Wrap(err, "failed to ensure keystore keys") + return pkgerrors.Wrap(err, "failed to ensure keystore keys") } } } @@ -383,19 +383,19 @@ func setupKeystore(cli *Shell, app chainlink.Application, keyStore keystore.Mast } if err := keyStore.OCR2().EnsureKeys(enabledChains...); err != nil { - return errors.Wrap(err, "failed to ensure ocr key") + return pkgerrors.Wrap(err, "failed to ensure ocr key") } if err := keyStore.DKGSign().EnsureKey(); err != nil { - return errors.Wrap(err, "failed to ensure dkgsign key") + return pkgerrors.Wrap(err, "failed to ensure dkgsign key") } if err := keyStore.DKGEncrypt().EnsureKey(); err != nil { - return errors.Wrap(err, "failed to ensure dkgencrypt key") + return pkgerrors.Wrap(err, "failed to ensure dkgencrypt key") } if err := keyStore.P2P().EnsureKey(); err != nil { - return errors.Wrap(err, "failed to ensure p2p key") + return pkgerrors.Wrap(err, "failed to ensure p2p key") } return nil @@ -410,18 +410,18 @@ func createBootstrapperJob(ctx context.Context, lggr logger.Logger, c *cli.Conte var jb job.Job err := toml.Unmarshal([]byte(sp), &jb) if err != nil { - return errors.Wrap(err, "failed to unmarshal job spec") + return pkgerrors.Wrap(err, "failed to unmarshal job spec") } var os job.BootstrapSpec err = toml.Unmarshal([]byte(sp), &os) if err != nil { - return errors.Wrap(err, "failed to unmarshal job spec") + return pkgerrors.Wrap(err, "failed to unmarshal job spec") } jb.BootstrapSpec = &os err = app.AddJobV2(ctx, &jb) if err != nil { - return errors.Wrap(err, "failed to add job") + return pkgerrors.Wrap(err, "failed to add job") } lggr.Info("bootstrap spec:", sp) @@ -447,18 +447,18 @@ func createDKGJob(ctx context.Context, lggr logger.Logger, app chainlink.Applica var jb job.Job err := toml.Unmarshal([]byte(sp), &jb) if err != nil { - return errors.Wrap(err, "failed to unmarshal job spec") + return pkgerrors.Wrap(err, "failed to unmarshal job spec") } var os job.OCR2OracleSpec err = toml.Unmarshal([]byte(sp), &os) if err != nil { - return errors.Wrap(err, "failed to unmarshal job spec") + return pkgerrors.Wrap(err, "failed to unmarshal job spec") } jb.OCR2OracleSpec = &os err = app.AddJobV2(ctx, &jb) if err != nil { - return errors.Wrap(err, "failed to add job") + return pkgerrors.Wrap(err, "failed to add job") } lggr.Info("dkg spec:", sp) @@ -490,18 +490,18 @@ func createOCR2VRFJob(ctx context.Context, lggr logger.Logger, app chainlink.App var jb job.Job err := toml.Unmarshal([]byte(sp), &jb) if err != nil { - return errors.Wrap(err, "failed to unmarshal job spec") + return pkgerrors.Wrap(err, "failed to unmarshal job spec") } var os job.OCR2OracleSpec err = toml.Unmarshal([]byte(sp), &os) if err != nil { - return errors.Wrap(err, "failed to unmarshal job spec") + return pkgerrors.Wrap(err, "failed to unmarshal job spec") } jb.OCR2OracleSpec = &os err = app.AddJobV2(ctx, &jb) if err != nil { - return errors.Wrap(err, "failed to add job") + return pkgerrors.Wrap(err, "failed to add job") } lggr.Info("ocr2vrf spec:", sp) diff --git a/core/cmd/ocr_keys_commands.go b/core/cmd/ocr_keys_commands.go index 399333bba93..33654d7e643 100644 --- a/core/cmd/ocr_keys_commands.go +++ b/core/cmd/ocr_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -158,7 +158,7 @@ func (s *Shell) CreateOCRKeyBundle(_ *cli.Context) error { // DeleteOCR2KeyBundle deletes an OCR key bundle func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id, err := models.Sha256HashFromHex(c.Args().Get(0)) if err != nil { @@ -191,16 +191,16 @@ func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { // ImportOCR2Key imports OCR key bundle func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -227,21 +227,21 @@ func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { // ExportOCR2Key exports an OCR key bundle by ID func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -249,7 +249,7 @@ func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -263,12 +263,12 @@ func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported OCR key bundle %s to %s", ID, filepath)) diff --git a/core/cmd/p2p_keys_commands.go b/core/cmd/p2p_keys_commands.go index da3bf412a04..07b46244c20 100644 --- a/core/cmd/p2p_keys_commands.go +++ b/core/cmd/p2p_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -157,7 +157,7 @@ func (s *Shell) CreateP2PKey(_ *cli.Context) (err error) { // key ID must be passed func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) } id := c.Args().Get(0) @@ -187,16 +187,16 @@ func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { // path to key must be passed func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -223,21 +223,21 @@ func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { // key ID must be passed func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -245,7 +245,7 @@ func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/p2p/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -259,12 +259,12 @@ func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported P2P key %s to %s\n", ID, filepath)) diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 5ca938b1b40..8c532b23590 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -24,7 +24,7 @@ import ( "github.com/Masterminds/semver/v3" "github.com/getsentry/sentry-go" "github.com/gin-gonic/gin" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" "go.uber.org/zap/zapcore" @@ -89,7 +89,7 @@ func initGlobals(cfgProm config.Prometheus, cfgTracing config.Tracing, logger lo var ( // ErrorNoAPICredentialsAvailable is returned when not run from a terminal // and no API credentials have been provided - ErrorNoAPICredentialsAvailable = errors.New("API credentials must be supplied") + ErrorNoAPICredentialsAvailable = pkgerrors.New("API credentials must be supplied") ) // Shell for the node, local commands and remote commands. @@ -129,7 +129,7 @@ func (s *Shell) configExitErr(validateFn func() error) cli.ExitCoder { if err != nil { fmt.Println("Invalid configuration:", err) fmt.Println() - return s.errorOut(errors.New("invalid configuration")) + return s.errorOut(pkgerrors.New("invalid configuration")) } return nil } @@ -263,7 +263,7 @@ func handleNodeVersioning(ctx context.Context, db *sqlx.DB, appLggr logger.Logge backupCfg := cfg.Backup() if backupCfg.Mode() != config.DatabaseBackupModeNone && backupCfg.OnVersionUpgrade() { if err = takeBackupIfVersionUpgrade(cfg.URL(), rootDir, cfg.Backup(), appLggr, appv, dbv, healthReportPort); err != nil { - if errors.Is(err, sql.ErrNoRows) { + if pkgerrors.Is(err, sql.ErrNoRows) { appLggr.Debugf("Failed to find any node version in the DB: %w", err) } else if strings.Contains(err.Error(), "relation \"node_versions\" does not exist") { appLggr.Debugf("Failed to find any node version in the DB, the node_versions table does not exist yet: %w", err) @@ -308,7 +308,7 @@ func takeBackupIfVersionUpgrade(dbUrl url.URL, rootDir string, cfg periodicbacku databaseBackup, err := periodicbackup.NewDatabaseBackup(dbUrl, rootDir, cfg, lggr) if err != nil { - return errors.Wrap(err, "takeBackupIfVersionUpgrade failed") + return pkgerrors.Wrap(err, "takeBackupIfVersionUpgrade failed") } //Because backups can take a long time we must start a "fake" health report to prevent @@ -343,17 +343,17 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err } if err := sentryInit(config.Sentry()); err != nil { - return errors.Wrap(err, "failed to initialize sentry") + return pkgerrors.Wrap(err, "failed to initialize sentry") } ws := config.WebServer() if ws.HTTPPort() == 0 && ws.TLS().HTTPSPort() == 0 { - return errors.New("You must specify at least one port to listen on") + return pkgerrors.New("You must specify at least one port to listen on") } handler, err := web.NewRouter(app, prometheus) if err != nil { - return errors.Wrap(err, "failed to create web router") + return pkgerrors.Wrap(err, "failed to create web router") } server := server{handler: handler, lggr: app.GetLogger()} @@ -381,15 +381,15 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err <-gCtx.Done() var err error if server.httpServer != nil { - err = errors.WithStack(server.httpServer.Shutdown(context.Background())) + err = pkgerrors.WithStack(server.httpServer.Shutdown(context.Background())) } if server.tlsServer != nil { - err = multierr.Combine(err, errors.WithStack(server.tlsServer.Shutdown(context.Background()))) + err = multierr.Combine(err, pkgerrors.WithStack(server.tlsServer.Shutdown(context.Background()))) } return err }) - return errors.WithStack(g.Wait()) + return pkgerrors.WithStack(g.Wait()) } func sentryInit(cfg config.Sentry) error { @@ -429,7 +429,7 @@ func tryRunServerUntilCancelled(ctx context.Context, lggr logger.Logger, timeout for { // try calling runServer() and log error if any if err := runServer(); err != nil { - if !errors.Is(err, http.ErrServerClosed) { + if !pkgerrors.Is(err, http.ErrServerClosed) { lggr.Criticalf("Error starting server: %v", err) } } @@ -455,7 +455,7 @@ func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error { s.lggr.Infow(fmt.Sprintf("Listening and serving HTTP on %s", addr), "ip", ip, "port", port) s.httpServer = createServer(s.handler, addr, writeTimeout) err := s.httpServer.ListenAndServe() - return errors.Wrap(err, "failed to run plaintext HTTP server") + return pkgerrors.Wrap(err, "failed to run plaintext HTTP server") } func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, requestTimeout time.Duration) error { @@ -463,7 +463,7 @@ func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, reques s.lggr.Infow(fmt.Sprintf("Listening and serving HTTPS on %s", addr), "ip", ip, "port", port) s.tlsServer = createServer(s.handler, addr, requestTimeout) err := s.tlsServer.ListenAndServeTLS(certFile, keyFile) - return errors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)") + return pkgerrors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)") } func createServer(handler *gin.Engine, addr string, requestTimeout time.Duration) *http.Server { @@ -646,7 +646,7 @@ func (t *SessionCookieAuthenticator) Authenticate(ctx context.Context, sessionRe cookies := resp.Cookies() if len(cookies) == 0 { - return nil, errors.New("did not receive cookie with session id") + return nil, pkgerrors.New("did not receive cookie with session id") } sc := web.FindSessionCookie(cookies) return sc, t.store.Save(sc) @@ -713,14 +713,14 @@ func (d DiskCookieStore) Retrieve() (*http.Cookie, error) { if os.IsNotExist(err) { return nil, nil } - return nil, multierr.Append(errors.New("unable to retrieve credentials, you must first login through the CLI"), err) + return nil, multierr.Append(pkgerrors.New("unable to retrieve credentials, you must first login through the CLI"), err) } header := http.Header{} header.Add("Cookie", string(b)) request := http.Request{Header: header} cookies := request.Cookies() if len(cookies) == 0 { - return nil, errors.New("Cookie not in file, you must first login through the CLI") + return nil, pkgerrors.New("Cookie not in file, you must first login through the CLI") } return request.Cookies()[0], nil } @@ -812,7 +812,7 @@ func (t *promptingAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lg // Load list of users to determine which to assume, or if a user needs to be created dbUsers, err := orm.ListUsers() if err != nil { - return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization") + return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization") } // If there are no users in the database, prompt for initial admin user creation @@ -871,14 +871,14 @@ func (f fileAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lggr log // Load list of users to determine which to assume, or if a user needs to be created dbUsers, err := orm.ListUsers() if err != nil { - return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization") + return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization") } // If there are no users in the database, create initial admin user from session request from file creds if len(dbUsers) == 0 { user, err2 := sessions.NewUser(request.Email, request.Password, sessions.UserRoleAdmin) if err2 != nil { - return user, errors.Wrap(err2, "failed to instantiate new user") + return user, pkgerrors.Wrap(err2, "failed to instantiate new user") } return user, orm.CreateUser(&user) } @@ -930,7 +930,7 @@ func attemptAssumeAdminUser(users []sessions.User, lggr logger.Logger) (sessions return sessions.User{}, false } -var ErrNoCredentialFile = errors.New("no API user credential file was passed") +var ErrNoCredentialFile = pkgerrors.New("no API user credential file was passed") func credentialsFromFile(file string, lggr logger.Logger) (sessions.SessionRequest, error) { if len(file) == 0 { @@ -979,7 +979,7 @@ func (c changePasswordPrompter) Prompt() (web.UpdatePasswordRequest, error) { confirmPassword := c.prompter.PasswordPrompt("Confirmation:") if newPassword != confirmPassword { - return web.UpdatePasswordRequest{}, errors.New("new password and confirmation did not match") + return web.UpdatePasswordRequest{}, pkgerrors.New("new password and confirmation did not match") } return web.UpdatePasswordRequest{ diff --git a/core/cmd/shell_local.go b/core/cmd/shell_local.go index b970b516413..e8193791d4e 100644 --- a/core/cmd/shell_local.go +++ b/core/cmd/shell_local.go @@ -25,7 +25,7 @@ import ( "github.com/lib/pq" "github.com/kylelemons/godebug/diff" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" "golang.org/x/sync/errgroup" @@ -54,7 +54,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/internal/testdb" ) -var ErrProfileTooLong = errors.New("requested profile duration too large") +var ErrProfileTooLong = pkgerrors.New("requested profile duration too large") func initLocalSubCmds(s *Shell, safe bool) []cli.Command { return []cli.Command{ @@ -274,14 +274,14 @@ func (s *Shell) runNode(c *cli.Context) error { if passwordFile := c.String("password"); passwordFile != "" { p, err := utils.PasswordFromFile(passwordFile) if err != nil { - return errors.Wrap(err, "error reading password from file") + return pkgerrors.Wrap(err, "error reading password from file") } pwd = &p } if vrfPasswordFile := c.String("vrfpassword"); len(vrfPasswordFile) != 0 { p, err := utils.PasswordFromFile(vrfPasswordFile) if err != nil { - return errors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) + return pkgerrors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) } vrfpwd = &p } @@ -291,7 +291,7 @@ func (s *Shell) runNode(c *cli.Context) error { s.Config.LogConfiguration(lggr.Debugf, lggr.Warnf) if err := s.Config.Validate(); err != nil { - return errors.Wrap(err, "config validation failed") + return pkgerrors.Wrap(err, "config validation failed") } lggr.Infow(fmt.Sprintf("Starting Chainlink Node %s at commit %s", static.Version, static.Sha), "Version", static.Version, "SHA", static.Sha) @@ -348,7 +348,7 @@ func (s *Shell) runNode(c *cli.Context) error { // Try opening DB connection and acquiring DB locks at once if err := ldb.Open(rootCtx); err != nil { // If not successful, we know neither locks nor connection remains opened - return s.errorOut(errors.Wrap(err, "opening db")) + return s.errorOut(pkgerrors.Wrap(err, "opening db")) } defer lggr.ErrorIfFn(ldb.Close, "Error closing db") @@ -357,7 +357,7 @@ func (s *Shell) runNode(c *cli.Context) error { app, err := s.AppFactory.NewApplication(rootCtx, s.Config, s.Logger, ldb.DB()) if err != nil { - return s.errorOut(errors.Wrap(err, "fatal error instantiating application")) + return s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) } // Local shell initialization always uses local auth users table for admin auth @@ -365,7 +365,7 @@ func (s *Shell) runNode(c *cli.Context) error { keyStore := app.GetKeyStore() err = s.KeyStoreAuthenticator.authenticate(keyStore, s.Config.Password()) if err != nil { - return errors.Wrap(err, "error authenticating keystore") + return pkgerrors.Wrap(err, "error authenticating keystore") } legacyEVMChains := app.GetRelayers().LegacyEVMChains() @@ -380,7 +380,7 @@ func (s *Shell) runNode(c *cli.Context) error { lggr.Debugf("AutoCreateKey=true, will ensure EVM key for chain %s", ch.ID()) err2 := app.GetKeyStore().Eth().EnsureKeys(ch.ID()) if err2 != nil { - return errors.Wrap(err2, "failed to ensure keystore keys") + return pkgerrors.Wrap(err2, "failed to ensure keystore keys") } } else { lggr.Debugf("AutoCreateKey=false, will not ensure EVM key for chain %s", ch.ID()) @@ -391,7 +391,7 @@ func (s *Shell) runNode(c *cli.Context) error { if s.Config.OCR().Enabled() { err2 := app.GetKeyStore().OCR().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure ocr key") + return pkgerrors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.OCR2().Enabled() { @@ -410,37 +410,37 @@ func (s *Shell) runNode(c *cli.Context) error { } err2 := app.GetKeyStore().OCR2().EnsureKeys(enabledChains...) if err2 != nil { - return errors.Wrap(err2, "failed to ensure ocr key") + return pkgerrors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.P2P().Enabled() { err2 := app.GetKeyStore().P2P().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure p2p key") + return pkgerrors.Wrap(err2, "failed to ensure p2p key") } } if s.Config.CosmosEnabled() { err2 := app.GetKeyStore().Cosmos().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure cosmos key") + return pkgerrors.Wrap(err2, "failed to ensure cosmos key") } } if s.Config.SolanaEnabled() { err2 := app.GetKeyStore().Solana().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure solana key") + return pkgerrors.Wrap(err2, "failed to ensure solana key") } } if s.Config.StarkNetEnabled() { err2 := app.GetKeyStore().StarkNet().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure starknet key") + return pkgerrors.Wrap(err2, "failed to ensure starknet key") } } err2 := app.GetKeyStore().CSA().EnsureKey() if err2 != nil { - return errors.Wrap(err2, "failed to ensure CSA key") + return pkgerrors.Wrap(err2, "failed to ensure CSA key") } if e := checkFilePermissions(lggr, s.Config.RootDir()); e != nil { @@ -449,14 +449,14 @@ func (s *Shell) runNode(c *cli.Context) error { var user sessions.User if user, err = NewFileAPIInitializer(c.String("api")).Initialize(authProviderORM, lggr); err != nil { - if !errors.Is(err, ErrNoCredentialFile) { - return errors.Wrap(err, "error creating api initializer") + if !pkgerrors.Is(err, ErrNoCredentialFile) { + return pkgerrors.Wrap(err, "error creating api initializer") } if user, err = s.FallbackAPIInitializer.Initialize(authProviderORM, lggr); err != nil { - if errors.Is(err, ErrorNoAPICredentialsAvailable) { - return errors.WithStack(err) + if pkgerrors.Is(err, ErrorNoAPICredentialsAvailable) { + return pkgerrors.WithStack(err) } - return errors.Wrap(err, "error creating fallback initializer") + return pkgerrors.Wrap(err, "error creating fallback initializer") } } @@ -466,7 +466,7 @@ func (s *Shell) runNode(c *cli.Context) error { // We do not try stopping any sub-services that might be started, // because the app will exit immediately upon return. // But LockedDB will be released by defer in above. - return errors.Wrap(err, "error starting app") + return pkgerrors.Wrap(err, "error starting app") } grp, grpCtx := errgroup.WithContext(rootCtx) @@ -474,7 +474,7 @@ func (s *Shell) runNode(c *cli.Context) error { grp.Go(func() error { <-grpCtx.Done() if errInternal := app.Stop(); errInternal != nil { - return errors.Wrap(errInternal, "error stopping app") + return pkgerrors.Wrap(errInternal, "error stopping app") } return nil }) @@ -483,7 +483,7 @@ func (s *Shell) runNode(c *cli.Context) error { grp.Go(func() error { errInternal := s.Runner.Run(grpCtx, app) - if errors.Is(errInternal, http.ErrServerClosed) { + if pkgerrors.Is(errInternal, http.ErrServerClosed) { errInternal = nil } // In tests we have custom runners that stop the app gracefully, @@ -566,7 +566,7 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { addressBytes, err := hexutil.Decode(addressHex) if err != nil { - return s.errorOut(errors.Wrap(err, "could not decode address")) + return s.errorOut(pkgerrors.Wrap(err, "could not decode address")) } address := gethCommon.BytesToAddress(addressBytes) @@ -575,20 +575,20 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { var ok bool chainID, ok = big.NewInt(0).SetString(chainIDStr, 10) if !ok { - return s.errorOut(errors.New("invalid evmChainID")) + return s.errorOut(pkgerrors.New("invalid evmChainID")) } } lggr := logger.Sugared(s.Logger.Named("RebroadcastTransactions")) db, err := pg.OpenUnlockedDB(s.Config.AppID(), s.Config.Database()) if err != nil { - return s.errorOut(errors.Wrap(err, "opening DB")) + return s.errorOut(pkgerrors.Wrap(err, "opening DB")) } defer lggr.ErrorIfFn(db.Close, "Error closing db") app, err := s.AppFactory.NewApplication(ctx, s.Config, lggr, db) if err != nil { - return s.errorOut(errors.Wrap(err, "fatal error instantiating application")) + return s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) } // TODO: BCF-2511 once the dust settles on BCF-2440/1 evaluate how the @@ -622,7 +622,7 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { err = keyStore.Unlock(s.Config.Password().Keystore()) if err != nil { - return s.errorOut(errors.Wrap(err, "error authenticating keystore")) + return s.errorOut(pkgerrors.Wrap(err, "error authenticating keystore")) } if err = keyStore.Eth().CheckEnabled(address, chain.ID()); err != nil { @@ -685,7 +685,7 @@ func (ps HealthCheckPresenters) RenderTable(rt RendererTable) error { return nil } -var errDBURLMissing = errors.New("You must set CL_DATABASE_URL env variable or provide a secrets TOML with Database.URL set. HINT: If you are running this to set up your local test database, try CL_DATABASE_URL=postgresql://postgres@localhost:5432/chainlink_test?sslmode=disable") +var errDBURLMissing = pkgerrors.New("You must set CL_DATABASE_URL env variable or provide a secrets TOML with Database.URL set. HINT: If you are running this to set up your local test database, try CL_DATABASE_URL=postgresql://postgres@localhost:5432/chainlink_test?sslmode=disable") // ConfigValidate validate the client configuration and pretty-prints results func (s *Shell) ConfigFileValidate(_ *cli.Context) error { @@ -911,7 +911,7 @@ func (s *Shell) RollbackDatabase(c *cli.Context) error { arg := c.Args().First() numVersion, err := strconv.ParseInt(arg, 10, 64) if err != nil { - return s.errorOut(errors.Errorf("Unable to parse %v as integer", arg)) + return s.errorOut(pkgerrors.Errorf("Unable to parse %v as integer", arg)) } version = null.IntFrom(numVersion) } @@ -962,7 +962,7 @@ func (s *Shell) StatusDatabase(_ *cli.Context) error { // CreateMigration displays the database migration status func (s *Shell) CreateMigration(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("You must specify a migration name")) + return s.errorOut(pkgerrors.New("You must specify a migration name")) } db, err := newConnection(s.Config.Database()) if err != nil { @@ -995,7 +995,7 @@ func (s *Shell) CleanupChainTables(c *cli.Context) error { db, err := newConnection(cfg) if err != nil { - return s.errorOut(errors.Wrap(err, "error connecting to the database")) + return s.errorOut(pkgerrors.Wrap(err, "error connecting to the database")) } defer db.Close() @@ -1032,7 +1032,7 @@ func (s *Shell) CleanupChainTables(c *cli.Context) error { } } } else { - return s.errorOut(errors.New("unknown chain type")) + return s.errorOut(pkgerrors.New("unknown chain type")) } return nil } @@ -1130,7 +1130,7 @@ func dumpSchema(dbURL url.URL) (string, error) { schema, err := cmd.Output() if err != nil { var ee *exec.ExitError - if errors.As(err, &ee) { + if pkgerrors.As(err, &ee) { return "", fmt.Errorf("failed to dump schema: %v\n%s", err, string(ee.Stderr)) } return "", fmt.Errorf("failed to dump schema: %v", err) @@ -1146,7 +1146,7 @@ func checkSchema(dbURL url.URL, prevSchema string) error { df := diff.Diff(prevSchema, newSchema) if len(df) > 0 { fmt.Println(df) - return errors.New("schema pre- and post- rollback does not match (ctrl+f for '+' or '-' to find the changed lines)") + return pkgerrors.New("schema pre- and post- rollback does not match (ctrl+f for '+' or '-' to find the changed lines)") } return nil } @@ -1164,7 +1164,7 @@ func insertFixtures(dbURL url.URL, pathToFixtures string) (err error) { _, filename, _, ok := runtime.Caller(1) if !ok { - return errors.New("could not get runtime.Caller(1)") + return pkgerrors.New("could not get runtime.Caller(1)") } filepath := path.Join(path.Dir(filename), pathToFixtures) fixturesSQL, err := os.ReadFile(filepath) diff --git a/core/cmd/shell_remote.go b/core/cmd/shell_remote.go index aab4a94da6f..53affdfd494 100644 --- a/core/cmd/shell_remote.go +++ b/core/cmd/shell_remote.go @@ -15,7 +15,7 @@ import ( "github.com/manyminds/api2go/jsonapi" "github.com/mitchellh/go-homedir" "github.com/pelletier/go-toml" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/tidwall/gjson" "github.com/urfave/cli" "go.uber.org/multierr" @@ -80,15 +80,15 @@ func initRemoteConfigSubCmds(s *Shell) []cli.Command { } var ( - errUnauthorized = errors.New(http.StatusText(http.StatusUnauthorized)) - errForbidden = errors.New(http.StatusText(http.StatusForbidden)) - errBadRequest = errors.New(http.StatusText(http.StatusBadRequest)) + errUnauthorized = pkgerrors.New(http.StatusText(http.StatusUnauthorized)) + errForbidden = pkgerrors.New(http.StatusText(http.StatusForbidden)) + errBadRequest = pkgerrors.New(http.StatusText(http.StatusBadRequest)) ) // CreateExternalInitiator adds an external initiator func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { if c.NArg() != 1 && c.NArg() != 2 { - return s.errorOut(errors.New("create expects 1 - 2 arguments: a name and a url (optional)")) + return s.errorOut(pkgerrors.New("create expects 1 - 2 arguments: a name and a url (optional)")) } var request bridges.ExternalInitiatorRequest @@ -128,7 +128,7 @@ func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { // DeleteExternalInitiator removes an external initiator func (s *Shell) DeleteExternalInitiator(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the name of the external initiator to delete")) + return s.errorOut(pkgerrors.New("Must pass the name of the external initiator to delete")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/external_initiators/"+c.Args().First()) @@ -270,11 +270,11 @@ func getTOMLString(s string) (string, error) { func (s *Shell) parseResponse(resp *http.Response) ([]byte, error) { b, err := parseResponse(resp) - if errors.Is(err, errUnauthorized) { + if pkgerrors.Is(err, errUnauthorized) { return nil, s.errorOut(multierr.Append(err, fmt.Errorf("your credentials may be missing, invalid or you may need to login first using the CLI via 'chainlink admin login'"))) } - if errors.Is(err, errForbidden) { + if pkgerrors.Is(err, errForbidden) { return nil, s.errorOut(multierr.Append(err, fmt.Errorf("this action requires %s privileges. The current user %s has '%s' role and cannot perform this action, login with a user that has '%s' role via 'chainlink admin login'", resp.Header.Get("forbidden-required-role"), resp.Header.Get("forbidden-provided-email"), resp.Header.Get("forbidden-provided-role"), resp.Header.Get("forbidden-required-role")))) } if err != nil { @@ -327,7 +327,7 @@ func (s *Shell) configV2Str(userOnly bool) (string, error) { return "", s.errorOut(err) } if resp.StatusCode != 200 { - return "", s.errorOut(errors.Errorf("got HTTP status %d: %s", resp.StatusCode, respPayload)) + return "", s.errorOut(pkgerrors.Errorf("got HTTP status %d: %s", resp.StatusCode, respPayload)) } var configV2Resource web.ConfigV2Resource err = web.ParseJSONAPIResponse(respPayload, &configV2Resource) @@ -370,7 +370,7 @@ func (s *Shell) SetLogLevel(c *cli.Context) (err error) { func (s *Shell) SetLogSQL(c *cli.Context) (err error) { // Enforces selection of --enable or --disable if !c.Bool("enable") && !c.Bool("disable") { - return s.errorOut(errors.New("Must set logSql --enabled || --disable")) + return s.errorOut(pkgerrors.New("Must set logSql --enabled || --disable")) } // Sets logSql to true || false based on the --enabled flag @@ -428,7 +428,7 @@ func fromFile(arg string) (*bytes.Buffer, error) { func (s *Shell) deserializeAPIResponse(resp *http.Response, dst interface{}, links *jsonapi.Links) error { b, err := s.parseResponse(resp) if err != nil { - return errors.Wrap(err, "parseResponse error") + return pkgerrors.Wrap(err, "parseResponse error") } if err = web.ParsePaginatedResponse(b, dst, links); err != nil { return s.errorOut(err) @@ -442,15 +442,15 @@ func parseErrorResponseBody(responseBody []byte) (string, error) { return "Empty error message", nil } - var errors models.JSONAPIErrors - err := json.Unmarshal(responseBody, &errors) - if err != nil || len(errors.Errors) == 0 { + var errs models.JSONAPIErrors + err := json.Unmarshal(responseBody, &errs) + if err != nil || len(errs.Errors) == 0 { return "", err } var errorDetails strings.Builder - errorDetails.WriteString(errors.Errors[0].Detail) - for _, errorDetail := range errors.Errors[1:] { + errorDetails.WriteString(errs.Errors[0].Detail) + for _, errorDetail := range errs.Errors[1:] { fmt.Fprintf(&errorDetails, "\n%s", errorDetail.Detail) } return errorDetails.String(), nil @@ -459,7 +459,7 @@ func parseErrorResponseBody(responseBody []byte) (string, error) { func parseResponse(resp *http.Response) ([]byte, error) { b, err := io.ReadAll(resp.Body) if err != nil { - return b, multierr.Append(errors.New(resp.Status), err) + return b, multierr.Append(pkgerrors.New(resp.Status), err) } if resp.StatusCode == http.StatusUnauthorized { return b, errUnauthorized @@ -470,7 +470,7 @@ func parseResponse(resp *http.Response) ([]byte, error) { if err2 != nil { return b, err2 } - return b, errors.New(errorMessage) + return b, pkgerrors.New(errorMessage) } return b, err } diff --git a/core/cmd/solana_transaction_commands.go b/core/cmd/solana_transaction_commands.go index 23e94eee50b..b060585d174 100644 --- a/core/cmd/solana_transaction_commands.go +++ b/core/cmd/solana_transaction_commands.go @@ -7,7 +7,7 @@ import ( "strconv" solanaGo "github.com/gagliardetto/solana-go" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -61,7 +61,7 @@ func (p *SolanaMsgPresenter) RenderTable(rt RendererTable) error { // SolanaSendSol transfers sol from the node's account to a specified address. func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { if c.NArg() < 3 { - return s.errorOut(errors.New("three arguments expected: amount, fromAddress and toAddress")) + return s.errorOut(pkgerrors.New("three arguments expected: amount, fromAddress and toAddress")) } amount, err := strconv.ParseUint(c.Args().Get(0), 10, 64) @@ -73,7 +73,7 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { fromAddress, err := solanaGo.PublicKeyFromBase58(unparsedFromAddress) if err != nil { return s.errorOut(multierr.Combine( - errors.Errorf("while parsing withdrawal source address %v", + pkgerrors.Errorf("while parsing withdrawal source address %v", unparsedFromAddress), err)) } @@ -81,13 +81,13 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { destinationAddress, err := solanaGo.PublicKeyFromBase58(unparsedDestinationAddress) if err != nil { return s.errorOut(multierr.Combine( - errors.Errorf("while parsing withdrawal destination address %v", + pkgerrors.Errorf("while parsing withdrawal destination address %v", unparsedDestinationAddress), err)) } chainID := c.String("id") if chainID == "" { - return s.errorOut(errors.New("missing id")) + return s.errorOut(pkgerrors.New("missing id")) } request := solana.SendRequest{ diff --git a/core/cmd/vrf_keys_commands.go b/core/cmd/vrf_keys_commands.go index 32d32334af5..db82ea08927 100644 --- a/core/cmd/vrf_keys_commands.go +++ b/core/cmd/vrf_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -135,16 +135,16 @@ func (s *Shell) CreateVRFKey(_ *cli.Context) error { // ImportVRFKey reads a file into an EncryptedVRFKey in the db func (s *Shell) ImportVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --old-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -172,21 +172,21 @@ func (s *Shell) ImportVRFKey(c *cli.Context) error { // requested file path. func (s *Shell) ExportVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the ID (compressed public key) of the key to export")) + return s.errorOut(pkgerrors.New("Must pass the ID (compressed public key) of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(errors.New("Must specify --new-password/-p flag")) + return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read password file")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(errors.New("Must specify --output/-o flag")) + return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) } pk, err := getPublicKey(c) @@ -197,7 +197,7 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/vrf/export/"+pk.String()+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -211,12 +211,12 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(errors.Wrap(err, "Could not read response body")) + return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported VRF key %s to %s\n", pk.String(), filepath)) @@ -232,7 +232,7 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { // (no such protection for the V1 jobs exists). func (s *Shell) DeleteVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(errors.New("Must pass the key ID (compressed public key) to be deleted")) + return s.errorOut(pkgerrors.New("Must pass the key ID (compressed public key) to be deleted")) } id, err := getPublicKey(c) if err != nil { @@ -269,7 +269,7 @@ func getPublicKey(c *cli.Context) (secp256k1.PublicKey, error) { } publicKey, err := secp256k1.NewPublicKeyFromHex(pkHexString) if err != nil { - return secp256k1.PublicKey{}, errors.Wrap(err, "failed to parse public key") + return secp256k1.PublicKey{}, pkgerrors.Wrap(err, "failed to parse public key") } return publicKey, nil } diff --git a/core/config/app_config.go b/core/config/app_config.go index 648939b871b..290e14dcc45 100644 --- a/core/config/app_config.go +++ b/core/config/app_config.go @@ -4,13 +4,13 @@ import ( "time" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/zap/zapcore" ) // nolint var ( - ErrEnvUnset = errors.New("env var unset") + ErrEnvUnset = pkgerrors.New("env var unset") ) type LogfFn func(string, ...any) diff --git a/core/config/docs/docs_test.go b/core/config/docs/docs_test.go index 508bd62e338..07ffb704fa5 100644 --- a/core/config/docs/docs_test.go +++ b/core/config/docs/docs_test.go @@ -6,7 +6,7 @@ import ( "github.com/kylelemons/godebug/diff" gotoml "github.com/pelletier/go-toml/v2" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -32,7 +32,7 @@ func TestDoc(t *testing.T) { var strict *gotoml.StrictMissingError if err != nil && strings.Contains(err.Error(), "undecoded keys: ") { t.Errorf("Docs contain extra fields: %v", err) - } else if errors.As(err, &strict) { + } else if pkgerrors.As(err, &strict) { t.Fatal("StrictMissingError:", strict.String()) } else { require.NoError(t, err) diff --git a/core/config/parse/parsers.go b/core/config/parse/parsers.go index 6243b74dd52..371354ba36e 100644 --- a/core/config/parse/parsers.go +++ b/core/config/parse/parsers.go @@ -10,7 +10,7 @@ import ( "time" "github.com/mitchellh/go-homedir" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/zap/zapcore" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" @@ -113,7 +113,7 @@ func HomeDir(str string) (string, error) { func DatabaseURL(s string) (url.URL, error) { uri, err := url.Parse(s) if err != nil { - return url.URL{}, errors.Wrapf(err, "invalid database url %s", s) + return url.URL{}, pkgerrors.Wrapf(err, "invalid database url %s", s) } if uri.String() == "" { return *uri, nil diff --git a/core/gethwrappers/versions.go b/core/gethwrappers/versions.go index acdefd06a59..43a59ddbb75 100644 --- a/core/gethwrappers/versions.go +++ b/core/gethwrappers/versions.go @@ -9,7 +9,7 @@ import ( "sort" "strings" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/multierr" ) @@ -44,11 +44,11 @@ func dbPath() (path string, err error) { func versionsDBLineReader() (*bufio.Scanner, error) { versionsDBPath, err := dbPath() if err != nil { - return nil, errors.Wrapf(err, "could not construct versions DB path") + return nil, pkgerrors.Wrapf(err, "could not construct versions DB path") } versionsDBFile, err := os.Open(versionsDBPath) if err != nil { - return nil, errors.Wrapf(err, "could not open versions database") + return nil, pkgerrors.Wrapf(err, "could not open versions database") } return bufio.NewScanner(versionsDBFile), nil @@ -66,28 +66,28 @@ func ReadVersionsDB() (*IntegratedVersion, error) { for db.Scan() { line := strings.Fields(db.Text()) if !strings.HasSuffix(line[0], ":") { - return nil, errors.Errorf( + return nil, pkgerrors.Errorf( `each line in versions.txt should start with "$TOPIC:"`) } topic := stripTrailingColon(line[0], "") if topic == "GETH_VERSION" { if len(line) != 2 { - return nil, errors.Errorf("GETH_VERSION line should contain geth "+ + return nil, pkgerrors.Errorf("GETH_VERSION line should contain geth "+ "version, and only that: %s", line) } if rv.GethVersion != "" { - return nil, errors.Errorf("more than one geth version") + return nil, pkgerrors.Errorf("more than one geth version") } rv.GethVersion = line[1] } else { // It's a wrapper from a compiler artifact if len(line) != 4 { - return nil, errors.Errorf(`"%s" should have four elements `+ + return nil, pkgerrors.Errorf(`"%s" should have four elements `+ `": "`, db.Text()) } _, alreadyExists := rv.ContractVersions[topic] if alreadyExists { - return nil, errors.Errorf(`topic "%s" already mentioned`, topic) + return nil, pkgerrors.Errorf(`topic "%s" already mentioned`, topic) } rv.ContractVersions[topic] = ContractVersion{ AbiPath: line[1], BinaryPath: line[2], Hash: line[3], @@ -102,11 +102,11 @@ var stripTrailingColon = regexp.MustCompile(":$").ReplaceAllString func WriteVersionsDB(db *IntegratedVersion) (err error) { versionsDBPath, err := dbPath() if err != nil { - return errors.Wrap(err, "could not construct path to versions DB") + return pkgerrors.Wrap(err, "could not construct path to versions DB") } f, err := os.Create(versionsDBPath) if err != nil { - return errors.Wrapf(err, "while opening %s", versionsDBPath) + return pkgerrors.Wrapf(err, "while opening %s", versionsDBPath) } defer func() { if cerr := f.Close(); cerr != nil { @@ -116,10 +116,10 @@ func WriteVersionsDB(db *IntegratedVersion) (err error) { gethLine := "GETH_VERSION: " + db.GethVersion + "\n" n, err := f.WriteString(gethLine) if err != nil { - return errors.Wrapf(err, "while recording geth version line") + return pkgerrors.Wrapf(err, "while recording geth version line") } if n != len(gethLine) { - return errors.Errorf("failed to write entire geth version line, %s", gethLine) + return pkgerrors.Errorf("failed to write entire geth version line, %s", gethLine) } var pkgNames []string for name := range db.ContractVersions { @@ -132,10 +132,10 @@ func WriteVersionsDB(db *IntegratedVersion) (err error) { vinfo.AbiPath, vinfo.BinaryPath, vinfo.Hash) n, err = f.WriteString(versionLine) if err != nil { - return errors.Wrapf(err, "while recording %s version line", name) + return pkgerrors.Wrapf(err, "while recording %s version line", name) } if n != len(versionLine) { - return errors.Errorf("failed to write entire version line %s", versionLine) + return pkgerrors.Errorf("failed to write entire version line %s", versionLine) } } return nil diff --git a/core/internal/testutils/httptest/httptest.go b/core/internal/testutils/httptest/httptest.go index 7607ca7552d..a1bd941fb02 100644 --- a/core/internal/testutils/httptest/httptest.go +++ b/core/internal/testutils/httptest/httptest.go @@ -6,7 +6,7 @@ import ( "net/http" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // NewTestHTTPClient returns a real HTTP client that may only make requests to @@ -31,7 +31,7 @@ func testDialContext(ctx context.Context, network, address string) (net.Conn, er } a := con.RemoteAddr().(*net.TCPAddr) if a != nil && !a.IP.IsLoopback() { - return nil, errors.Errorf("Test HTTP client may only dial localhost, got address: %v", a.String()) + return nil, pkgerrors.Errorf("Test HTTP client may only dial localhost, got address: %v", a.String()) } return con, err } diff --git a/core/internal/testutils/keystest/keystest.go b/core/internal/testutils/keystest/keystest.go index beb7e580f1b..850e1ad1fa0 100644 --- a/core/internal/testutils/keystest/keystest.go +++ b/core/internal/testutils/keystest/keystest.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/crypto" "github.com/google/uuid" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" ) // NewKey pulled from geth @@ -19,7 +19,7 @@ func NewKey() (key keystore.Key, err error) { id, err := uuid.NewRandom() if err != nil { - return key, errors.Errorf("Could not create random uuid: %v", err) + return key, pkgerrors.Errorf("Could not create random uuid: %v", err) } return keystore.Key{ diff --git a/core/logger/zap.go b/core/logger/zap.go index c739a80d45a..e11458bdf8b 100644 --- a/core/logger/zap.go +++ b/core/logger/zap.go @@ -3,7 +3,7 @@ package logger import ( "os" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) @@ -76,7 +76,7 @@ func (l *zapLogger) Sync() error { return nil } var msg string - if uw := errors.Unwrap(err); uw != nil { + if uw := pkgerrors.Unwrap(err); uw != nil { msg = uw.Error() } else { msg = err.Error() diff --git a/core/sessions/localauth/orm.go b/core/sessions/localauth/orm.go index 013f719ad34..8afaf5e7fc1 100644 --- a/core/sessions/localauth/orm.go +++ b/core/sessions/localauth/orm.go @@ -7,7 +7,7 @@ import ( "time" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" "github.com/smartcontractkit/chainlink/v2/core/auth" @@ -69,7 +69,7 @@ func (o *orm) ListUsers() (users []sessions.User, err error) { func (o *orm) findValidSession(sessionID string) (email string, err error) { if err := o.q.Get(&email, "SELECT email FROM sessions WHERE id = $1 AND last_used + $2 >= now() FOR UPDATE", sessionID, o.sessionDuration); err != nil { o.lggr.Infof("query result: %v", email) - return email, errors.Wrap(err, "no matching user for provided session token") + return email, pkgerrors.Wrap(err, "no matching user for provided session token") } return email, nil } @@ -152,12 +152,12 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { // for MFA tokens leaking if an account has MFA tokens or not. if !constantTimeEmailCompare(strings.ToLower(sr.Email), strings.ToLower(user.Email)) { o.auditLogger.Audit(audit.AuthLoginFailedEmail, map[string]interface{}{"email": sr.Email}) - return "", errors.New("Invalid email") + return "", pkgerrors.New("Invalid email") } if !utils.CheckPasswordHash(sr.Password, user.HashedPassword) { o.auditLogger.Audit(audit.AuthLoginFailedPassword, map[string]interface{}{"email": sr.Email}) - return "", errors.New("Invalid password") + return "", pkgerrors.New("Invalid password") } // Load all valid MFA tokens associated with user's email @@ -165,7 +165,7 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { if err != nil { // There was an error with the database query lggr.Errorf("Could not fetch user's MFA data: %v", err) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } // No webauthn tokens registered for the current user, so normal authentication is now complete @@ -185,16 +185,16 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { options, webauthnError := sessions.BeginWebAuthnLogin(user, uwas, sr) if webauthnError != nil { lggr.Errorf("Could not begin WebAuthn verification: %v", webauthnError) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } j, jsonError := json.Marshal(options) if jsonError != nil { lggr.Errorf("Could not serialize WebAuthn challenge: %v", jsonError) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } - return "", errors.New(string(j)) + return "", pkgerrors.New(string(j)) } // The user is at the final stage of logging in with MFA. We have an @@ -206,7 +206,7 @@ func (o *orm) CreateSession(sr sessions.SessionRequest) (string, error) { // The user does have WebAuthn enabled but failed the check o.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]interface{}{"email": sr.Email, "error": err}) lggr.Errorf("User sent an invalid attestation: %v", err) - return "", errors.New("MFA Error") + return "", pkgerrors.New("MFA Error") } lggr.Infof("User passed MFA authentication and login will proceed") @@ -256,13 +256,13 @@ func (o *orm) UpdateRole(email, newRole string) (sessions.User, error) { var userToEdit sessions.User if newRole == "" { - return userToEdit, errors.New("user role must be specified") + return userToEdit, pkgerrors.New("user role must be specified") } err := o.q.Transaction(func(tx pg.Queryer) error { // First, attempt to load specified user by email if err := tx.Get(&userToEdit, "SELECT * FROM users WHERE lower(email) = lower($1)", email); err != nil { - return errors.New("no matching user for provided email") + return pkgerrors.New("no matching user for provided email") } // Patch validated role @@ -275,13 +275,13 @@ func (o *orm) UpdateRole(email, newRole string) (sessions.User, error) { _, err = tx.Exec("DELETE FROM sessions WHERE email = lower($1)", email) if err != nil { o.lggr.Errorf("Failed to purge user sessions for UpdateRole", "err", err) - return errors.New("error updating API user") + return pkgerrors.New("error updating API user") } sql := "UPDATE users SET role = $1, updated_at = now() WHERE lower(email) = lower($2) RETURNING *" if err := tx.Get(&userToEdit, sql, userToEdit.Role, email); err != nil { o.lggr.Errorf("Error updating API user", "err", err) - return errors.New("error updating API user") + return pkgerrors.New("error updating API user") } return nil @@ -304,10 +304,10 @@ func (o *orm) SetPassword(user *sessions.User, newPassword string) error { func (o *orm) TestPassword(email string, password string) error { var hashedPassword string if err := o.q.Get(&hashedPassword, "SELECT hashed_password FROM users WHERE lower(email) = lower($1)", email); err != nil { - return errors.New("no matching user for provided email") + return pkgerrors.New("no matching user for provided email") } if !utils.CheckPasswordHash(password, hashedPassword) { - return errors.New("passwords don't match") + return pkgerrors.New("passwords don't match") } return nil } @@ -328,7 +328,7 @@ func (o *orm) SetAuthToken(user *sessions.User, token *auth.Token) error { salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(token, salt) if err != nil { - return errors.Wrap(err, "user") + return pkgerrors.Wrap(err, "user") } sql := "UPDATE users SET token_salt = $1, token_key = $2, token_hashed_secret = $3, updated_at = now() WHERE email = $4 RETURNING *" return o.q.Get(user, sql, salt, token.AccessKey, hashedSecret, user.Email) diff --git a/core/sessions/session.go b/core/sessions/session.go index 90964596e9a..49f403b6a81 100644 --- a/core/sessions/session.go +++ b/core/sessions/session.go @@ -4,7 +4,7 @@ import ( "crypto/subtle" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink/v2/core/auth" @@ -55,7 +55,7 @@ func (u *User) SetAuthToken(token *auth.Token) error { salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(token, salt) if err != nil { - return errors.Wrap(err, "user") + return pkgerrors.Wrap(err, "user") } u.TokenSalt = null.StringFrom(salt) u.TokenKey = null.StringFrom(token.AccessKey) diff --git a/core/sessions/user.go b/core/sessions/user.go index f2e4827b922..bcedaa4b197 100644 --- a/core/sessions/user.go +++ b/core/sessions/user.go @@ -5,7 +5,7 @@ import ( "net/mail" "time" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -58,7 +58,7 @@ func NewUser(email string, plainPwd string, role UserRole) (User, error) { // ValidateEmail is the single point of logic for user email validations func ValidateEmail(email string) error { if len(email) == 0 { - return errors.New("Must enter an email") + return pkgerrors.New("Must enter an email") } _, err := mail.ParseAddress(email) return err @@ -67,10 +67,10 @@ func ValidateEmail(email string) error { // ValidateAndHashPassword is the single point of logic for user password validations func ValidateAndHashPassword(plainPwd string) (string, error) { if err := utils.VerifyPasswordComplexity(plainPwd); err != nil { - return "", errors.Wrapf(err, "password insufficiently complex:\n%s", utils.PasswordComplexityRequirements) + return "", pkgerrors.Wrapf(err, "password insufficiently complex:\n%s", utils.PasswordComplexityRequirements) } if len(plainPwd) > MaxBcryptPasswordLength { - return "", errors.Errorf("must enter a password less than %v characters", MaxBcryptPasswordLength) + return "", pkgerrors.Errorf("must enter a password less than %v characters", MaxBcryptPasswordLength) } pwd, err := utils.HashPassword(plainPwd) @@ -104,5 +104,5 @@ func GetUserRole(role string) (UserRole, error) { UserRoleRun, UserRoleView, ) - return UserRole(""), errors.New(errStr) + return UserRole(""), pkgerrors.New(errStr) } diff --git a/core/sessions/webauthn.go b/core/sessions/webauthn.go index 89e7758bc5b..264dc596826 100644 --- a/core/sessions/webauthn.go +++ b/core/sessions/webauthn.go @@ -7,10 +7,10 @@ import ( "strings" "sync" + "cosmossdk.io/errors" "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" sqlxTypes "github.com/jmoiron/sqlx/types" - "github.com/pkg/errors" ) // WebAuthn holds the credentials for API user. diff --git a/core/store/migrate/migrate.go b/core/store/migrate/migrate.go index 04da4c48e92..aff3229e92a 100644 --- a/core/store/migrate/migrate.go +++ b/core/store/migrate/migrate.go @@ -10,7 +10,7 @@ import ( "strings" "github.com/jmoiron/sqlx" - "github.com/pkg/errors" + pkgerrors "github.com/pkg/errors" "github.com/pressly/goose/v3" "gopkg.in/guregu/null.v4" @@ -62,7 +62,7 @@ func ensureMigrated(ctx context.Context, db *sql.DB, lggr logger.Logger) error { } } if !found { - return errors.New("database state is too old. Need to migrate to chainlink version 0.9.10 first before upgrading to this version. This upgrade is NOT REVERSIBLE, so it is STRONGLY RECOMMENDED that you take a database backup before continuing") + return pkgerrors.New("database state is too old. Need to migrate to chainlink version 0.9.10 first before upgrading to this version. This upgrade is NOT REVERSIBLE, so it is STRONGLY RECOMMENDED that you take a database backup before continuing") } // ensure a goose migrations table exists with it's initial v0 @@ -88,7 +88,7 @@ func ensureMigrated(ctx context.Context, db *sql.DB, lggr logger.Logger) error { id, err = strconv.ParseInt(name[:idx], 10, 64) if err == nil && id <= 0 { - return errors.New("migration IDs must be greater than zero") + return pkgerrors.New("migration IDs must be greater than zero") } } @@ -144,7 +144,7 @@ func SetMigrationENVVars(generalConfig chainlink.GeneralConfig) error { if generalConfig.EVMEnabled() { err := os.Setenv(env.EVMChainIDNotNullMigration0195, generalConfig.EVMConfigs()[0].ChainID.String()) if err != nil { - panic(errors.Wrap(err, "failed to set migrations env variables")) + panic(pkgerrors.Wrap(err, "failed to set migrations env variables")) } } return nil From cc7212beaeeee5a21a31351518d2567e4fcb7beb Mon Sep 17 00:00:00 2001 From: James Walker Date: Tue, 23 Jan 2024 10:45:56 -0500 Subject: [PATCH 06/11] cleanup --- core/sessions/webauthn.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/sessions/webauthn.go b/core/sessions/webauthn.go index 264dc596826..c959bec08de 100644 --- a/core/sessions/webauthn.go +++ b/core/sessions/webauthn.go @@ -7,10 +7,10 @@ import ( "strings" "sync" - "cosmossdk.io/errors" "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" sqlxTypes "github.com/jmoiron/sqlx/types" + pkgerrors "github.com/pkg/errors" ) // WebAuthn holds the credentials for API user. @@ -93,7 +93,7 @@ func (store *WebAuthnSessionStore) FinishWebAuthnRegistration(user User, uwas [] credential, err := webAuthn.FinishRegistration(waUser, sessionData, response) if err != nil { - return nil, errors.Wrap(err, "failed to FinishRegistration") + return nil, pkgerrors.Wrap(err, "failed to FinishRegistration") } return credential, nil @@ -137,7 +137,7 @@ func FinishWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) error { }) if err != nil { - return errors.Wrapf(err, "failed to create webAuthn structure with RPID: %s and RPOrigin: %s", sr.WebAuthnConfig.RPID, sr.WebAuthnConfig.RPOrigin) + return pkgerrors.Wrapf(err, "failed to create webAuthn structure with RPID: %s and RPOrigin: %s", sr.WebAuthnConfig.RPID, sr.WebAuthnConfig.RPOrigin) } credential, err := protocol.ParseCredentialRequestResponseBody(strings.NewReader(sr.WebAuthnData)) @@ -272,7 +272,7 @@ func (store *WebAuthnSessionStore) take(key string) (val string, ok bool) { func (store *WebAuthnSessionStore) GetWebauthnSession(key string) (data webauthn.SessionData, err error) { assertion, ok := store.take(key) if !ok { - err = errors.New("assertion not in challenge store") + err = pkgerrors.New("assertion not in challenge store") return } err = json.Unmarshal([]byte(assertion), &data) From 3f04f048cbeed936ed72eea4977348e6849a146e Mon Sep 17 00:00:00 2001 From: James Walker Date: Tue, 23 Jan 2024 13:35:25 -0500 Subject: [PATCH 07/11] fix linting issues --- core/auth/auth.go | 1 + core/bridges/external_initiator.go | 1 + 2 files changed, 2 insertions(+) diff --git a/core/auth/auth.go b/core/auth/auth.go index d6e6a107df9..62f1ab528a2 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -5,6 +5,7 @@ import ( "fmt" pkgerrors "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/utils" "golang.org/x/crypto/sha3" diff --git a/core/bridges/external_initiator.go b/core/bridges/external_initiator.go index bfab811f337..bfec3adb407 100644 --- a/core/bridges/external_initiator.go +++ b/core/bridges/external_initiator.go @@ -6,6 +6,7 @@ import ( "time" pkgerrors "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/store/models" "github.com/smartcontractkit/chainlink/v2/core/utils" From f28df81a4921eac396af8fd15471f89cd33032db Mon Sep 17 00:00:00 2001 From: James Walker Date: Fri, 26 Jan 2024 11:45:59 -0500 Subject: [PATCH 08/11] fix merge bugs --- core/chains/evm/gas/suggested_price_estimator.go | 4 ++-- core/chains/evm/gas/suggested_price_estimator_test.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/chains/evm/gas/suggested_price_estimator.go b/core/chains/evm/gas/suggested_price_estimator.go index 20465d30223..d58a1155b91 100644 --- a/core/chains/evm/gas/suggested_price_estimator.go +++ b/core/chains/evm/gas/suggested_price_estimator.go @@ -138,14 +138,14 @@ func (o *SuggestedPriceEstimator) forceRefresh(ctx context.Context) (err error) select { case o.chForceRefetch <- ch: case <-o.chStop: - return errors.New("estimator stopped") + return pkgerrors.New("estimator stopped") case <-ctx.Done(): return ctx.Err() } select { case <-ch: case <-o.chStop: - return errors.New("estimator stopped") + return pkgerrors.New("estimator stopped") case <-ctx.Done(): return ctx.Err() } diff --git a/core/chains/evm/gas/suggested_price_estimator_test.go b/core/chains/evm/gas/suggested_price_estimator_test.go index b2095570067..c09582774b8 100644 --- a/core/chains/evm/gas/suggested_price_estimator_test.go +++ b/core/chains/evm/gas/suggested_price_estimator_test.go @@ -203,7 +203,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { client := mocks.NewRPCClient(t) o := gas.NewSuggestedPriceEstimator(logger.Test(t), client, cfg) - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) servicetest.RunHealthy(t, o) @@ -219,7 +219,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { res := args.Get(1).(*hexutil.Big) (*big.Int)(res).SetInt64(40) }).Once() - client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) + client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(pkgerrors.New("kaboom")) servicetest.RunHealthy(t, o) From 88e223666d5a9236f67e7d0c55ef03e9000db171 Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 26 Feb 2024 22:20:21 -0500 Subject: [PATCH 09/11] revert all changes to the core/cmd dir --- core/cmd/app.go | 8 +- core/cmd/blocks_commands.go | 4 +- core/cmd/cosmos_node_commands_test.go | 2 +- core/cmd/csa_keys_commands.go | 22 ++-- core/cmd/eth_keys_commands.go | 34 +++---- core/cmd/eth_keys_commands_test.go | 24 ++--- core/cmd/evm_node_commands_test.go | 4 +- core/cmd/forwarders_commands.go | 8 +- core/cmd/jobs_commands.go | 10 +- core/cmd/key_store_authenticator.go | 6 +- core/cmd/keys_commands.go | 24 ++--- core/cmd/ocr2_keys_commands.go | 26 ++--- core/cmd/ocr2_keys_commands_test.go | 2 +- core/cmd/ocr2vrf_configure_commands.go | 60 +++++------ core/cmd/ocr_keys_commands.go | 24 ++--- core/cmd/p2p_keys_commands.go | 24 ++--- core/cmd/shell.go | 44 ++++---- core/cmd/shell_local.go | 129 ++++++++++++------------ core/cmd/shell_local_test.go | 5 +- core/cmd/shell_remote.go | 36 +++---- core/cmd/solana_node_commands_test.go | 4 +- core/cmd/solana_transaction_commands.go | 10 +- core/cmd/starknet_node_commands_test.go | 4 +- core/cmd/vrf_keys_commands.go | 26 ++--- 24 files changed, 269 insertions(+), 271 deletions(-) diff --git a/core/cmd/app.go b/core/cmd/app.go index f87d0a863fb..8e61380156c 100644 --- a/core/cmd/app.go +++ b/core/cmd/app.go @@ -7,7 +7,7 @@ import ( "path/filepath" "regexp" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "github.com/smartcontractkit/chainlink/v2/core/build" @@ -98,7 +98,7 @@ func NewApp(s *Shell) *cli.App { urlStr := c.String("remote-node-url") remoteNodeURL, err := url.Parse(urlStr) if err != nil { - return pkgerrors.Wrapf(err, "%s is not a valid URL", urlStr) + return errors.Wrapf(err, "%s is not a valid URL", urlStr) } insecureSkipVerify := c.Bool("insecure-skip-verify") @@ -108,8 +108,8 @@ func NewApp(s *Shell) *cli.App { credentialsFile := c.String("admin-credentials-file") sr, err := sessionRequestBuilder.Build(credentialsFile) - if err != nil && !pkgerrors.Is(pkgerrors.Cause(err), ErrNoCredentialFile) && !os.IsNotExist(err) { - return pkgerrors.Wrapf(err, "failed to load API credentials from file %s", credentialsFile) + if err != nil && !errors.Is(errors.Cause(err), ErrNoCredentialFile) && !os.IsNotExist(err) { + return errors.Wrapf(err, "failed to load API credentials from file %s", credentialsFile) } s.HTTP = NewAuthenticatedHTTPClient(s.Logger, clientOpts, cookieAuth, sr) diff --git a/core/cmd/blocks_commands.go b/core/cmd/blocks_commands.go index 8570826c8b6..72b0523e18d 100644 --- a/core/cmd/blocks_commands.go +++ b/core/cmd/blocks_commands.go @@ -6,7 +6,7 @@ import ( "net/url" "strconv" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" ) @@ -41,7 +41,7 @@ func initBlocksSubCmds(s *Shell) []cli.Command { func (s *Shell) ReplayFromBlock(c *cli.Context) (err error) { blockNumber := c.Int64("block-number") if blockNumber <= 0 { - return s.errorOut(pkgerrors.New("Must pass a positive value in '--block-number' parameter")) + return s.errorOut(errors.New("Must pass a positive value in '--block-number' parameter")) } v := url.Values{} diff --git a/core/cmd/cosmos_node_commands_test.go b/core/cmd/cosmos_node_commands_test.go index 728be9396f9..3197c48aa94 100644 --- a/core/cmd/cosmos_node_commands_test.go +++ b/core/cmd/cosmos_node_commands_test.go @@ -48,8 +48,8 @@ func TestShell_IndexCosmosNodes(t *testing.T) { nodes := *r.Renders[0].(*cmd.CosmosNodePresenters) require.Len(t, nodes, 1) n := nodes[0] + assert.Equal(t, cltest.FormatWithPrefixedChainID(chainID, *node.Name), n.ID) assert.Equal(t, chainID, n.ChainID) - assert.Equal(t, *node.Name, n.ID) assert.Equal(t, *node.Name, n.Name) wantConfig, err := toml.Marshal(node) require.NoError(t, err) diff --git a/core/cmd/csa_keys_commands.go b/core/cmd/csa_keys_commands.go index 35e7b25d29d..1c0fe54ab09 100644 --- a/core/cmd/csa_keys_commands.go +++ b/core/cmd/csa_keys_commands.go @@ -8,7 +8,7 @@ import ( "net/url" "os" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -139,16 +139,16 @@ func (s *Shell) CreateCSAKey(_ *cli.Context) (err error) { // ImportCSAKey imports and stores a CSA key. Path to key must be passed. func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return s.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -181,22 +181,22 @@ func (s *Shell) ImportCSAKey(c *cli.Context) (err error) { // ExportCSAKey exports a CSA key. Key ID must be passed. func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) + return s.errorOut(errors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return s.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return s.errorOut(errors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -210,7 +210,7 @@ func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { exportUrl.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), exportUrl.String(), nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -224,12 +224,12 @@ func (s *Shell) ExportCSAKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return s.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported P2P key %s to %s\n", ID, filepath)) diff --git a/core/cmd/eth_keys_commands.go b/core/cmd/eth_keys_commands.go index 52243000ff1..5adac3b382b 100644 --- a/core/cmd/eth_keys_commands.go +++ b/core/cmd/eth_keys_commands.go @@ -10,7 +10,7 @@ import ( "os" "strings" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -223,7 +223,7 @@ func (s *Shell) CreateETHKey(c *cli.Context) (err error) { // address of key must be passed func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the address of the key to be deleted")) + return s.errorOut(errors.New("Must pass the address of the key to be deleted")) } address := c.Args().Get(0) @@ -244,14 +244,14 @@ func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Failed to read request response")) + return s.errorOut(errors.Wrap(err, "Failed to read request response")) } var result *models.JSONAPIErrors err = json.Unmarshal(body, &result) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Unable to unmarshal json from body '%s'", string(body))) + return s.errorOut(errors.Wrapf(err, "Unable to unmarshal json from body '%s'", string(body))) } - return s.errorOut(pkgerrors.Errorf("Delete ETH key failed: %s", result.Error())) + return s.errorOut(errors.Errorf("Delete ETH key failed: %s", result.Error())) } return s.renderAPIResponse(resp, &EthKeyPresenter{}, fmt.Sprintf("🔑 Deleted ETH key: %s\n", address)) } @@ -260,16 +260,16 @@ func (s *Shell) DeleteETHKey(c *cli.Context) (err error) { // file path must be passed func (s *Shell) ImportETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return s.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -307,21 +307,21 @@ func (s *Shell) ImportETHKey(c *cli.Context) (err error) { // address must be passed func (s *Shell) ExportETHKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the address of the key to export")) + return s.errorOut(errors.New("Must pass the address of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return s.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(newPassword) == 0 { - return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return s.errorOut(errors.New("Must specify --output/-o flag")) } address := c.Args().Get(0) @@ -334,7 +334,7 @@ func (s *Shell) ExportETHKey(c *cli.Context) (err error) { exportUrl.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), exportUrl.String(), nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -348,12 +348,12 @@ func (s *Shell) ExportETHKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return s.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString("🔑 Exported ETH key " + address + " to " + filepath + "\n") @@ -377,7 +377,7 @@ func (s *Shell) UpdateChainEVMKey(c *cli.Context) (err error) { query.Set("abandon", abandon) if c.IsSet("enable") && c.IsSet("disable") { - return s.errorOut(pkgerrors.New("cannot set both --enable and --disable simultaneously")) + return s.errorOut(errors.New("cannot set both --enable and --disable simultaneously")) } else if c.Bool("enable") { query.Set("enabled", "true") } else if c.Bool("disable") { @@ -387,7 +387,7 @@ func (s *Shell) UpdateChainEVMKey(c *cli.Context) (err error) { chainURL.RawQuery = query.Encode() resp, err := s.HTTP.Post(s.ctx(), chainURL.String(), nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { diff --git a/core/cmd/eth_keys_commands_test.go b/core/cmd/eth_keys_commands_test.go index 88b1e194208..2f22cd1d3ae 100644 --- a/core/cmd/eth_keys_commands_test.go +++ b/core/cmd/eth_keys_commands_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" commonassets "github.com/smartcontractkit/chainlink-common/pkg/assets" "github.com/smartcontractkit/chainlink-common/pkg/utils" @@ -116,8 +116,8 @@ func TestShell_ListETHKeys_Error(t *testing.T) { t.Parallel() ethClient := newEthMock(t) - ethClient.On("BalanceAt", mock.Anything, mock.Anything, mock.Anything).Return(nil, pkgerrors.New("fake error")) - ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(nil, pkgerrors.New("fake error")) + ethClient.On("BalanceAt", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("fake error")) + ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("fake error")) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].Enabled = ptr(true) @@ -148,7 +148,7 @@ func TestShell_ListETHKeys_Disabled(t *testing.T) { withMocks(ethClient), ) client, r := app.NewShellAndRenderer() - keys, err := app.KeyStore.Eth().GetAll() + keys, err := app.KeyStore.Eth().GetAll(testutils.Context(t)) require.NoError(t, err) require.Equal(t, 1, len(keys)) k := keys[0] @@ -186,7 +186,7 @@ func TestShell_CreateETHKey(t *testing.T) { client, _ := app.NewShellAndRenderer() cltest.AssertCount(t, db, "evm.key_states", 1) // The initial funding key - keys, err := app.KeyStore.Eth().GetAll() + keys, err := app.KeyStore.Eth().GetAll(testutils.Context(t)) require.NoError(t, err) require.Equal(t, 1, len(keys)) @@ -202,7 +202,7 @@ func TestShell_CreateETHKey(t *testing.T) { assert.NoError(t, client.CreateETHKey(c)) cltest.AssertCount(t, db, "evm.key_states", 2) - keys, err = app.KeyStore.Eth().GetAll() + keys, err = app.KeyStore.Eth().GetAll(testutils.Context(t)) require.NoError(t, err) require.Equal(t, 2, len(keys)) } @@ -221,7 +221,7 @@ func TestShell_DeleteETHKey(t *testing.T) { client, _ := app.NewShellAndRenderer() // Create the key - key, err := ethKeyStore.Create(&cltest.FixtureChainID) + key, err := ethKeyStore.Create(testutils.Context(t), &cltest.FixtureChainID) require.NoError(t, err) // Delete the key @@ -235,7 +235,7 @@ func TestShell_DeleteETHKey(t *testing.T) { err = client.DeleteETHKey(c) require.NoError(t, err) - _, err = ethKeyStore.Get(key.Address.Hex()) + _, err = ethKeyStore.Get(testutils.Context(t), key.Address.Hex()) assert.Error(t, err) } @@ -303,7 +303,7 @@ func TestShell_ImportExportETHKey_NoChains(t *testing.T) { c = cli.NewContext(nil, set, nil) err = client.DeleteETHKey(c) require.NoError(t, err) - _, err = ethKeyStore.Get(address) + _, err = ethKeyStore.Get(testutils.Context(t), address) require.Error(t, err) cltest.AssertCount(t, app.GetSqlxDB(), "evm.key_states", 0) @@ -328,7 +328,7 @@ func TestShell_ImportExportETHKey_NoChains(t *testing.T) { err = client.ListETHKeys(c) require.NoError(t, err) require.Len(t, *r.Renders[0].(*cmd.EthKeyPresenters), 1) - _, err = ethKeyStore.Get(address) + _, err = ethKeyStore.Get(testutils.Context(t), address) require.NoError(t, err) // Export test invalid id @@ -411,7 +411,7 @@ func TestShell_ImportExportETHKey_WithChains(t *testing.T) { c = cli.NewContext(nil, set, nil) err = client.DeleteETHKey(c) require.NoError(t, err) - _, err = ethKeyStore.Get(address) + _, err = ethKeyStore.Get(testutils.Context(t), address) require.Error(t, err) // Import the key @@ -435,7 +435,7 @@ func TestShell_ImportExportETHKey_WithChains(t *testing.T) { err = client.ListETHKeys(c) require.NoError(t, err) require.Len(t, *r.Renders[0].(*cmd.EthKeyPresenters), 1) - _, err = ethKeyStore.Get(address) + _, err = ethKeyStore.Get(testutils.Context(t), address) require.NoError(t, err) // Export test invalid id diff --git a/core/cmd/evm_node_commands_test.go b/core/cmd/evm_node_commands_test.go index dae950fce01..96269c9e028 100644 --- a/core/cmd/evm_node_commands_test.go +++ b/core/cmd/evm_node_commands_test.go @@ -60,13 +60,13 @@ func TestShell_IndexEVMNodes(t *testing.T) { n1 := nodes[0] n2 := nodes[1] assert.Equal(t, chainID.String(), n1.ChainID) - assert.Equal(t, *node1.Name, n1.ID) + assert.Equal(t, cltest.FormatWithPrefixedChainID(chainID.String(), *node1.Name), n1.ID) assert.Equal(t, *node1.Name, n1.Name) wantConfig, err := toml.Marshal(node1) require.NoError(t, err) assert.Equal(t, string(wantConfig), n1.Config) assert.Equal(t, chainID.String(), n2.ChainID) - assert.Equal(t, *node2.Name, n2.ID) + assert.Equal(t, cltest.FormatWithPrefixedChainID(chainID.String(), *node2.Name), n2.ID) assert.Equal(t, *node2.Name, n2.Name) wantConfig2, err := toml.Marshal(node2) require.NoError(t, err) diff --git a/core/cmd/forwarders_commands.go b/core/cmd/forwarders_commands.go index f6d40de7b25..2445be5bfec 100644 --- a/core/cmd/forwarders_commands.go +++ b/core/cmd/forwarders_commands.go @@ -10,7 +10,7 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -100,7 +100,7 @@ func (s *Shell) ListForwarders(c *cli.Context) (err error) { // DeleteForwarder deletes forwarder address from node db by id. func (s *Shell) DeleteForwarder(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("must pass the forwarder id to be archived")) + return s.errorOut(errors.New("must pass the forwarder id to be archived")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/nodes/evm/forwarders/"+c.Args().First()) if err != nil { @@ -122,7 +122,7 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { addressBytes, err := hexutil.Decode(addressHex) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "could not decode address")) + return s.errorOut(errors.Wrap(err, "could not decode address")) } address := gethCommon.BytesToAddress(addressBytes) @@ -131,7 +131,7 @@ func (s *Shell) TrackForwarder(c *cli.Context) (err error) { var ok bool chainID, ok = big.NewInt(0).SetString(chainIDStr, 10) if !ok { - return s.errorOut(pkgerrors.Wrap(err, "invalid evm-chain-id")) + return s.errorOut(errors.Wrap(err, "invalid evm-chain-id")) } } diff --git a/core/cmd/jobs_commands.go b/core/cmd/jobs_commands.go index f46f5c11e9b..1f9ca33c78e 100644 --- a/core/cmd/jobs_commands.go +++ b/core/cmd/jobs_commands.go @@ -8,7 +8,7 @@ import ( "strings" "time" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -209,7 +209,7 @@ func (s *Shell) ListJobs(c *cli.Context) (err error) { // ShowJob displays the details of a job func (s *Shell) ShowJob(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("must provide the id of the job")) + return s.errorOut(errors.New("must provide the id of the job")) } id := c.Args().First() resp, err := s.HTTP.Get(s.ctx(), "/v2/jobs/"+id) @@ -229,7 +229,7 @@ func (s *Shell) ShowJob(c *cli.Context) (err error) { // Valid input is a TOML string or a path to TOML file func (s *Shell) CreateJob(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("must pass in TOML or filepath")) + return s.errorOut(errors.New("must pass in TOML or filepath")) } tomlString, err := getTOMLString(c.Args().First()) @@ -271,7 +271,7 @@ func (s *Shell) CreateJob(c *cli.Context) (err error) { // DeleteJob deletes a job func (s *Shell) DeleteJob(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("must pass the job id to be archived")) + return s.errorOut(errors.New("must pass the job id to be archived")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/jobs/"+c.Args().First()) if err != nil { @@ -289,7 +289,7 @@ func (s *Shell) DeleteJob(c *cli.Context) error { // TriggerPipelineRun triggers a job run based on a job ID func (s *Shell) TriggerPipelineRun(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the job id to trigger a run")) + return s.errorOut(errors.New("Must pass the job id to trigger a run")) } resp, err := s.HTTP.Post(s.ctx(), "/v2/jobs/"+c.Args().First()+"/runs", nil) if err != nil { diff --git a/core/cmd/key_store_authenticator.go b/core/cmd/key_store_authenticator.go index 4a0b429b5cd..0707aa5087d 100644 --- a/core/cmd/key_store_authenticator.go +++ b/core/cmd/key_store_authenticator.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -23,7 +23,7 @@ type keystorePassword interface { func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, password keystorePassword) error { isEmpty, err := keyStore.IsEmpty() if err != nil { - return pkgerrors.Wrap(err, "error determining if keystore is empty") + return errors.Wrap(err, "error determining if keystore is empty") } pw := password.Keystore() @@ -38,7 +38,7 @@ func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, } interactive := auth.Prompter.IsTerminal() if !interactive { - return pkgerrors.New("no password provided") + return errors.New("no password provided") } else if !isEmpty { pw = auth.promptExistingPassword() } else { diff --git a/core/cmd/keys_commands.go b/core/cmd/keys_commands.go index 8d6c964b310..7408d168887 100644 --- a/core/cmd/keys_commands.go +++ b/core/cmd/keys_commands.go @@ -8,7 +8,7 @@ import ( "os" "strings" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -139,7 +139,7 @@ func (cli *keysClient[K, P, P2]) CreateKey(_ *cli.Context) (err error) { // key ID must be passed func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) + return cli.errorOut(errors.New("Must pass the key ID to be deleted")) } id := c.Args().Get(0) @@ -170,16 +170,16 @@ func (cli *keysClient[K, P, P2]) DeleteKey(c *cli.Context) (err error) { // path to key must be passed func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return cli.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return cli.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return cli.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return cli.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return cli.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -207,21 +207,21 @@ func (cli *keysClient[K, P, P2]) ImportKey(c *cli.Context) (err error) { // key ID must be passed func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { if !c.Args().Present() { - return cli.errorOut(pkgerrors.New("Must pass the ID of the key to export")) + return cli.errorOut(errors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return cli.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return cli.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return cli.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return cli.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return cli.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return cli.errorOut(errors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -229,7 +229,7 @@ func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := cli.HTTP.Post(cli.ctx(), cli.path+"/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return cli.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return cli.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -243,12 +243,12 @@ func (cli *keysClient[K, P, P2]) ExportKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return cli.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return cli.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0600) if err != nil { - return cli.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return cli.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported %s key %s to %s\n", cli.typ, ID, filepath)) diff --git a/core/cmd/ocr2_keys_commands.go b/core/cmd/ocr2_keys_commands.go index ee5f821294c..1d469024878 100644 --- a/core/cmd/ocr2_keys_commands.go +++ b/core/cmd/ocr2_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -145,7 +145,7 @@ func (s *Shell) ListOCR2KeyBundles(_ *cli.Context) error { func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { if !c.Args().Present() { return s.errorOut( - pkgerrors.Errorf(`must pass the type to create, options are: %s`, chaintype.SupportedChainTypes.String()), + errors.Errorf(`must pass the type to create, options are: %s`, chaintype.SupportedChainTypes.String()), ) } chainType := c.Args().Get(0) @@ -166,7 +166,7 @@ func (s *Shell) CreateOCR2KeyBundle(c *cli.Context) error { // DeleteOCR2KeyBundle deletes an OCR2 key bundle func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) + return s.errorOut(errors.New("Must pass the key ID to be deleted")) } id, err := models.Sha256HashFromHex(c.Args().Get(0)) if err != nil { @@ -199,16 +199,16 @@ func (s *Shell) DeleteOCR2KeyBundle(c *cli.Context) error { // ImportOCR2Key imports OCR2 key bundle func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return s.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -235,21 +235,21 @@ func (s *Shell) ImportOCR2Key(c *cli.Context) (err error) { // ExportOCR2Key exports an OCR2 key bundle by ID func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) + return s.errorOut(errors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return s.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return s.errorOut(errors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -257,7 +257,7 @@ func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr2/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -271,12 +271,12 @@ func (s *Shell) ExportOCR2Key(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return s.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported OCR key bundle %s to %s", ID, filepath)) diff --git a/core/cmd/ocr2_keys_commands_test.go b/core/cmd/ocr2_keys_commands_test.go index 5a861fafa7c..eff44685612 100644 --- a/core/cmd/ocr2_keys_commands_test.go +++ b/core/cmd/ocr2_keys_commands_test.go @@ -32,7 +32,7 @@ func TestOCR2KeyBundlePresenter_RenderTable(t *testing.T) { pubKeyConfig := key.ConfigEncryptionPublicKey() pubKey := key.OffchainPublicKey() p := cmd.OCR2KeyBundlePresenter{ - JAID: cmd.JAID{ID: bundleID}, + JAID: cmd.NewJAID(bundleID), OCR2KeysBundleResource: presenters.OCR2KeysBundleResource{ JAID: presenters.NewJAID(key.ID()), ChainType: "evm", diff --git a/core/cmd/ocr2vrf_configure_commands.go b/core/cmd/ocr2vrf_configure_commands.go index cde341c4c48..906c27374c8 100644 --- a/core/cmd/ocr2vrf_configure_commands.go +++ b/core/cmd/ocr2vrf_configure_commands.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/pelletier/go-toml" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "github.com/jmoiron/sqlx" @@ -137,14 +137,14 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e if passwordFile := c.String("password"); passwordFile != "" { p, err := utils.PasswordFromFile(passwordFile) if err != nil { - return nil, pkgerrors.Wrap(err, "error reading password from file") + return nil, errors.Wrap(err, "error reading password from file") } pwd = &p } if vrfPasswordFile := c.String("vrfpassword"); len(vrfPasswordFile) != 0 { p, err := utils.PasswordFromFile(vrfPasswordFile) if err != nil { - return nil, pkgerrors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) + return nil, errors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) } vrfpwd = &p } @@ -153,27 +153,27 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e err := s.Config.Validate() if err != nil { - return nil, s.errorOut(pkgerrors.Wrap(err, "config validation failed")) + return nil, s.errorOut(errors.Wrap(err, "config validation failed")) } cfg := s.Config ldb := pg.NewLockedDB(cfg.AppID(), cfg.Database(), cfg.Database().Lock(), lggr) if err = ldb.Open(ctx); err != nil { - return nil, s.errorOut(pkgerrors.Wrap(err, "opening db")) + return nil, s.errorOut(errors.Wrap(err, "opening db")) } defer lggr.ErrorIfFn(ldb.Close, "Error closing db") app, err := s.AppFactory.NewApplication(ctx, s.Config, lggr, ldb.DB()) if err != nil { - return nil, s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) + return nil, s.errorOut(errors.Wrap(err, "fatal error instantiating application")) } chainID := c.Int64("chainID") // Initialize keystore and generate keys. keyStore := app.GetKeyStore() - err = setupKeystore(s, app, keyStore) + err = setupKeystore(ctx, s, app, keyStore) if err != nil { return nil, s.errorOut(err) } @@ -191,7 +191,7 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e var sendingKeys []string var sendingKeysAddresses []common.Address useForwarder := c.Bool("use-forwarder") - ethKeys, err := app.GetKeyStore().Eth().EnabledKeysForChain(big.NewInt(chainID)) + ethKeys, err := app.GetKeyStore().Eth().EnabledKeysForChain(ctx, big.NewInt(chainID)) if err != nil { return nil, s.errorOut(err) } @@ -205,7 +205,7 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e if useForwarder { // Add extra sending keys if using a forwarder. - sendingKeys, sendingKeysAddresses, err = s.appendForwarders(chainID, app.GetKeyStore().Eth(), sendingKeys, sendingKeysAddresses) + sendingKeys, sendingKeysAddresses, err = s.appendForwarders(ctx, chainID, app.GetKeyStore().Eth(), sendingKeys, sendingKeysAddresses) if err != nil { return nil, err } @@ -236,7 +236,7 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e } } if ocr2 == nil { - return nil, s.errorOut(pkgerrors.Wrap(job.ErrNoSuchKeyBundle, "evm OCR2 key bundle not found")) + return nil, s.errorOut(errors.Wrap(job.ErrNoSuchKeyBundle, "evm OCR2 key bundle not found")) } offChainPublicKey := ocr2.OffchainPublicKey() configPublicKey := ocr2.ConfigEncryptionPublicKey() @@ -298,16 +298,16 @@ func (s *Shell) ConfigureOCR2VRFNode(c *cli.Context, owner *bind.TransactOpts, e }, nil } -func (s *Shell) appendForwarders(chainID int64, ks keystore.Eth, sendingKeys []string, sendingKeysAddresses []common.Address) ([]string, []common.Address, error) { +func (s *Shell) appendForwarders(ctx context.Context, chainID int64, ks keystore.Eth, sendingKeys []string, sendingKeysAddresses []common.Address) ([]string, []common.Address, error) { for i := 0; i < forwarderAdditionalEOACount; i++ { // Create the sending key in the keystore. - k, err := ks.Create() + k, err := ks.Create(ctx) if err != nil { return nil, nil, err } // Enable the sending key for the current chain. - err = ks.Enable(k.Address, big.NewInt(chainID)) + err = ks.Enable(ctx, k.Address, big.NewInt(chainID)) if err != nil { return nil, nil, err } @@ -351,9 +351,9 @@ func (s *Shell) authorizeForwarder(c *cli.Context, db *sqlx.DB, lggr logger.Logg return nil } -func setupKeystore(cli *Shell, app chainlink.Application, keyStore keystore.Master) error { +func setupKeystore(ctx context.Context, cli *Shell, app chainlink.Application, keyStore keystore.Master) error { if err := cli.KeyStoreAuthenticator.authenticate(keyStore, cli.Config.Password()); err != nil { - return pkgerrors.Wrap(err, "error authenticating keystore") + return errors.Wrap(err, "error authenticating keystore") } if cli.Config.EVMEnabled() { @@ -362,8 +362,8 @@ func setupKeystore(cli *Shell, app chainlink.Application, keyStore keystore.Mast return fmt.Errorf("failed to get legacy evm chains") } for _, ch := range chains { - if err = keyStore.Eth().EnsureKeys(ch.ID()); err != nil { - return pkgerrors.Wrap(err, "failed to ensure keystore keys") + if err = keyStore.Eth().EnsureKeys(ctx, ch.ID()); err != nil { + return errors.Wrap(err, "failed to ensure keystore keys") } } } @@ -383,19 +383,19 @@ func setupKeystore(cli *Shell, app chainlink.Application, keyStore keystore.Mast } if err := keyStore.OCR2().EnsureKeys(enabledChains...); err != nil { - return pkgerrors.Wrap(err, "failed to ensure ocr key") + return errors.Wrap(err, "failed to ensure ocr key") } if err := keyStore.DKGSign().EnsureKey(); err != nil { - return pkgerrors.Wrap(err, "failed to ensure dkgsign key") + return errors.Wrap(err, "failed to ensure dkgsign key") } if err := keyStore.DKGEncrypt().EnsureKey(); err != nil { - return pkgerrors.Wrap(err, "failed to ensure dkgencrypt key") + return errors.Wrap(err, "failed to ensure dkgencrypt key") } if err := keyStore.P2P().EnsureKey(); err != nil { - return pkgerrors.Wrap(err, "failed to ensure p2p key") + return errors.Wrap(err, "failed to ensure p2p key") } return nil @@ -410,18 +410,18 @@ func createBootstrapperJob(ctx context.Context, lggr logger.Logger, c *cli.Conte var jb job.Job err := toml.Unmarshal([]byte(sp), &jb) if err != nil { - return pkgerrors.Wrap(err, "failed to unmarshal job spec") + return errors.Wrap(err, "failed to unmarshal job spec") } var os job.BootstrapSpec err = toml.Unmarshal([]byte(sp), &os) if err != nil { - return pkgerrors.Wrap(err, "failed to unmarshal job spec") + return errors.Wrap(err, "failed to unmarshal job spec") } jb.BootstrapSpec = &os err = app.AddJobV2(ctx, &jb) if err != nil { - return pkgerrors.Wrap(err, "failed to add job") + return errors.Wrap(err, "failed to add job") } lggr.Info("bootstrap spec:", sp) @@ -447,18 +447,18 @@ func createDKGJob(ctx context.Context, lggr logger.Logger, app chainlink.Applica var jb job.Job err := toml.Unmarshal([]byte(sp), &jb) if err != nil { - return pkgerrors.Wrap(err, "failed to unmarshal job spec") + return errors.Wrap(err, "failed to unmarshal job spec") } var os job.OCR2OracleSpec err = toml.Unmarshal([]byte(sp), &os) if err != nil { - return pkgerrors.Wrap(err, "failed to unmarshal job spec") + return errors.Wrap(err, "failed to unmarshal job spec") } jb.OCR2OracleSpec = &os err = app.AddJobV2(ctx, &jb) if err != nil { - return pkgerrors.Wrap(err, "failed to add job") + return errors.Wrap(err, "failed to add job") } lggr.Info("dkg spec:", sp) @@ -490,18 +490,18 @@ func createOCR2VRFJob(ctx context.Context, lggr logger.Logger, app chainlink.App var jb job.Job err := toml.Unmarshal([]byte(sp), &jb) if err != nil { - return pkgerrors.Wrap(err, "failed to unmarshal job spec") + return errors.Wrap(err, "failed to unmarshal job spec") } var os job.OCR2OracleSpec err = toml.Unmarshal([]byte(sp), &os) if err != nil { - return pkgerrors.Wrap(err, "failed to unmarshal job spec") + return errors.Wrap(err, "failed to unmarshal job spec") } jb.OCR2OracleSpec = &os err = app.AddJobV2(ctx, &jb) if err != nil { - return pkgerrors.Wrap(err, "failed to add job") + return errors.Wrap(err, "failed to add job") } lggr.Info("ocr2vrf spec:", sp) diff --git a/core/cmd/ocr_keys_commands.go b/core/cmd/ocr_keys_commands.go index 33654d7e643..399333bba93 100644 --- a/core/cmd/ocr_keys_commands.go +++ b/core/cmd/ocr_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -158,7 +158,7 @@ func (s *Shell) CreateOCRKeyBundle(_ *cli.Context) error { // DeleteOCR2KeyBundle deletes an OCR key bundle func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) + return s.errorOut(errors.New("Must pass the key ID to be deleted")) } id, err := models.Sha256HashFromHex(c.Args().Get(0)) if err != nil { @@ -191,16 +191,16 @@ func (s *Shell) DeleteOCRKeyBundle(c *cli.Context) error { // ImportOCR2Key imports OCR key bundle func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return s.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -227,21 +227,21 @@ func (s *Shell) ImportOCRKey(c *cli.Context) (err error) { // ExportOCR2Key exports an OCR key bundle by ID func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) + return s.errorOut(errors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return s.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return s.errorOut(errors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -249,7 +249,7 @@ func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/ocr/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -263,12 +263,12 @@ func (s *Shell) ExportOCRKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return s.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported OCR key bundle %s to %s", ID, filepath)) diff --git a/core/cmd/p2p_keys_commands.go b/core/cmd/p2p_keys_commands.go index 07b46244c20..da3bf412a04 100644 --- a/core/cmd/p2p_keys_commands.go +++ b/core/cmd/p2p_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -157,7 +157,7 @@ func (s *Shell) CreateP2PKey(_ *cli.Context) (err error) { // key ID must be passed func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the key ID to be deleted")) + return s.errorOut(errors.New("Must pass the key ID to be deleted")) } id := c.Args().Get(0) @@ -187,16 +187,16 @@ func (s *Shell) DeleteP2PKey(c *cli.Context) (err error) { // path to key must be passed func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return s.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -223,21 +223,21 @@ func (s *Shell) ImportP2PKey(c *cli.Context) (err error) { // key ID must be passed func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the ID of the key to export")) + return s.errorOut(errors.New("Must pass the ID of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return s.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return s.errorOut(errors.New("Must specify --output/-o flag")) } ID := c.Args().Get(0) @@ -245,7 +245,7 @@ func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/p2p/export/"+ID+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -259,12 +259,12 @@ func (s *Shell) ExportP2PKey(c *cli.Context) (err error) { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return s.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("🔑 Exported P2P key %s to %s\n", ID, filepath)) diff --git a/core/cmd/shell.go b/core/cmd/shell.go index 8c532b23590..5ca938b1b40 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -24,7 +24,7 @@ import ( "github.com/Masterminds/semver/v3" "github.com/getsentry/sentry-go" "github.com/gin-gonic/gin" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" "go.uber.org/zap/zapcore" @@ -89,7 +89,7 @@ func initGlobals(cfgProm config.Prometheus, cfgTracing config.Tracing, logger lo var ( // ErrorNoAPICredentialsAvailable is returned when not run from a terminal // and no API credentials have been provided - ErrorNoAPICredentialsAvailable = pkgerrors.New("API credentials must be supplied") + ErrorNoAPICredentialsAvailable = errors.New("API credentials must be supplied") ) // Shell for the node, local commands and remote commands. @@ -129,7 +129,7 @@ func (s *Shell) configExitErr(validateFn func() error) cli.ExitCoder { if err != nil { fmt.Println("Invalid configuration:", err) fmt.Println() - return s.errorOut(pkgerrors.New("invalid configuration")) + return s.errorOut(errors.New("invalid configuration")) } return nil } @@ -263,7 +263,7 @@ func handleNodeVersioning(ctx context.Context, db *sqlx.DB, appLggr logger.Logge backupCfg := cfg.Backup() if backupCfg.Mode() != config.DatabaseBackupModeNone && backupCfg.OnVersionUpgrade() { if err = takeBackupIfVersionUpgrade(cfg.URL(), rootDir, cfg.Backup(), appLggr, appv, dbv, healthReportPort); err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { appLggr.Debugf("Failed to find any node version in the DB: %w", err) } else if strings.Contains(err.Error(), "relation \"node_versions\" does not exist") { appLggr.Debugf("Failed to find any node version in the DB, the node_versions table does not exist yet: %w", err) @@ -308,7 +308,7 @@ func takeBackupIfVersionUpgrade(dbUrl url.URL, rootDir string, cfg periodicbacku databaseBackup, err := periodicbackup.NewDatabaseBackup(dbUrl, rootDir, cfg, lggr) if err != nil { - return pkgerrors.Wrap(err, "takeBackupIfVersionUpgrade failed") + return errors.Wrap(err, "takeBackupIfVersionUpgrade failed") } //Because backups can take a long time we must start a "fake" health report to prevent @@ -343,17 +343,17 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err } if err := sentryInit(config.Sentry()); err != nil { - return pkgerrors.Wrap(err, "failed to initialize sentry") + return errors.Wrap(err, "failed to initialize sentry") } ws := config.WebServer() if ws.HTTPPort() == 0 && ws.TLS().HTTPSPort() == 0 { - return pkgerrors.New("You must specify at least one port to listen on") + return errors.New("You must specify at least one port to listen on") } handler, err := web.NewRouter(app, prometheus) if err != nil { - return pkgerrors.Wrap(err, "failed to create web router") + return errors.Wrap(err, "failed to create web router") } server := server{handler: handler, lggr: app.GetLogger()} @@ -381,15 +381,15 @@ func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) err <-gCtx.Done() var err error if server.httpServer != nil { - err = pkgerrors.WithStack(server.httpServer.Shutdown(context.Background())) + err = errors.WithStack(server.httpServer.Shutdown(context.Background())) } if server.tlsServer != nil { - err = multierr.Combine(err, pkgerrors.WithStack(server.tlsServer.Shutdown(context.Background()))) + err = multierr.Combine(err, errors.WithStack(server.tlsServer.Shutdown(context.Background()))) } return err }) - return pkgerrors.WithStack(g.Wait()) + return errors.WithStack(g.Wait()) } func sentryInit(cfg config.Sentry) error { @@ -429,7 +429,7 @@ func tryRunServerUntilCancelled(ctx context.Context, lggr logger.Logger, timeout for { // try calling runServer() and log error if any if err := runServer(); err != nil { - if !pkgerrors.Is(err, http.ErrServerClosed) { + if !errors.Is(err, http.ErrServerClosed) { lggr.Criticalf("Error starting server: %v", err) } } @@ -455,7 +455,7 @@ func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error { s.lggr.Infow(fmt.Sprintf("Listening and serving HTTP on %s", addr), "ip", ip, "port", port) s.httpServer = createServer(s.handler, addr, writeTimeout) err := s.httpServer.ListenAndServe() - return pkgerrors.Wrap(err, "failed to run plaintext HTTP server") + return errors.Wrap(err, "failed to run plaintext HTTP server") } func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, requestTimeout time.Duration) error { @@ -463,7 +463,7 @@ func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, reques s.lggr.Infow(fmt.Sprintf("Listening and serving HTTPS on %s", addr), "ip", ip, "port", port) s.tlsServer = createServer(s.handler, addr, requestTimeout) err := s.tlsServer.ListenAndServeTLS(certFile, keyFile) - return pkgerrors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)") + return errors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)") } func createServer(handler *gin.Engine, addr string, requestTimeout time.Duration) *http.Server { @@ -646,7 +646,7 @@ func (t *SessionCookieAuthenticator) Authenticate(ctx context.Context, sessionRe cookies := resp.Cookies() if len(cookies) == 0 { - return nil, pkgerrors.New("did not receive cookie with session id") + return nil, errors.New("did not receive cookie with session id") } sc := web.FindSessionCookie(cookies) return sc, t.store.Save(sc) @@ -713,14 +713,14 @@ func (d DiskCookieStore) Retrieve() (*http.Cookie, error) { if os.IsNotExist(err) { return nil, nil } - return nil, multierr.Append(pkgerrors.New("unable to retrieve credentials, you must first login through the CLI"), err) + return nil, multierr.Append(errors.New("unable to retrieve credentials, you must first login through the CLI"), err) } header := http.Header{} header.Add("Cookie", string(b)) request := http.Request{Header: header} cookies := request.Cookies() if len(cookies) == 0 { - return nil, pkgerrors.New("Cookie not in file, you must first login through the CLI") + return nil, errors.New("Cookie not in file, you must first login through the CLI") } return request.Cookies()[0], nil } @@ -812,7 +812,7 @@ func (t *promptingAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lg // Load list of users to determine which to assume, or if a user needs to be created dbUsers, err := orm.ListUsers() if err != nil { - return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization") + return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization") } // If there are no users in the database, prompt for initial admin user creation @@ -871,14 +871,14 @@ func (f fileAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lggr log // Load list of users to determine which to assume, or if a user needs to be created dbUsers, err := orm.ListUsers() if err != nil { - return sessions.User{}, pkgerrors.Wrap(err, "Unable to List users for initialization") + return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization") } // If there are no users in the database, create initial admin user from session request from file creds if len(dbUsers) == 0 { user, err2 := sessions.NewUser(request.Email, request.Password, sessions.UserRoleAdmin) if err2 != nil { - return user, pkgerrors.Wrap(err2, "failed to instantiate new user") + return user, errors.Wrap(err2, "failed to instantiate new user") } return user, orm.CreateUser(&user) } @@ -930,7 +930,7 @@ func attemptAssumeAdminUser(users []sessions.User, lggr logger.Logger) (sessions return sessions.User{}, false } -var ErrNoCredentialFile = pkgerrors.New("no API user credential file was passed") +var ErrNoCredentialFile = errors.New("no API user credential file was passed") func credentialsFromFile(file string, lggr logger.Logger) (sessions.SessionRequest, error) { if len(file) == 0 { @@ -979,7 +979,7 @@ func (c changePasswordPrompter) Prompt() (web.UpdatePasswordRequest, error) { confirmPassword := c.prompter.PasswordPrompt("Confirmation:") if newPassword != confirmPassword { - return web.UpdatePasswordRequest{}, pkgerrors.New("new password and confirmation did not match") + return web.UpdatePasswordRequest{}, errors.New("new password and confirmation did not match") } return web.UpdatePasswordRequest{ diff --git a/core/cmd/shell_local.go b/core/cmd/shell_local.go index e8193791d4e..7e03fe719e1 100644 --- a/core/cmd/shell_local.go +++ b/core/cmd/shell_local.go @@ -25,7 +25,7 @@ import ( "github.com/lib/pq" "github.com/kylelemons/godebug/diff" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" "golang.org/x/sync/errgroup" @@ -54,7 +54,7 @@ import ( "github.com/smartcontractkit/chainlink/v2/internal/testdb" ) -var ErrProfileTooLong = pkgerrors.New("requested profile duration too large") +var ErrProfileTooLong = errors.New("requested profile duration too large") func initLocalSubCmds(s *Shell, safe bool) []cli.Command { return []cli.Command{ @@ -274,14 +274,14 @@ func (s *Shell) runNode(c *cli.Context) error { if passwordFile := c.String("password"); passwordFile != "" { p, err := utils.PasswordFromFile(passwordFile) if err != nil { - return pkgerrors.Wrap(err, "error reading password from file") + return errors.Wrap(err, "error reading password from file") } pwd = &p } if vrfPasswordFile := c.String("vrfpassword"); len(vrfPasswordFile) != 0 { p, err := utils.PasswordFromFile(vrfPasswordFile) if err != nil { - return pkgerrors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) + return errors.Wrapf(err, "error reading VRF password from vrfpassword file \"%s\"", vrfPasswordFile) } vrfpwd = &p } @@ -291,7 +291,7 @@ func (s *Shell) runNode(c *cli.Context) error { s.Config.LogConfiguration(lggr.Debugf, lggr.Warnf) if err := s.Config.Validate(); err != nil { - return pkgerrors.Wrap(err, "config validation failed") + return errors.Wrap(err, "config validation failed") } lggr.Infow(fmt.Sprintf("Starting Chainlink Node %s at commit %s", static.Version, static.Sha), "Version", static.Version, "SHA", static.Sha) @@ -348,7 +348,7 @@ func (s *Shell) runNode(c *cli.Context) error { // Try opening DB connection and acquiring DB locks at once if err := ldb.Open(rootCtx); err != nil { // If not successful, we know neither locks nor connection remains opened - return s.errorOut(pkgerrors.Wrap(err, "opening db")) + return s.errorOut(errors.Wrap(err, "opening db")) } defer lggr.ErrorIfFn(ldb.Close, "Error closing db") @@ -357,7 +357,7 @@ func (s *Shell) runNode(c *cli.Context) error { app, err := s.AppFactory.NewApplication(rootCtx, s.Config, s.Logger, ldb.DB()) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) + return s.errorOut(errors.Wrap(err, "fatal error instantiating application")) } // Local shell initialization always uses local auth users table for admin auth @@ -365,7 +365,7 @@ func (s *Shell) runNode(c *cli.Context) error { keyStore := app.GetKeyStore() err = s.KeyStoreAuthenticator.authenticate(keyStore, s.Config.Password()) if err != nil { - return pkgerrors.Wrap(err, "error authenticating keystore") + return errors.Wrap(err, "error authenticating keystore") } legacyEVMChains := app.GetRelayers().LegacyEVMChains() @@ -378,9 +378,9 @@ func (s *Shell) runNode(c *cli.Context) error { for _, ch := range chainList { if ch.Config().EVM().AutoCreateKey() { lggr.Debugf("AutoCreateKey=true, will ensure EVM key for chain %s", ch.ID()) - err2 := app.GetKeyStore().Eth().EnsureKeys(ch.ID()) + err2 := app.GetKeyStore().Eth().EnsureKeys(rootCtx, ch.ID()) if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure keystore keys") + return errors.Wrap(err2, "failed to ensure keystore keys") } } else { lggr.Debugf("AutoCreateKey=false, will not ensure EVM key for chain %s", ch.ID()) @@ -391,7 +391,7 @@ func (s *Shell) runNode(c *cli.Context) error { if s.Config.OCR().Enabled() { err2 := app.GetKeyStore().OCR().EnsureKey() if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure ocr key") + return errors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.OCR2().Enabled() { @@ -410,37 +410,37 @@ func (s *Shell) runNode(c *cli.Context) error { } err2 := app.GetKeyStore().OCR2().EnsureKeys(enabledChains...) if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure ocr key") + return errors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.P2P().Enabled() { err2 := app.GetKeyStore().P2P().EnsureKey() if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure p2p key") + return errors.Wrap(err2, "failed to ensure p2p key") } } if s.Config.CosmosEnabled() { err2 := app.GetKeyStore().Cosmos().EnsureKey() if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure cosmos key") + return errors.Wrap(err2, "failed to ensure cosmos key") } } if s.Config.SolanaEnabled() { err2 := app.GetKeyStore().Solana().EnsureKey() if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure solana key") + return errors.Wrap(err2, "failed to ensure solana key") } } if s.Config.StarkNetEnabled() { err2 := app.GetKeyStore().StarkNet().EnsureKey() if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure starknet key") + return errors.Wrap(err2, "failed to ensure starknet key") } } err2 := app.GetKeyStore().CSA().EnsureKey() if err2 != nil { - return pkgerrors.Wrap(err2, "failed to ensure CSA key") + return errors.Wrap(err2, "failed to ensure CSA key") } if e := checkFilePermissions(lggr, s.Config.RootDir()); e != nil { @@ -449,14 +449,14 @@ func (s *Shell) runNode(c *cli.Context) error { var user sessions.User if user, err = NewFileAPIInitializer(c.String("api")).Initialize(authProviderORM, lggr); err != nil { - if !pkgerrors.Is(err, ErrNoCredentialFile) { - return pkgerrors.Wrap(err, "error creating api initializer") + if !errors.Is(err, ErrNoCredentialFile) { + return errors.Wrap(err, "error creating api initializer") } if user, err = s.FallbackAPIInitializer.Initialize(authProviderORM, lggr); err != nil { - if pkgerrors.Is(err, ErrorNoAPICredentialsAvailable) { - return pkgerrors.WithStack(err) + if errors.Is(err, ErrorNoAPICredentialsAvailable) { + return errors.WithStack(err) } - return pkgerrors.Wrap(err, "error creating fallback initializer") + return errors.Wrap(err, "error creating fallback initializer") } } @@ -466,7 +466,7 @@ func (s *Shell) runNode(c *cli.Context) error { // We do not try stopping any sub-services that might be started, // because the app will exit immediately upon return. // But LockedDB will be released by defer in above. - return pkgerrors.Wrap(err, "error starting app") + return errors.Wrap(err, "error starting app") } grp, grpCtx := errgroup.WithContext(rootCtx) @@ -474,7 +474,7 @@ func (s *Shell) runNode(c *cli.Context) error { grp.Go(func() error { <-grpCtx.Done() if errInternal := app.Stop(); errInternal != nil { - return pkgerrors.Wrap(errInternal, "error stopping app") + return errors.Wrap(errInternal, "error stopping app") } return nil }) @@ -483,7 +483,7 @@ func (s *Shell) runNode(c *cli.Context) error { grp.Go(func() error { errInternal := s.Runner.Run(grpCtx, app) - if pkgerrors.Is(errInternal, http.ErrServerClosed) { + if errors.Is(errInternal, http.ErrServerClosed) { errInternal = nil } // In tests we have custom runners that stop the app gracefully, @@ -566,7 +566,7 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { addressBytes, err := hexutil.Decode(addressHex) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "could not decode address")) + return s.errorOut(errors.Wrap(err, "could not decode address")) } address := gethCommon.BytesToAddress(addressBytes) @@ -575,20 +575,20 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { var ok bool chainID, ok = big.NewInt(0).SetString(chainIDStr, 10) if !ok { - return s.errorOut(pkgerrors.New("invalid evmChainID")) + return s.errorOut(errors.New("invalid evmChainID")) } } lggr := logger.Sugared(s.Logger.Named("RebroadcastTransactions")) db, err := pg.OpenUnlockedDB(s.Config.AppID(), s.Config.Database()) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "opening DB")) + return s.errorOut(errors.Wrap(err, "opening DB")) } defer lggr.ErrorIfFn(db.Close, "Error closing db") app, err := s.AppFactory.NewApplication(ctx, s.Config, lggr, db) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "fatal error instantiating application")) + return s.errorOut(errors.Wrap(err, "fatal error instantiating application")) } // TODO: BCF-2511 once the dust settles on BCF-2440/1 evaluate how the @@ -622,10 +622,10 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { err = keyStore.Unlock(s.Config.Password().Keystore()) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "error authenticating keystore")) + return s.errorOut(errors.Wrap(err, "error authenticating keystore")) } - if err = keyStore.Eth().CheckEnabled(address, chain.ID()); err != nil { + if err = keyStore.Eth().CheckEnabled(ctx, address, chain.ID()); err != nil { return s.errorOut(err) } @@ -685,7 +685,7 @@ func (ps HealthCheckPresenters) RenderTable(rt RendererTable) error { return nil } -var errDBURLMissing = pkgerrors.New("You must set CL_DATABASE_URL env variable or provide a secrets TOML with Database.URL set. HINT: If you are running this to set up your local test database, try CL_DATABASE_URL=postgresql://postgres@localhost:5432/chainlink_test?sslmode=disable") +var errDBURLMissing = errors.New("You must set CL_DATABASE_URL env variable or provide a secrets TOML with Database.URL set. HINT: If you are running this to set up your local test database, try CL_DATABASE_URL=postgresql://postgres@localhost:5432/chainlink_test?sslmode=disable") // ConfigValidate validate the client configuration and pretty-prints results func (s *Shell) ConfigFileValidate(_ *cli.Context) error { @@ -911,7 +911,7 @@ func (s *Shell) RollbackDatabase(c *cli.Context) error { arg := c.Args().First() numVersion, err := strconv.ParseInt(arg, 10, 64) if err != nil { - return s.errorOut(pkgerrors.Errorf("Unable to parse %v as integer", arg)) + return s.errorOut(errors.Errorf("Unable to parse %v as integer", arg)) } version = null.IntFrom(numVersion) } @@ -962,7 +962,7 @@ func (s *Shell) StatusDatabase(_ *cli.Context) error { // CreateMigration displays the database migration status func (s *Shell) CreateMigration(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("You must specify a migration name")) + return s.errorOut(errors.New("You must specify a migration name")) } db, err := newConnection(s.Config.Database()) if err != nil { @@ -995,44 +995,43 @@ func (s *Shell) CleanupChainTables(c *cli.Context) error { db, err := newConnection(cfg) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "error connecting to the database")) + return s.errorOut(errors.Wrap(err, "error connecting to the database")) } defer db.Close() // some tables with evm_chain_id (mostly job specs) are in public schema tablesToDeleteFromQuery := `SELECT table_name, table_schema FROM information_schema.columns WHERE "column_name"=$1;` // Delete rows from each table based on the chain_id. - if strings.EqualFold("EVM", c.String("type")) { - rows, err := db.Query(tablesToDeleteFromQuery, "evm_chain_id") - if err != nil { - return err - } - defer rows.Close() + if !strings.EqualFold("EVM", c.String("type")) { + return s.errorOut(errors.New("unknown chain type")) + } + rows, err := db.Query(tablesToDeleteFromQuery, "evm_chain_id") + if err != nil { + return err + } + defer rows.Close() - var tablesToDeleteFrom []string - for rows.Next() { - var name string - var schema string - if err = rows.Scan(&name, &schema); err != nil { - return err - } - tablesToDeleteFrom = append(tablesToDeleteFrom, schema+"."+name) - } - if rows.Err() != nil { - return rows.Err() + var tablesToDeleteFrom []string + for rows.Next() { + var name string + var schema string + if err = rows.Scan(&name, &schema); err != nil { + return err } + tablesToDeleteFrom = append(tablesToDeleteFrom, schema+"."+name) + } + if rows.Err() != nil { + return rows.Err() + } - for _, tableName := range tablesToDeleteFrom { - query := fmt.Sprintf(`DELETE FROM %s WHERE "evm_chain_id"=$1;`, tableName) - _, err = db.Exec(query, c.String("id")) - if err != nil { - fmt.Printf("Error deleting rows containing evm_chain_id from %s: %v\n", tableName, err) - } else { - fmt.Printf("Rows with evm_chain_id %s deleted from %s.\n", c.String("id"), tableName) - } + for _, tableName := range tablesToDeleteFrom { + query := fmt.Sprintf(`DELETE FROM %s WHERE "evm_chain_id"=$1;`, tableName) + _, err = db.Exec(query, c.String("id")) + if err != nil { + fmt.Printf("Error deleting rows containing evm_chain_id from %s: %v\n", tableName, err) + } else { + fmt.Printf("Rows with evm_chain_id %s deleted from %s.\n", c.String("id"), tableName) } - } else { - return s.errorOut(pkgerrors.New("unknown chain type")) } return nil } @@ -1130,7 +1129,7 @@ func dumpSchema(dbURL url.URL) (string, error) { schema, err := cmd.Output() if err != nil { var ee *exec.ExitError - if pkgerrors.As(err, &ee) { + if errors.As(err, &ee) { return "", fmt.Errorf("failed to dump schema: %v\n%s", err, string(ee.Stderr)) } return "", fmt.Errorf("failed to dump schema: %v", err) @@ -1146,7 +1145,7 @@ func checkSchema(dbURL url.URL, prevSchema string) error { df := diff.Diff(prevSchema, newSchema) if len(df) > 0 { fmt.Println(df) - return pkgerrors.New("schema pre- and post- rollback does not match (ctrl+f for '+' or '-' to find the changed lines)") + return errors.New("schema pre- and post- rollback does not match (ctrl+f for '+' or '-' to find the changed lines)") } return nil } @@ -1164,7 +1163,7 @@ func insertFixtures(dbURL url.URL, pathToFixtures string) (err error) { _, filename, _, ok := runtime.Caller(1) if !ok { - return pkgerrors.New("could not get runtime.Caller(1)") + return errors.New("could not get runtime.Caller(1)") } filepath := path.Join(path.Dir(filename), pathToFixtures) fixturesSQL, err := os.ReadFile(filepath) diff --git a/core/cmd/shell_local_test.go b/core/cmd/shell_local_test.go index 72c2f2b5bbd..d6f4946dd9d 100644 --- a/core/cmd/shell_local_test.go +++ b/core/cmd/shell_local_test.go @@ -181,7 +181,7 @@ func TestShell_RunNodeWithAPICredentialsFile(t *testing.T) { pgtest.MustExec(t, db, "DELETE FROM users;") keyStore := cltest.NewKeyStore(t, db, cfg.Database()) - _, err := keyStore.Eth().Create(&cltest.FixtureChainID) + _, err := keyStore.Eth().Create(testutils.Context(t), &cltest.FixtureChainID) require.NoError(t, err) ethClient := evmtest.NewEthClientMock(t) @@ -436,7 +436,6 @@ func TestShell_RebroadcastTransactions_AddressCheck(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - config, sqlxDB := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Database.Dialect = dialects.Postgres @@ -450,7 +449,7 @@ func TestShell_RebroadcastTransactions_AddressCheck(t *testing.T) { _, fromAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) if !test.enableAddress { - err := keyStore.Eth().Disable(fromAddress, testutils.FixtureChainID) + err := keyStore.Eth().Disable(testutils.Context(t), fromAddress, testutils.FixtureChainID) require.NoError(t, err, "failed to disable test key") } diff --git a/core/cmd/shell_remote.go b/core/cmd/shell_remote.go index 53affdfd494..aab4a94da6f 100644 --- a/core/cmd/shell_remote.go +++ b/core/cmd/shell_remote.go @@ -15,7 +15,7 @@ import ( "github.com/manyminds/api2go/jsonapi" "github.com/mitchellh/go-homedir" "github.com/pelletier/go-toml" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/tidwall/gjson" "github.com/urfave/cli" "go.uber.org/multierr" @@ -80,15 +80,15 @@ func initRemoteConfigSubCmds(s *Shell) []cli.Command { } var ( - errUnauthorized = pkgerrors.New(http.StatusText(http.StatusUnauthorized)) - errForbidden = pkgerrors.New(http.StatusText(http.StatusForbidden)) - errBadRequest = pkgerrors.New(http.StatusText(http.StatusBadRequest)) + errUnauthorized = errors.New(http.StatusText(http.StatusUnauthorized)) + errForbidden = errors.New(http.StatusText(http.StatusForbidden)) + errBadRequest = errors.New(http.StatusText(http.StatusBadRequest)) ) // CreateExternalInitiator adds an external initiator func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { if c.NArg() != 1 && c.NArg() != 2 { - return s.errorOut(pkgerrors.New("create expects 1 - 2 arguments: a name and a url (optional)")) + return s.errorOut(errors.New("create expects 1 - 2 arguments: a name and a url (optional)")) } var request bridges.ExternalInitiatorRequest @@ -128,7 +128,7 @@ func (s *Shell) CreateExternalInitiator(c *cli.Context) (err error) { // DeleteExternalInitiator removes an external initiator func (s *Shell) DeleteExternalInitiator(c *cli.Context) (err error) { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the name of the external initiator to delete")) + return s.errorOut(errors.New("Must pass the name of the external initiator to delete")) } resp, err := s.HTTP.Delete(s.ctx(), "/v2/external_initiators/"+c.Args().First()) @@ -270,11 +270,11 @@ func getTOMLString(s string) (string, error) { func (s *Shell) parseResponse(resp *http.Response) ([]byte, error) { b, err := parseResponse(resp) - if pkgerrors.Is(err, errUnauthorized) { + if errors.Is(err, errUnauthorized) { return nil, s.errorOut(multierr.Append(err, fmt.Errorf("your credentials may be missing, invalid or you may need to login first using the CLI via 'chainlink admin login'"))) } - if pkgerrors.Is(err, errForbidden) { + if errors.Is(err, errForbidden) { return nil, s.errorOut(multierr.Append(err, fmt.Errorf("this action requires %s privileges. The current user %s has '%s' role and cannot perform this action, login with a user that has '%s' role via 'chainlink admin login'", resp.Header.Get("forbidden-required-role"), resp.Header.Get("forbidden-provided-email"), resp.Header.Get("forbidden-provided-role"), resp.Header.Get("forbidden-required-role")))) } if err != nil { @@ -327,7 +327,7 @@ func (s *Shell) configV2Str(userOnly bool) (string, error) { return "", s.errorOut(err) } if resp.StatusCode != 200 { - return "", s.errorOut(pkgerrors.Errorf("got HTTP status %d: %s", resp.StatusCode, respPayload)) + return "", s.errorOut(errors.Errorf("got HTTP status %d: %s", resp.StatusCode, respPayload)) } var configV2Resource web.ConfigV2Resource err = web.ParseJSONAPIResponse(respPayload, &configV2Resource) @@ -370,7 +370,7 @@ func (s *Shell) SetLogLevel(c *cli.Context) (err error) { func (s *Shell) SetLogSQL(c *cli.Context) (err error) { // Enforces selection of --enable or --disable if !c.Bool("enable") && !c.Bool("disable") { - return s.errorOut(pkgerrors.New("Must set logSql --enabled || --disable")) + return s.errorOut(errors.New("Must set logSql --enabled || --disable")) } // Sets logSql to true || false based on the --enabled flag @@ -428,7 +428,7 @@ func fromFile(arg string) (*bytes.Buffer, error) { func (s *Shell) deserializeAPIResponse(resp *http.Response, dst interface{}, links *jsonapi.Links) error { b, err := s.parseResponse(resp) if err != nil { - return pkgerrors.Wrap(err, "parseResponse error") + return errors.Wrap(err, "parseResponse error") } if err = web.ParsePaginatedResponse(b, dst, links); err != nil { return s.errorOut(err) @@ -442,15 +442,15 @@ func parseErrorResponseBody(responseBody []byte) (string, error) { return "Empty error message", nil } - var errs models.JSONAPIErrors - err := json.Unmarshal(responseBody, &errs) - if err != nil || len(errs.Errors) == 0 { + var errors models.JSONAPIErrors + err := json.Unmarshal(responseBody, &errors) + if err != nil || len(errors.Errors) == 0 { return "", err } var errorDetails strings.Builder - errorDetails.WriteString(errs.Errors[0].Detail) - for _, errorDetail := range errs.Errors[1:] { + errorDetails.WriteString(errors.Errors[0].Detail) + for _, errorDetail := range errors.Errors[1:] { fmt.Fprintf(&errorDetails, "\n%s", errorDetail.Detail) } return errorDetails.String(), nil @@ -459,7 +459,7 @@ func parseErrorResponseBody(responseBody []byte) (string, error) { func parseResponse(resp *http.Response) ([]byte, error) { b, err := io.ReadAll(resp.Body) if err != nil { - return b, multierr.Append(pkgerrors.New(resp.Status), err) + return b, multierr.Append(errors.New(resp.Status), err) } if resp.StatusCode == http.StatusUnauthorized { return b, errUnauthorized @@ -470,7 +470,7 @@ func parseResponse(resp *http.Response) ([]byte, error) { if err2 != nil { return b, err2 } - return b, pkgerrors.New(errorMessage) + return b, errors.New(errorMessage) } return b, err } diff --git a/core/cmd/solana_node_commands_test.go b/core/cmd/solana_node_commands_test.go index 316cf16212d..ebe9502d1fa 100644 --- a/core/cmd/solana_node_commands_test.go +++ b/core/cmd/solana_node_commands_test.go @@ -55,13 +55,13 @@ func TestShell_IndexSolanaNodes(t *testing.T) { n1 := nodes[0] n2 := nodes[1] assert.Equal(t, id, n1.ChainID) - assert.Equal(t, *node1.Name, n1.ID) + assert.Equal(t, cltest.FormatWithPrefixedChainID(id, *node1.Name), n1.ID) assert.Equal(t, *node1.Name, n1.Name) wantConfig, err := toml.Marshal(node1) require.NoError(t, err) assert.Equal(t, string(wantConfig), n1.Config) assert.Equal(t, id, n2.ChainID) - assert.Equal(t, *node2.Name, n2.ID) + assert.Equal(t, cltest.FormatWithPrefixedChainID(id, *node2.Name), n2.ID) assert.Equal(t, *node2.Name, n2.Name) wantConfig2, err := toml.Marshal(node2) require.NoError(t, err) diff --git a/core/cmd/solana_transaction_commands.go b/core/cmd/solana_transaction_commands.go index b060585d174..23e94eee50b 100644 --- a/core/cmd/solana_transaction_commands.go +++ b/core/cmd/solana_transaction_commands.go @@ -7,7 +7,7 @@ import ( "strconv" solanaGo "github.com/gagliardetto/solana-go" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -61,7 +61,7 @@ func (p *SolanaMsgPresenter) RenderTable(rt RendererTable) error { // SolanaSendSol transfers sol from the node's account to a specified address. func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { if c.NArg() < 3 { - return s.errorOut(pkgerrors.New("three arguments expected: amount, fromAddress and toAddress")) + return s.errorOut(errors.New("three arguments expected: amount, fromAddress and toAddress")) } amount, err := strconv.ParseUint(c.Args().Get(0), 10, 64) @@ -73,7 +73,7 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { fromAddress, err := solanaGo.PublicKeyFromBase58(unparsedFromAddress) if err != nil { return s.errorOut(multierr.Combine( - pkgerrors.Errorf("while parsing withdrawal source address %v", + errors.Errorf("while parsing withdrawal source address %v", unparsedFromAddress), err)) } @@ -81,13 +81,13 @@ func (s *Shell) SolanaSendSol(c *cli.Context) (err error) { destinationAddress, err := solanaGo.PublicKeyFromBase58(unparsedDestinationAddress) if err != nil { return s.errorOut(multierr.Combine( - pkgerrors.Errorf("while parsing withdrawal destination address %v", + errors.Errorf("while parsing withdrawal destination address %v", unparsedDestinationAddress), err)) } chainID := c.String("id") if chainID == "" { - return s.errorOut(pkgerrors.New("missing id")) + return s.errorOut(errors.New("missing id")) } request := solana.SendRequest{ diff --git a/core/cmd/starknet_node_commands_test.go b/core/cmd/starknet_node_commands_test.go index 0347cdd18f7..95f712d29bd 100644 --- a/core/cmd/starknet_node_commands_test.go +++ b/core/cmd/starknet_node_commands_test.go @@ -54,13 +54,13 @@ func TestShell_IndexStarkNetNodes(t *testing.T) { n1 := nodes[0] n2 := nodes[1] assert.Equal(t, id, n1.ChainID) - assert.Equal(t, *node1.Name, n1.ID) + assert.Equal(t, cltest.FormatWithPrefixedChainID(id, *node1.Name), n1.ID) assert.Equal(t, *node1.Name, n1.Name) wantConfig, err := toml.Marshal(node1) require.NoError(t, err) assert.Equal(t, string(wantConfig), n1.Config) assert.Equal(t, id, n2.ChainID) - assert.Equal(t, *node2.Name, n2.ID) + assert.Equal(t, cltest.FormatWithPrefixedChainID(id, *node2.Name), n2.ID) assert.Equal(t, *node2.Name, n2.Name) wantConfig2, err := toml.Marshal(node2) require.NoError(t, err) diff --git a/core/cmd/vrf_keys_commands.go b/core/cmd/vrf_keys_commands.go index db82ea08927..32d32334af5 100644 --- a/core/cmd/vrf_keys_commands.go +++ b/core/cmd/vrf_keys_commands.go @@ -7,7 +7,7 @@ import ( "net/http" "os" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/urfave/cli" "go.uber.org/multierr" @@ -135,16 +135,16 @@ func (s *Shell) CreateVRFKey(_ *cli.Context) error { // ImportVRFKey reads a file into an EncryptedVRFKey in the db func (s *Shell) ImportVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the filepath of the key to be imported")) + return s.errorOut(errors.New("Must pass the filepath of the key to be imported")) } oldPasswordFile := c.String("old-password") if len(oldPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --old-password/-p flag")) + return s.errorOut(errors.New("Must specify --old-password/-p flag")) } oldPassword, err := os.ReadFile(oldPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.Args().Get(0) @@ -172,21 +172,21 @@ func (s *Shell) ImportVRFKey(c *cli.Context) error { // requested file path. func (s *Shell) ExportVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the ID (compressed public key) of the key to export")) + return s.errorOut(errors.New("Must pass the ID (compressed public key) of the key to export")) } newPasswordFile := c.String("new-password") if len(newPasswordFile) == 0 { - return s.errorOut(pkgerrors.New("Must specify --new-password/-p flag")) + return s.errorOut(errors.New("Must specify --new-password/-p flag")) } newPassword, err := os.ReadFile(newPasswordFile) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read password file")) + return s.errorOut(errors.Wrap(err, "Could not read password file")) } filepath := c.String("output") if len(filepath) == 0 { - return s.errorOut(pkgerrors.New("Must specify --output/-o flag")) + return s.errorOut(errors.New("Must specify --output/-o flag")) } pk, err := getPublicKey(c) @@ -197,7 +197,7 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { normalizedPassword := normalizePassword(string(newPassword)) resp, err := s.HTTP.Post(s.ctx(), "/v2/keys/vrf/export/"+pk.String()+"?newpassword="+normalizedPassword, nil) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not make HTTP request")) + return s.errorOut(errors.Wrap(err, "Could not make HTTP request")) } defer func() { if cerr := resp.Body.Close(); cerr != nil { @@ -211,12 +211,12 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { keyJSON, err := io.ReadAll(resp.Body) if err != nil { - return s.errorOut(pkgerrors.Wrap(err, "Could not read response body")) + return s.errorOut(errors.Wrap(err, "Could not read response body")) } err = utils.WriteFileWithMaxPerms(filepath, keyJSON, 0o600) if err != nil { - return s.errorOut(pkgerrors.Wrapf(err, "Could not write %v", filepath)) + return s.errorOut(errors.Wrapf(err, "Could not write %v", filepath)) } _, err = os.Stderr.WriteString(fmt.Sprintf("Exported VRF key %s to %s\n", pk.String(), filepath)) @@ -232,7 +232,7 @@ func (s *Shell) ExportVRFKey(c *cli.Context) error { // (no such protection for the V1 jobs exists). func (s *Shell) DeleteVRFKey(c *cli.Context) error { if !c.Args().Present() { - return s.errorOut(pkgerrors.New("Must pass the key ID (compressed public key) to be deleted")) + return s.errorOut(errors.New("Must pass the key ID (compressed public key) to be deleted")) } id, err := getPublicKey(c) if err != nil { @@ -269,7 +269,7 @@ func getPublicKey(c *cli.Context) (secp256k1.PublicKey, error) { } publicKey, err := secp256k1.NewPublicKeyFromHex(pkHexString) if err != nil { - return secp256k1.PublicKey{}, pkgerrors.Wrap(err, "failed to parse public key") + return secp256k1.PublicKey{}, errors.Wrap(err, "failed to parse public key") } return publicKey, nil } From f18a2c183250c354b4bc79983cbae47a45c56a9c Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 26 Feb 2024 22:22:19 -0500 Subject: [PATCH 10/11] revert all changes to core/services/relay/evm --- core/services/relay/evm/address.go | 8 +- core/services/relay/evm/chain_reader_test.go | 26 ++- core/services/relay/evm/codec_test.go | 25 ++ core/services/relay/evm/config_poller.go | 93 +++----- core/services/relay/evm/config_poller_test.go | 23 +- .../relay/evm/contract_transmitter.go | 14 +- core/services/relay/evm/evm.go | 221 ++++++++++++------ core/services/relay/evm/functions.go | 36 ++- .../relay/evm/functions/config_poller.go | 14 +- .../relay/evm/functions/config_poller_test.go | 2 +- .../evm/functions/contract_transmitter.go | 27 +-- .../relay/evm/functions/logpoller_wrapper.go | 15 +- core/services/relay/evm/median.go | 10 +- .../relay/evm/mercury/config_digest.go | 2 +- .../relay/evm/mercury/config_poller.go | 6 +- .../relay/evm/mercury/config_poller_test.go | 4 +- .../relay/evm/mercury/helpers_test.go | 2 +- .../evm/mercury/offchain_config_digester.go | 8 +- .../services/relay/evm/mercury/transmitter.go | 4 +- .../relay/evm/mercury/transmitter_test.go | 42 ++-- .../relay/evm/mercury/v1/data_source_test.go | 8 +- .../relay/evm/mercury/v2/data_source_test.go | 14 +- .../relay/evm/mercury/v3/data_source_test.go | 14 +- .../relay/evm/mercury/wsrpc/client.go | 32 +-- .../relay/evm/mercury/wsrpc/pb/generate.go | 2 + .../relay/evm/mercury/wsrpc/pb/mercury.pb.go | 147 ++++++------ .../relay/evm/mercury/wsrpc/pb/mercury.proto | 2 +- .../evm/mercury/wsrpc/pb/mercury_wsrpc.pb.go | 2 +- core/services/relay/evm/ocr2keeper.go | 52 ++--- core/services/relay/evm/ocr2vrf.go | 35 +-- core/services/relay/evm/relayer_extender.go | 6 +- core/services/relay/evm/request_round_db.go | 14 +- .../relay/evm/request_round_tracker.go | 4 +- .../relay/evm/request_round_tracker_test.go | 4 +- core/services/relay/evm/types/abi_types.go | 4 + core/services/relay/evm/types/codec_entry.go | 2 +- 36 files changed, 509 insertions(+), 415 deletions(-) create mode 100644 core/services/relay/evm/mercury/wsrpc/pb/generate.go diff --git a/core/services/relay/evm/address.go b/core/services/relay/evm/address.go index 0a78270c714..1a3e93ed3ca 100644 --- a/core/services/relay/evm/address.go +++ b/core/services/relay/evm/address.go @@ -5,7 +5,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ) @@ -13,10 +13,10 @@ func AccountToAddress(accounts []types.Account) (addresses []common.Address, err for _, signer := range accounts { bytes, err := hexutil.Decode(string(signer)) if err != nil { - return []common.Address{}, pkgerrors.Wrap(err, fmt.Sprintf("given address is not valid %s", signer)) + return []common.Address{}, errors.Wrap(err, fmt.Sprintf("given address is not valid %s", signer)) } if len(bytes) != 20 { - return []common.Address{}, pkgerrors.Errorf("address is not 20 bytes %s", signer) + return []common.Address{}, errors.Errorf("address is not 20 bytes %s", signer) } addresses = append(addresses, common.BytesToAddress(bytes)) } @@ -26,7 +26,7 @@ func AccountToAddress(accounts []types.Account) (addresses []common.Address, err func OnchainPublicKeyToAddress(publicKeys []types.OnchainPublicKey) (addresses []common.Address, err error) { for _, signer := range publicKeys { if len(signer) != 20 { - return []common.Address{}, pkgerrors.Errorf("address is not 20 bytes %s", signer) + return []common.Address{}, errors.Errorf("address is not 20 bytes %s", signer) } addresses = append(addresses, common.BytesToAddress(signer)) } diff --git a/core/services/relay/evm/chain_reader_test.go b/core/services/relay/evm/chain_reader_test.go index 02e9d4e3f6a..64d9f9f1cac 100644 --- a/core/services/relay/evm/chain_reader_test.go +++ b/core/services/relay/evm/chain_reader_test.go @@ -52,19 +52,21 @@ func TestChainReader(t *testing.T) { it := &chainReaderInterfaceTester{} RunChainReaderInterfaceTests(t, it) RunChainReaderInterfaceTests(t, commontestutils.WrapChainReaderTesterForLoop(it)) + t.Run("Dynamically typed topics can be used to filter and have type correct in return", func(t *testing.T) { it.Setup(t) + // bind event before firing it to avoid log poller race + ctx := testutils.Context(t) + cr := it.GetChainReader(t) + require.NoError(t, cr.Bind(ctx, it.GetBindings(t))) + anyString := "foo" tx, err := it.evmTest.LatestValueHolderTransactor.TriggerEventWithDynamicTopic(it.auth, anyString) require.NoError(t, err) it.sim.Commit() it.incNonce() it.awaitTx(t, tx) - ctx := testutils.Context(t) - - cr := it.GetChainReader(t) - require.NoError(t, cr.Bind(ctx, it.GetBindings(t))) input := struct{ Field string }{Field: anyString} tp := cr.(clcommontypes.ContractTypeProvider) @@ -84,20 +86,24 @@ func TestChainReader(t *testing.T) { t.Run("Multiple topics can filter together", func(t *testing.T) { it.Setup(t) + + // bind event before firing it to avoid log poller race + ctx := testutils.Context(t) + cr := it.GetChainReader(t) + require.NoError(t, cr.Bind(ctx, it.GetBindings(t))) + triggerFourTopics(t, it, int32(1), int32(2), int32(3)) triggerFourTopics(t, it, int32(2), int32(2), int32(3)) triggerFourTopics(t, it, int32(1), int32(3), int32(3)) triggerFourTopics(t, it, int32(1), int32(2), int32(4)) - ctx := testutils.Context(t) - cr := it.GetChainReader(t) - require.NoError(t, cr.Bind(ctx, it.GetBindings(t))) var latest struct{ Field1, Field2, Field3 int32 } params := struct{ Field1, Field2, Field3 int32 }{Field1: 1, Field2: 2, Field3: 3} - time.Sleep(it.MaxWaitTimeForEvents()) + require.Eventually(t, func() bool { + return cr.GetLatestValue(ctx, AnyContractName, triggerWithAllTopics, params, &latest) == nil + }, it.MaxWaitTimeForEvents(), time.Millisecond*10) - require.NoError(t, cr.GetLatestValue(ctx, AnyContractName, triggerWithAllTopics, params, &latest)) assert.Equal(t, int32(1), latest.Field1) assert.Equal(t, int32(2), latest.Field2) assert.Equal(t, int32(3), latest.Field3) @@ -257,7 +263,7 @@ func (it *chainReaderInterfaceTester) GetChainReader(t *testing.T) clcommontypes lggr := logger.NullLogger db := pgtest.NewSqlxDB(t) - lp := logpoller.NewLogPoller(logpoller.NewORM(testutils.SimulatedChainID, db, lggr, pgtest.NewQConfig(true)), it.chain.Client(), lggr, time.Millisecond, false, 0, 1, 1, 10000) + lp := logpoller.NewLogPoller(logpoller.NewORM(testutils.SimulatedChainID, db, lggr, pgtest.NewQConfig(true)), it.chain.Client(), lggr, time.Millisecond, false, 0, 1, 1, 10000, 0) require.NoError(t, lp.Start(ctx)) it.chain.On("LogPoller").Return(lp) cr, err := evm.NewChainReaderService(lggr, lp, it.chain, it.chainConfig) diff --git a/core/services/relay/evm/codec_test.go b/core/services/relay/evm/codec_test.go index b13051cb010..2f9a4639d41 100644 --- a/core/services/relay/evm/codec_test.go +++ b/core/services/relay/evm/codec_test.go @@ -50,6 +50,31 @@ func TestCodec(t *testing.T) { }) } +func TestCodec_SimpleEncode(t *testing.T) { + codecName := "my_codec" + input := map[string]any{ + "Report": int32(6), + "Meta": "abcdefg", + } + evmEncoderConfig := `[{"Name":"Report","Type":"int32"},{"Name":"Meta","Type":"string"}]` + + codecConfig := types.CodecConfig{Configs: map[string]types.ChainCodecConfig{ + codecName: {TypeABI: evmEncoderConfig}, + }} + c, err := evm.NewCodec(codecConfig) + require.NoError(t, err) + + result, err := c.Encode(testutils.Context(t), input, codecName) + require.NoError(t, err) + expected := + "0000000000000000000000000000000000000000000000000000000000000006" + // int32(6) + "0000000000000000000000000000000000000000000000000000000000000040" + // total bytes occupied by the string (64) + "0000000000000000000000000000000000000000000000000000000000000007" + // length of the string (7 chars) + "6162636465666700000000000000000000000000000000000000000000000000" // actual string + + require.Equal(t, expected, hexutil.Encode(result)[2:]) +} + type codecInterfaceTester struct{} func (it *codecInterfaceTester) Setup(_ *testing.T) {} diff --git a/core/services/relay/evm/config_poller.go b/core/services/relay/evm/config_poller.go index ef9934f4e10..bb962fc6ed5 100644 --- a/core/services/relay/evm/config_poller.go +++ b/core/services/relay/evm/config_poller.go @@ -5,10 +5,9 @@ import ( "database/sql" "fmt" - "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -34,60 +33,9 @@ var ( ) ) -var ( - // ConfigSet Common to all OCR2 evm based contracts: https://github.com/smartcontractkit/libocr/blob/master/contract2/dev/OCR2Abstract.sol - ConfigSet common.Hash - - defaultABI abi.ABI -) - -const configSetEventName = "ConfigSet" - -func init() { - var err error - abiPointer, err := ocr2aggregator.OCR2AggregatorMetaData.GetAbi() - if err != nil { - panic(err) - } - defaultABI = *abiPointer - ConfigSet = defaultABI.Events[configSetEventName].ID -} - -func unpackLogData(d []byte) (*ocr2aggregator.OCR2AggregatorConfigSet, error) { - unpacked := new(ocr2aggregator.OCR2AggregatorConfigSet) - err := defaultABI.UnpackIntoInterface(unpacked, configSetEventName, d) - if err != nil { - return nil, pkgerrors.Wrap(err, "failed to unpack log data") - } - return unpacked, nil -} - -func configFromLog(logData []byte) (ocrtypes.ContractConfig, error) { - unpacked, err := unpackLogData(logData) - if err != nil { - return ocrtypes.ContractConfig{}, err - } - - var transmitAccounts []ocrtypes.Account - for _, addr := range unpacked.Transmitters { - transmitAccounts = append(transmitAccounts, ocrtypes.Account(addr.Hex())) - } - var signers []ocrtypes.OnchainPublicKey - for _, addr := range unpacked.Signers { - addr := addr - signers = append(signers, addr[:]) - } - - return ocrtypes.ContractConfig{ - ConfigDigest: unpacked.ConfigDigest, - ConfigCount: unpacked.ConfigCount, - Signers: signers, - Transmitters: transmitAccounts, - F: unpacked.F, - OnchainConfig: unpacked.OnchainConfig, - OffchainConfigVersion: unpacked.OffchainConfigVersion, - OffchainConfig: unpacked.OffchainConfig, - }, nil +type LogDecoder interface { + EventSig() common.Hash + Decode(rawLog []byte) (ocrtypes.ContractConfig, error) } type configPoller struct { @@ -105,18 +53,30 @@ type configPoller struct { // contract allows us work around such restrictions. configStoreContractAddr *common.Address configStoreContract *ocrconfigurationstoreevmsimple.OCRConfigurationStoreEVMSimple + + // Depending on the exact contract used, the raw config log may be shaped + // in different ways + ld LogDecoder } func configPollerFilterName(addr common.Address) string { return logpoller.FilterName("OCR2ConfigPoller", addr.String()) } -func NewConfigPoller(lggr logger.Logger, client client.Client, destChainPoller logpoller.LogPoller, aggregatorContractAddr common.Address, configStoreAddr *common.Address) (evmRelayTypes.ConfigPoller, error) { - return newConfigPoller(lggr, client, destChainPoller, aggregatorContractAddr, configStoreAddr) +type CPConfig struct { + Client client.Client + DestinationChainPoller logpoller.LogPoller + AggregatorContractAddress common.Address + ConfigStoreAddress *common.Address + LogDecoder LogDecoder +} + +func NewConfigPoller(lggr logger.Logger, cfg CPConfig) (evmRelayTypes.ConfigPoller, error) { + return newConfigPoller(lggr, cfg.Client, cfg.DestinationChainPoller, cfg.AggregatorContractAddress, cfg.ConfigStoreAddress, cfg.LogDecoder) } -func newConfigPoller(lggr logger.Logger, client client.Client, destChainPoller logpoller.LogPoller, aggregatorContractAddr common.Address, configStoreAddr *common.Address) (*configPoller, error) { - err := destChainPoller.RegisterFilter(logpoller.Filter{Name: configPollerFilterName(aggregatorContractAddr), EventSigs: []common.Hash{ConfigSet}, Addresses: []common.Address{aggregatorContractAddr}}) +func newConfigPoller(lggr logger.Logger, client client.Client, destChainPoller logpoller.LogPoller, aggregatorContractAddr common.Address, configStoreAddr *common.Address, ld LogDecoder) (*configPoller, error) { + err := destChainPoller.RegisterFilter(logpoller.Filter{Name: configPollerFilterName(aggregatorContractAddr), EventSigs: []common.Hash{ld.EventSig()}, Addresses: []common.Address{aggregatorContractAddr}}) if err != nil { return nil, err } @@ -133,6 +93,7 @@ func newConfigPoller(lggr logger.Logger, client client.Client, destChainPoller l aggregatorContractAddr: aggregatorContractAddr, client: client, aggregatorContract: aggregatorContract, + ld: ld, } if configStoreAddr != nil { @@ -164,9 +125,9 @@ func (cp *configPoller) Replay(ctx context.Context, fromBlock int64) error { // LatestConfigDetails returns the latest config details from the logs func (cp *configPoller) LatestConfigDetails(ctx context.Context) (changedInBlock uint64, configDigest ocrtypes.ConfigDigest, err error) { - latest, err := cp.destChainLogPoller.LatestLogByEventSigWithConfs(ConfigSet, cp.aggregatorContractAddr, 1, pg.WithParentCtx(ctx)) + latest, err := cp.destChainLogPoller.LatestLogByEventSigWithConfs(cp.ld.EventSig(), cp.aggregatorContractAddr, 1, pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { if cp.isConfigStoreAvailable() { // Fallback to RPC call in case logs have been pruned and configStoreContract is available return cp.callLatestConfigDetails(ctx) @@ -176,7 +137,7 @@ func (cp *configPoller) LatestConfigDetails(ctx context.Context) (changedInBlock } return 0, ocrtypes.ConfigDigest{}, err } - latestConfigSet, err := configFromLog(latest.Data) + latestConfigSet, err := cp.ld.Decode(latest.Data) if err != nil { return 0, ocrtypes.ConfigDigest{}, err } @@ -185,7 +146,7 @@ func (cp *configPoller) LatestConfigDetails(ctx context.Context) (changedInBlock // LatestConfig returns the latest config from the logs on a certain block func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) (ocrtypes.ContractConfig, error) { - lgs, err := cp.destChainLogPoller.Logs(int64(changedInBlock), int64(changedInBlock), ConfigSet, cp.aggregatorContractAddr, pg.WithParentCtx(ctx)) + lgs, err := cp.destChainLogPoller.Logs(int64(changedInBlock), int64(changedInBlock), cp.ld.EventSig(), cp.aggregatorContractAddr, pg.WithParentCtx(ctx)) if err != nil { return ocrtypes.ContractConfig{}, err } @@ -196,7 +157,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) } return ocrtypes.ContractConfig{}, fmt.Errorf("no logs found for config on contract %s (chain %s) at block %d", cp.aggregatorContractAddr.Hex(), cp.client.ConfiguredChainID().String(), changedInBlock) } - latestConfigSet, err := configFromLog(lgs[len(lgs)-1].Data) + latestConfigSet, err := cp.ld.Decode(lgs[len(lgs)-1].Data) if err != nil { return ocrtypes.ContractConfig{}, err } @@ -208,7 +169,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) func (cp *configPoller) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { latest, err := cp.destChainLogPoller.LatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { return 0, nil } return 0, err diff --git a/core/services/relay/evm/config_poller_test.go b/core/services/relay/evm/config_poller_test.go index 28687573760..089db6decd5 100644 --- a/core/services/relay/evm/config_poller_test.go +++ b/core/services/relay/evm/config_poller_test.go @@ -14,7 +14,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/onsi/gomega" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -28,6 +28,7 @@ import ( ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" evmClientMocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" @@ -55,6 +56,8 @@ func TestConfigPoller(t *testing.T) { var linkTokenAddress common.Address var accessAddress common.Address + ld := OCR2AggregatorLogDecoder + { key, err := crypto.GenerateKey() require.NoError(t, err) @@ -87,12 +90,12 @@ func TestConfigPoller(t *testing.T) { cfg := pgtest.NewQConfig(false) ethClient = evmclient.NewSimulatedBackendClient(t, b, testutils.SimulatedChainID) lorm := logpoller.NewORM(testutils.SimulatedChainID, db, lggr, cfg) - lp = logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000) + lp = logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000, 0) servicetest.Run(t, lp) } t.Run("LatestConfig errors if there is no config in logs and config store is unconfigured", func(t *testing.T) { - cp, err := NewConfigPoller(lggr, ethClient, lp, ocrAddress, nil) + cp, err := NewConfigPoller(lggr, CPConfig{ethClient, lp, ocrAddress, nil, ld}) require.NoError(t, err) _, err = cp.LatestConfig(testutils.Context(t), 0) @@ -101,7 +104,7 @@ func TestConfigPoller(t *testing.T) { }) t.Run("happy path (with config store)", func(t *testing.T) { - cp, err := NewConfigPoller(lggr, ethClient, lp, ocrAddress, &configStoreContractAddr) + cp, err := NewConfigPoller(lggr, CPConfig{ethClient, lp, ocrAddress, &configStoreContractAddr, ld}) require.NoError(t, err) // Should have no config to begin with. _, configDigest, err := cp.LatestConfigDetails(testutils.Context(t)) @@ -172,7 +175,7 @@ func TestConfigPoller(t *testing.T) { mp.On("LatestLogByEventSigWithConfs", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, sql.ErrNoRows) t.Run("if callLatestConfigDetails succeeds", func(t *testing.T) { - cp, err := newConfigPoller(lggr, ethClient, mp, ocrAddress, &configStoreContractAddr) + cp, err := newConfigPoller(lggr, ethClient, mp, ocrAddress, &configStoreContractAddr, ld) require.NoError(t, err) t.Run("when config has not been set, returns zero values", func(t *testing.T) { @@ -208,8 +211,8 @@ func TestConfigPoller(t *testing.T) { t.Run("returns error if callLatestConfigDetails fails", func(t *testing.T) { failingClient := new(evmClientMocks.Client) failingClient.On("ConfiguredChainID").Return(big.NewInt(42)) - failingClient.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Return(nil, pkgerrors.New("something exploded")) - cp, err := newConfigPoller(lggr, failingClient, mp, ocrAddress, &configStoreContractAddr) + failingClient.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("something exploded")) + cp, err := newConfigPoller(lggr, failingClient, mp, ocrAddress, &configStoreContractAddr, ld) require.NoError(t, err) cp.configStoreContractAddr = &configStoreContractAddr @@ -248,7 +251,7 @@ func TestConfigPoller(t *testing.T) { mp.On("LatestLogByEventSigWithConfs", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, sql.ErrNoRows) t.Run("if callReadConfig succeeds", func(t *testing.T) { - cp, err := newConfigPoller(lggr, ethClient, mp, ocrAddress, &configStoreContractAddr) + cp, err := newConfigPoller(lggr, ethClient, mp, ocrAddress, &configStoreContractAddr, ld) require.NoError(t, err) t.Run("when config has not been set, returns error", func(t *testing.T) { @@ -309,8 +312,8 @@ func TestConfigPoller(t *testing.T) { failingClient.On("CallContract", mock.Anything, mock.MatchedBy(func(callArgs ethereum.CallMsg) bool { // initial call to retrieve config store address from aggregator return *callArgs.To == ocrAddress - }), mock.Anything).Return(nil, pkgerrors.New("something exploded")).Once() - cp, err := newConfigPoller(lggr, failingClient, mp, ocrAddress, &configStoreContractAddr) + }), mock.Anything).Return(nil, errors.New("something exploded")).Once() + cp, err := newConfigPoller(lggr, failingClient, mp, ocrAddress, &configStoreContractAddr, ld) require.NoError(t, err) _, err = cp.LatestConfig(testutils.Context(t), 0) diff --git a/core/services/relay/evm/contract_transmitter.go b/core/services/relay/evm/contract_transmitter.go index 767a8f98a6d..76360e34e1a 100644 --- a/core/services/relay/evm/contract_transmitter.go +++ b/core/services/relay/evm/contract_transmitter.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" gethcommon "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -66,7 +66,7 @@ func NewOCRContractTransmitter( ) (*contractTransmitter, error) { transmitted, ok := contractABI.Events["Transmitted"] if !ok { - return nil, pkgerrors.New("invalid ABI, missing transmitted") + return nil, errors.New("invalid ABI, missing transmitted") } err := lp.RegisterFilter(logpoller.Filter{Name: transmitterFilterName(address), EventSigs: []common.Hash{transmitted.ID}, Addresses: []common.Address{address}}) @@ -94,7 +94,7 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. var ss [][32]byte var vs [32]byte if len(signatures) > 32 { - return pkgerrors.New("too many signatures, maximum is 32") + return errors.New("too many signatures, maximum is 32") } for i, as := range signatures { r, s, v, err := evmutil.SplitSignature(as.Signature) @@ -116,10 +116,10 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. payload, err := oc.contractABI.Pack("transmit", rawReportCtx, []byte(report), rs, ss, vs) if err != nil { - return pkgerrors.Wrap(err, "abi.Pack failed") + return errors.Wrap(err, "abi.Pack failed") } - return pkgerrors.Wrap(oc.transmitter.CreateEthTransaction(ctx, oc.contractAddress, payload, txMeta), "failed to send Eth transaction") + return errors.Wrap(oc.transmitter.CreateEthTransaction(ctx, oc.contractAddress, payload, txMeta), "failed to send Eth transaction") } type contractReader interface { @@ -142,7 +142,7 @@ func parseTransmitted(log []byte) ([32]byte, uint32, error) { return [32]byte{}, 0, err } if len(transmitted) < 2 { - return [32]byte{}, 0, pkgerrors.New("transmitted event log has too few arguments") + return [32]byte{}, 0, errors.New("transmitted event log has too few arguments") } configDigest := *abi.ConvertType(transmitted[0], new([32]byte)).(*[32]byte) epoch := *abi.ConvertType(transmitted[1], new(uint32)).(*uint32) @@ -184,7 +184,7 @@ func (oc *contractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) ( latest, err := oc.lp.LatestLogByEventSigWithConfs( oc.transmittedEventSig, oc.contractAddress, 1, pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { // No transmissions yet return configDigest, 0, nil } diff --git a/core/services/relay/evm/evm.go b/core/services/relay/evm/evm.go index 596f53308b6..a02885cb556 100644 --- a/core/services/relay/evm/evm.go +++ b/core/services/relay/evm/evm.go @@ -17,7 +17,6 @@ import ( "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2/reportingplugin/median" "github.com/smartcontractkit/libocr/offchainreporting2/reportingplugin/median/evmreportcodec" - "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -29,6 +28,9 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" + "github.com/smartcontractkit/chainlink/v2/core/services/llo" + "github.com/smartcontractkit/chainlink/v2/core/services/llo/bm" + lloconfig "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/llo/config" mercuryconfig "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/mercury/config" "github.com/smartcontractkit/chainlink/v2/core/services/ocrcommon" "github.com/smartcontractkit/chainlink/v2/core/services/pg" @@ -42,6 +44,28 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/types" ) +var ( + OCR2AggregatorTransmissionContractABI abi.ABI + OCR2AggregatorLogDecoder LogDecoder + ChannelVerifierLogDecoder LogDecoder +) + +func init() { + var err error + OCR2AggregatorTransmissionContractABI, err = abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) + if err != nil { + panic(err) + } + OCR2AggregatorLogDecoder, err = newOCR2AggregatorLogDecoder() + if err != nil { + panic(err) + } + ChannelVerifierLogDecoder, err = newChannelVerifierLogDecoder() + if err != nil { + panic(err) + } +} + var _ commontypes.Relayer = &Relayer{} //nolint:staticcheck type Relayer struct { @@ -53,6 +77,10 @@ type Relayer struct { pgCfg pg.QConfig chainReader commontypes.ChainReader codec commontypes.Codec + + // LLO/data streams + cdcFactory llo.ChannelDefinitionCacheFactory + orm llo.ORM } type CSAETHKeystore interface { @@ -91,6 +119,9 @@ func NewRelayer(lggr logger.Logger, chain legacyevm.Chain, opts RelayerOpts) (*R return nil, fmt.Errorf("cannot create evm relayer: %w", err) } lggr = lggr.Named("Relayer") + + orm := llo.NewORM(pg.NewQ(opts.DB, lggr, opts.QConfig), chain.ID()) + cdcFactory := llo.NewChannelDefinitionCacheFactory(lggr, orm, chain.LogPoller()) return &Relayer{ db: opts.DB, chain: chain, @@ -98,6 +129,8 @@ func NewRelayer(lggr logger.Logger, chain legacyevm.Chain, opts RelayerOpts) (*R ks: opts.CSAETHKeystore, mercuryPool: opts.MercuryPool, pgCfg: opts.QConfig, + cdcFactory: cdcFactory, + orm: orm, }, nil } @@ -125,6 +158,32 @@ func (r *Relayer) HealthReport() (report map[string]error) { return } +func (r *Relayer) NewPluginProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (commontypes.PluginProvider, error) { + + // TODO https://smartcontract-it.atlassian.net/browse/BCF-2887 + ctx := context.Background() + + lggr := r.lggr.Named("PluginProvider").Named(rargs.ExternalJobID.String()) + + configWatcher, err := newStandardConfigProvider(r.lggr, r.chain, types.NewRelayOpts(rargs)) + if err != nil { + return nil, err + } + + transmitter, err := newOnChainContractTransmitter(ctx, r.lggr, rargs, pargs.TransmitterID, r.ks.Eth(), configWatcher, configTransmitterOpts{}, OCR2AggregatorTransmissionContractABI) + if err != nil { + return nil, err + } + + return NewPluginProvider( + r.chainReader, + r.codec, + transmitter, + configWatcher, + lggr, + ), nil +} + func (r *Relayer) NewMercuryProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (commontypes.MercuryProvider, error) { lggr := r.lggr.Named("MercuryProvider").Named(rargs.ExternalJobID.String()) relayOpts := types.NewRelayOpts(rargs) @@ -146,7 +205,7 @@ func (r *Relayer) NewMercuryProvider(rargs commontypes.RelayArgs, pargs commonty if relayConfig.ChainID.String() != r.chain.ID().String() { return nil, fmt.Errorf("internal error: chain id in spec does not match this relayer's chain: have %s expected %s", relayConfig.ChainID.String(), r.chain.ID().String()) } - cw, err := newConfigProvider(lggr, r.chain, relayOpts) + cp, err := newMercuryConfigProvider(lggr, r.chain, relayOpts) if err != nil { return nil, pkgerrors.WithStack(err) } @@ -182,22 +241,80 @@ func (r *Relayer) NewMercuryProvider(rargs commontypes.RelayArgs, pargs commonty default: return nil, fmt.Errorf("invalid feed version %d", feedID.Version()) } - transmitter := mercury.NewTransmitter(lggr, cw.ContractConfigTracker(), client, privKey.PublicKey, rargs.JobID, *relayConfig.FeedID, r.db, r.pgCfg, transmitterCodec) + transmitter := mercury.NewTransmitter(lggr, client, privKey.PublicKey, rargs.JobID, *relayConfig.FeedID, r.db, r.pgCfg, transmitterCodec) - return NewMercuryProvider(cw, r.chainReader, r.codec, NewMercuryChainReader(r.chain.HeadTracker()), transmitter, reportCodecV1, reportCodecV2, reportCodecV3, lggr), nil + return NewMercuryProvider(cp, r.chainReader, r.codec, NewMercuryChainReader(r.chain.HeadTracker()), transmitter, reportCodecV1, reportCodecV2, reportCodecV3, lggr), nil } func (r *Relayer) NewLLOProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (commontypes.LLOProvider, error) { - return nil, errors.New("not implemented") + relayOpts := types.NewRelayOpts(rargs) + var relayConfig types.RelayConfig + { + var err error + relayConfig, err = relayOpts.RelayConfig() + if err != nil { + return nil, fmt.Errorf("failed to get relay config: %w", err) + } + } + + var lloCfg lloconfig.PluginConfig + if err := json.Unmarshal(pargs.PluginConfig, &lloCfg); err != nil { + return nil, pkgerrors.WithStack(err) + } + if err := lloCfg.Validate(); err != nil { + return nil, err + } + + if relayConfig.ChainID.String() != r.chain.ID().String() { + return nil, fmt.Errorf("internal error: chain id in spec does not match this relayer's chain: have %s expected %s", relayConfig.ChainID.String(), r.chain.ID().String()) + } + cp, err := newLLOConfigProvider(r.lggr, r.chain, relayOpts) + if err != nil { + return nil, pkgerrors.WithStack(err) + } + + if !relayConfig.EffectiveTransmitterID.Valid { + return nil, pkgerrors.New("EffectiveTransmitterID must be specified") + } + privKey, err := r.ks.CSA().Get(relayConfig.EffectiveTransmitterID.String) + if err != nil { + return nil, pkgerrors.Wrap(err, "failed to get CSA key for mercury connection") + } + + // FIXME: Remove after benchmarking is done + // https://smartcontract-it.atlassian.net/browse/MERC-3487 + var transmitter llo.Transmitter + if lloCfg.BenchmarkMode { + r.lggr.Info("Benchmark mode enabled, using dummy transmitter. NOTE: THIS WILL NOT TRANSMIT ANYTHING") + transmitter = bm.NewTransmitter(r.lggr, privKey.PublicKey) + } else { + var client wsrpc.Client + client, err = r.mercuryPool.Checkout(context.Background(), privKey, lloCfg.ServerPubKey, lloCfg.ServerURL()) + if err != nil { + return nil, err + } + transmitter = llo.NewTransmitter(r.lggr, client, privKey.PublicKey) + } + + cdc, err := r.cdcFactory.NewCache(lloCfg) + if err != nil { + return nil, err + } + return NewLLOProvider(cp, transmitter, r.lggr, cdc), nil } func (r *Relayer) NewFunctionsProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (commontypes.FunctionsProvider, error) { + + // TODO https://smartcontract-it.atlassian.net/browse/BCF-2887 + ctx := context.Background() + lggr := r.lggr.Named("FunctionsProvider").Named(rargs.ExternalJobID.String()) // TODO(FUN-668): Not ready yet (doesn't implement FunctionsEvents() properly) - return NewFunctionsProvider(r.chain, rargs, pargs, lggr, r.ks.Eth(), functions.FunctionsPlugin) + return NewFunctionsProvider(ctx, r.chain, rargs, pargs, lggr, r.ks.Eth(), functions.FunctionsPlugin) } -func (r *Relayer) NewConfigProvider(args commontypes.RelayArgs) (commontypes.ConfigProvider, error) { +// NewConfigProvider is called by bootstrap jobs +func (r *Relayer) NewConfigProvider(args commontypes.RelayArgs) (configProvider commontypes.ConfigProvider, err error) { lggr := r.lggr.Named("ConfigProvider").Named(args.ExternalJobID.String()) relayOpts := types.NewRelayOpts(args) relayConfig, err := relayOpts.RelayConfig() @@ -209,7 +326,27 @@ func (r *Relayer) NewConfigProvider(args commontypes.RelayArgs) (commontypes.Con return nil, fmt.Errorf("internal error: chain id in spec does not match this relayer's chain: have %s expected %s", relayConfig.ChainID.String(), r.chain.ID().String()) } - configProvider, err := newConfigProvider(lggr, r.chain, relayOpts) + // Handle legacy jobs which did not yet specify provider type and + // switched between median/mercury based on presence of feed ID + if args.ProviderType == "" { + if relayConfig.FeedID == nil { + args.ProviderType = "median" + } else { + args.ProviderType = "mercury" + } + } + + switch args.ProviderType { + case "median": + configProvider, err = newStandardConfigProvider(lggr, r.chain, relayOpts) + case "mercury": + configProvider, err = newMercuryConfigProvider(lggr, r.chain, relayOpts) + case "llo": + configProvider, err = newLLOConfigProvider(lggr, r.chain, relayOpts) + default: + return nil, fmt.Errorf("unrecognized provider type: %q", args.ProviderType) + } + if err != nil { // Never return (*configProvider)(nil) return nil, err @@ -239,7 +376,6 @@ type configWatcher struct { services.StateMachine lggr logger.Logger contractAddress common.Address - contractABI abi.ABI offchainDigester ocrtypes.OffchainConfigDigester configPoller types.ConfigPoller chain legacyevm.Chain @@ -252,7 +388,6 @@ type configWatcher struct { func newConfigWatcher(lggr logger.Logger, contractAddress common.Address, - contractABI abi.ABI, offchainDigester ocrtypes.OffchainConfigDigester, configPoller types.ConfigPoller, chain legacyevm.Chain, @@ -263,7 +398,6 @@ func newConfigWatcher(lggr logger.Logger, return &configWatcher{ lggr: lggr.Named("ConfigWatcher").Named(contractAddress.String()), contractAddress: contractAddress, - contractABI: contractABI, offchainDigester: offchainDigester, configPoller: configPoller, chain: chain, @@ -319,63 +453,12 @@ func (c *configWatcher) ContractConfigTracker() ocrtypes.ContractConfigTracker { return c.configPoller } -func newConfigProvider(lggr logger.Logger, chain legacyevm.Chain, opts *types.RelayOpts) (*configWatcher, error) { - if !common.IsHexAddress(opts.ContractID) { - return nil, pkgerrors.Errorf("invalid contractID, expected hex address") - } - - aggregatorAddress := common.HexToAddress(opts.ContractID) - contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) - if err != nil { - return nil, pkgerrors.Wrap(err, "could not get contract ABI JSON") - } - var cp types.ConfigPoller - - relayConfig, err := opts.RelayConfig() - if err != nil { - return nil, fmt.Errorf("failed to get relay config: %w", err) - } - if relayConfig.FeedID != nil { - cp, err = mercury.NewConfigPoller( - lggr.Named(relayConfig.FeedID.String()), - chain.LogPoller(), - aggregatorAddress, - *relayConfig.FeedID, - // TODO: Does mercury need to support config contract? DF-19182 - ) - } else { - cp, err = NewConfigPoller( - lggr, - chain.Client(), - chain.LogPoller(), - aggregatorAddress, - relayConfig.ConfigContractAddress, - ) - } - if err != nil { - return nil, err - } - - var offchainConfigDigester ocrtypes.OffchainConfigDigester - if relayConfig.FeedID != nil { - // Mercury - offchainConfigDigester = mercury.NewOffchainConfigDigester(*relayConfig.FeedID, chain.Config().EVM().ChainID(), aggregatorAddress) - } else { - // Non-mercury - offchainConfigDigester = evmutil.EVMOffchainConfigDigester{ - ChainID: chain.Config().EVM().ChainID().Uint64(), - ContractAddress: aggregatorAddress, - } - } - return newConfigWatcher(lggr, aggregatorAddress, contractABI, offchainConfigDigester, cp, chain, relayConfig.FromBlock, opts.New), nil -} - type configTransmitterOpts struct { // override the gas limit default provided in the config watcher pluginGasLimit *uint32 } -func newContractTransmitter(lggr logger.Logger, rargs commontypes.RelayArgs, transmitterID string, ethKeystore keystore.Eth, configWatcher *configWatcher, opts configTransmitterOpts) (*contractTransmitter, error) { +func newOnChainContractTransmitter(ctx context.Context, lggr logger.Logger, rargs commontypes.RelayArgs, transmitterID string, ethKeystore keystore.Eth, configWatcher *configWatcher, opts configTransmitterOpts, transmissionContractABI abi.ABI) (*contractTransmitter, error) { var relayConfig types.RelayConfig if err := json.Unmarshal(rargs.RelayConfig, &relayConfig); err != nil { return nil, err @@ -398,7 +481,7 @@ func newContractTransmitter(lggr logger.Logger, rargs commontypes.RelayArgs, tra if sendingKeysLength > 1 && s == effectiveTransmitterAddress.String() { return nil, pkgerrors.New("the transmitter is a local sending key with transaction forwarding enabled") } - if err := ethKeystore.CheckEnabled(common.HexToAddress(s), configWatcher.chain.Config().EVM().ChainID()); err != nil { + if err := ethKeystore.CheckEnabled(ctx, common.HexToAddress(s), configWatcher.chain.Config().EVM().ChainID()); err != nil { return nil, pkgerrors.Wrap(err, "one of the sending keys given is not enabled") } fromAddresses = append(fromAddresses, common.HexToAddress(s)) @@ -439,7 +522,7 @@ func newContractTransmitter(lggr logger.Logger, rargs commontypes.RelayArgs, tra return NewOCRContractTransmitter( configWatcher.contractAddress, configWatcher.chain.Client(), - configWatcher.contractABI, + transmissionContractABI, transmitter, configWatcher.chain.LogPoller(), lggr, @@ -448,6 +531,9 @@ func newContractTransmitter(lggr logger.Logger, rargs commontypes.RelayArgs, tra } func (r *Relayer) NewMedianProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (commontypes.MedianProvider, error) { + // TODO https://smartcontract-it.atlassian.net/browse/BCF-2887 + ctx := context.Background() + lggr := r.lggr.Named("MedianProvider").Named(rargs.ExternalJobID.String()) relayOpts := types.NewRelayOpts(rargs) relayConfig, err := relayOpts.RelayConfig() @@ -463,13 +549,14 @@ func (r *Relayer) NewMedianProvider(rargs commontypes.RelayArgs, pargs commontyp } contractID := common.HexToAddress(relayOpts.ContractID) - configWatcher, err := newConfigProvider(lggr, r.chain, relayOpts) + configWatcher, err := newStandardConfigProvider(lggr, r.chain, relayOpts) if err != nil { return nil, err } reportCodec := evmreportcodec.ReportCodec{} - contractTransmitter, err := newContractTransmitter(lggr, rargs, pargs.TransmitterID, r.ks.Eth(), configWatcher, configTransmitterOpts{}) + + contractTransmitter, err := newOnChainContractTransmitter(ctx, lggr, rargs, pargs.TransmitterID, r.ks.Eth(), configWatcher, configTransmitterOpts{}, OCR2AggregatorTransmissionContractABI) if err != nil { return nil, err } diff --git a/core/services/relay/evm/functions.go b/core/services/relay/evm/functions.go index d11ab274c06..c10134f3acc 100644 --- a/core/services/relay/evm/functions.go +++ b/core/services/relay/evm/functions.go @@ -4,13 +4,9 @@ import ( "context" "encoding/json" "fmt" - "strings" - "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" - - "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" + "github.com/pkg/errors" "go.uber.org/multierr" @@ -94,7 +90,7 @@ func (p *functionsProvider) Codec() commontypes.Codec { return nil } -func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pargs commontypes.PluginArgs, lggr logger.Logger, ethKeystore keystore.Eth, pluginType functionsRelay.FunctionsPluginType) (evmRelayTypes.FunctionsProvider, error) { +func NewFunctionsProvider(ctx context.Context, chain legacyevm.Chain, rargs commontypes.RelayArgs, pargs commontypes.PluginArgs, lggr logger.Logger, ethKeystore keystore.Eth, pluginType functionsRelay.FunctionsPluginType) (evmRelayTypes.FunctionsProvider, error) { relayOpts := evmRelayTypes.NewRelayOpts(rargs) relayConfig, err := relayOpts.RelayConfig() if err != nil { @@ -108,7 +104,7 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa return nil, err } if !common.IsHexAddress(rargs.ContractID) { - return nil, pkgerrors.Errorf("invalid contractID, expected hex address") + return nil, errors.Errorf("invalid contractID, expected hex address") } var pluginConfig config.PluginConfig if err2 := json.Unmarshal(pargs.PluginConfig, &pluginConfig); err2 != nil { @@ -125,7 +121,7 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa } var contractTransmitter ContractTransmitter if relayConfig.SendingKeys != nil { - contractTransmitter, err = newFunctionsContractTransmitter(pluginConfig.ContractVersion, rargs, pargs.TransmitterID, configWatcher, ethKeystore, logPollerWrapper, lggr) + contractTransmitter, err = newFunctionsContractTransmitter(ctx, pluginConfig.ContractVersion, rargs, pargs.TransmitterID, configWatcher, ethKeystore, logPollerWrapper, lggr) if err != nil { return nil, err } @@ -141,14 +137,10 @@ func NewFunctionsProvider(chain legacyevm.Chain, rargs commontypes.RelayArgs, pa func newFunctionsConfigProvider(pluginType functionsRelay.FunctionsPluginType, chain legacyevm.Chain, args commontypes.RelayArgs, fromBlock uint64, logPollerWrapper evmRelayTypes.LogPollerWrapper, lggr logger.Logger) (*configWatcher, error) { if !common.IsHexAddress(args.ContractID) { - return nil, pkgerrors.Errorf("invalid contractID, expected hex address") + return nil, errors.Errorf("invalid contractID, expected hex address") } routerContractAddress := common.HexToAddress(args.ContractID) - contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) - if err != nil { - return nil, pkgerrors.Wrap(err, "could not get contract ABI JSON") - } cp, err := functionsRelay.NewFunctionsConfigPoller(pluginType, chain.LogPoller(), lggr) if err != nil { @@ -159,10 +151,10 @@ func newFunctionsConfigProvider(pluginType functionsRelay.FunctionsPluginType, c offchainConfigDigester := functionsRelay.NewFunctionsOffchainConfigDigester(pluginType, chain.ID().Uint64()) logPollerWrapper.SubscribeToUpdates("FunctionsOffchainConfigDigester", offchainConfigDigester) - return newConfigWatcher(lggr, routerContractAddress, contractABI, offchainConfigDigester, cp, chain, fromBlock, args.New), nil + return newConfigWatcher(lggr, routerContractAddress, offchainConfigDigester, cp, chain, fromBlock, args.New), nil } -func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.RelayArgs, transmitterID string, configWatcher *configWatcher, ethKeystore keystore.Eth, logPollerWrapper evmRelayTypes.LogPollerWrapper, lggr logger.Logger) (ContractTransmitter, error) { +func newFunctionsContractTransmitter(ctx context.Context, contractVersion uint32, rargs commontypes.RelayArgs, transmitterID string, configWatcher *configWatcher, ethKeystore keystore.Eth, logPollerWrapper evmRelayTypes.LogPollerWrapper, lggr logger.Logger) (ContractTransmitter, error) { var relayConfig evmRelayTypes.RelayConfig if err := json.Unmarshal(rargs.RelayConfig, &relayConfig); err != nil { return nil, err @@ -170,23 +162,23 @@ func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.R var fromAddresses []common.Address sendingKeys := relayConfig.SendingKeys if !relayConfig.EffectiveTransmitterID.Valid { - return nil, pkgerrors.New("EffectiveTransmitterID must be specified") + return nil, errors.New("EffectiveTransmitterID must be specified") } effectiveTransmitterAddress := common.HexToAddress(relayConfig.EffectiveTransmitterID.String) sendingKeysLength := len(sendingKeys) if sendingKeysLength == 0 { - return nil, pkgerrors.New("no sending keys provided") + return nil, errors.New("no sending keys provided") } // If we are using multiple sending keys, then a forwarder is needed to rotate transmissions. // Ensure that this forwarder is not set to a local sending key, and ensure our sending keys are enabled. for _, s := range sendingKeys { if sendingKeysLength > 1 && s == effectiveTransmitterAddress.String() { - return nil, pkgerrors.New("the transmitter is a local sending key with transaction forwarding enabled") + return nil, errors.New("the transmitter is a local sending key with transaction forwarding enabled") } - if err := ethKeystore.CheckEnabled(common.HexToAddress(s), configWatcher.chain.Config().EVM().ChainID()); err != nil { - return nil, pkgerrors.Wrap(err, "one of the sending keys given is not enabled") + if err := ethKeystore.CheckEnabled(ctx, common.HexToAddress(s), configWatcher.chain.Config().EVM().ChainID()); err != nil { + return nil, errors.Wrap(err, "one of the sending keys given is not enabled") } fromAddresses = append(fromAddresses, common.HexToAddress(s)) } @@ -217,12 +209,12 @@ func newFunctionsContractTransmitter(contractVersion uint32, rargs commontypes.R ) if err != nil { - return nil, pkgerrors.Wrap(err, "failed to create transmitter") + return nil, errors.Wrap(err, "failed to create transmitter") } functionsTransmitter, err := functionsRelay.NewFunctionsContractTransmitter( configWatcher.chain.Client(), - configWatcher.contractABI, + OCR2AggregatorTransmissionContractABI, transmitter, configWatcher.chain.LogPoller(), lggr, diff --git a/core/services/relay/evm/functions/config_poller.go b/core/services/relay/evm/functions/config_poller.go index a1975171fd7..7a59d499898 100644 --- a/core/services/relay/evm/functions/config_poller.go +++ b/core/services/relay/evm/functions/config_poller.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2/types" @@ -58,7 +58,7 @@ func unpackLogData(d []byte) (*ocr2aggregator.OCR2AggregatorConfigSet, error) { unpacked := new(ocr2aggregator.OCR2AggregatorConfigSet) err := defaultABI.UnpackIntoInterface(unpacked, configSetEventName, d) if err != nil { - return nil, pkgerrors.Wrap(err, "failed to unpack log data") + return nil, errors.Wrap(err, "failed to unpack log data") } return unpacked, nil } @@ -88,7 +88,7 @@ func configFromLog(logData []byte, pluginType FunctionsPluginType) (ocrtypes.Con case S4Plugin: binary.BigEndian.PutUint16(unpacked.ConfigDigest[:2], uint16(S4DigestPrefix)) default: - return ocrtypes.ContractConfig{}, pkgerrors.New("unknown plugin type") + return ocrtypes.ContractConfig{}, errors.New("unknown plugin type") } return ocrtypes.ContractConfig{ @@ -138,7 +138,7 @@ func (cp *configPoller) LatestConfigDetails(ctx context.Context) (changedInBlock latest, err := cp.destChainLogPoller.LatestLogByEventSigWithConfs(ConfigSet, *contractAddr, 1, pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { return 0, ocrtypes.ConfigDigest{}, nil } return 0, ocrtypes.ConfigDigest{}, err @@ -155,7 +155,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) // (unlikely), we'll return an error here and libocr will re-try. contractAddr := cp.targetContract.Load() if contractAddr == nil { - return ocrtypes.ContractConfig{}, pkgerrors.New("no target contract address set yet") + return ocrtypes.ContractConfig{}, errors.New("no target contract address set yet") } lgs, err := cp.destChainLogPoller.Logs(int64(changedInBlock), int64(changedInBlock), ConfigSet, *contractAddr, pg.WithParentCtx(ctx)) @@ -163,7 +163,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) return ocrtypes.ContractConfig{}, err } if len(lgs) == 0 { - return ocrtypes.ContractConfig{}, pkgerrors.New("no logs found") + return ocrtypes.ContractConfig{}, errors.New("no logs found") } latestConfigSet, err := configFromLog(lgs[len(lgs)-1].Data, cp.pluginType) if err != nil { @@ -176,7 +176,7 @@ func (cp *configPoller) LatestConfig(ctx context.Context, changedInBlock uint64) func (cp *configPoller) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { latest, err := cp.destChainLogPoller.LatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { return 0, nil } return 0, err diff --git a/core/services/relay/evm/functions/config_poller_test.go b/core/services/relay/evm/functions/config_poller_test.go index 2cf373d2e86..6a8c682a81b 100644 --- a/core/services/relay/evm/functions/config_poller_test.go +++ b/core/services/relay/evm/functions/config_poller_test.go @@ -81,7 +81,7 @@ func runTest(t *testing.T, pluginType functions.FunctionsPluginType, expectedDig defer ethClient.Close() lggr := logger.TestLogger(t) lorm := logpoller.NewORM(big.NewInt(1337), db, lggr, cfg) - lp := logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000) + lp := logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000, 0) servicetest.Run(t, lp) configPoller, err := functions.NewFunctionsConfigPoller(pluginType, lp, lggr) require.NoError(t, err) diff --git a/core/services/relay/evm/functions/contract_transmitter.go b/core/services/relay/evm/functions/contract_transmitter.go index 672179c2506..78a5ff39bb7 100644 --- a/core/services/relay/evm/functions/contract_transmitter.go +++ b/core/services/relay/evm/functions/contract_transmitter.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -73,7 +73,7 @@ func NewFunctionsContractTransmitter( ) (*contractTransmitter, error) { transmitted, ok := contractABI.Events["Transmitted"] if !ok { - return nil, pkgerrors.New("invalid ABI, missing transmitted") + return nil, errors.New("invalid ABI, missing transmitted") } if contractVersion != 1 { @@ -106,7 +106,7 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. var ss [][32]byte var vs [32]byte if len(signatures) > 32 { - return pkgerrors.New("too many signatures, maximum is 32") + return errors.New("too many signatures, maximum is 32") } for i, as := range signatures { r, s, v, err := evmutil.SplitSignature(as.Signature) @@ -125,21 +125,22 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. } var destinationContract common.Address - if oc.contractVersion == 1 { + switch oc.contractVersion { + case 1: oc.lggr.Debugw("FunctionsContractTransmitter: start", "reportLenBytes", len(report)) requests, err2 := oc.reportCodec.DecodeReport(report) if err2 != nil { - return pkgerrors.Wrap(err2, "FunctionsContractTransmitter: DecodeReport failed") + return errors.Wrap(err2, "FunctionsContractTransmitter: DecodeReport failed") } if len(requests) == 0 { - return pkgerrors.New("FunctionsContractTransmitter: no requests in report") + return errors.New("FunctionsContractTransmitter: no requests in report") } if len(requests[0].CoordinatorContract) != common.AddressLength { return fmt.Errorf("FunctionsContractTransmitter: incorrect length of CoordinatorContract field: %d", len(requests[0].CoordinatorContract)) } destinationContract.SetBytes(requests[0].CoordinatorContract) if destinationContract == (common.Address{}) { - return pkgerrors.New("FunctionsContractTransmitter: destination coordinator contract is zero") + return errors.New("FunctionsContractTransmitter: destination coordinator contract is zero") } // Sanity check - every report should contain requests with the same coordinator contract. for _, req := range requests[1:] { @@ -152,16 +153,16 @@ func (oc *contractTransmitter) Transmit(ctx context.Context, reportCtx ocrtypes. } } oc.lggr.Debugw("FunctionsContractTransmitter: ready", "nRequests", len(requests), "coordinatorContract", destinationContract.Hex()) - } else { + default: return fmt.Errorf("unsupported contract version: %d", oc.contractVersion) } payload, err := oc.contractABI.Pack("transmit", rawReportCtx, []byte(report), rs, ss, vs) if err != nil { - return pkgerrors.Wrap(err, "abi.Pack failed") + return errors.Wrap(err, "abi.Pack failed") } oc.lggr.Debugw("FunctionsContractTransmitter: transmitting report", "contractAddress", destinationContract, "txMeta", txMeta, "payloadSize", len(payload)) - return pkgerrors.Wrap(oc.transmitter.CreateEthTransaction(ctx, destinationContract, payload, txMeta), "failed to send Eth transaction") + return errors.Wrap(oc.transmitter.CreateEthTransaction(ctx, destinationContract, payload, txMeta), "failed to send Eth transaction") } type contractReader interface { @@ -184,7 +185,7 @@ func parseTransmitted(log []byte) ([32]byte, uint32, error) { return [32]byte{}, 0, err } if len(transmitted) < 2 { - return [32]byte{}, 0, pkgerrors.New("transmitted event log has too few arguments") + return [32]byte{}, 0, errors.New("transmitted event log has too few arguments") } configDigest := *abi.ConvertType(transmitted[0], new([32]byte)).(*[32]byte) epoch := *abi.ConvertType(transmitted[1], new(uint32)).(*uint32) @@ -209,7 +210,7 @@ func callContract(ctx context.Context, addr common.Address, contractABI abi.ABI, func (oc *contractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) (ocrtypes.ConfigDigest, uint32, error) { contractAddr := oc.contractAddress.Load() if contractAddr == nil { - return ocrtypes.ConfigDigest{}, 0, pkgerrors.New("destination contract address not set") + return ocrtypes.ConfigDigest{}, 0, errors.New("destination contract address not set") } latestConfigDigestAndEpoch, err := callContract(ctx, *contractAddr, oc.contractABI, "latestConfigDigestAndEpoch", nil, oc.contractReader) if err != nil { @@ -230,7 +231,7 @@ func (oc *contractTransmitter) LatestConfigDigestAndEpoch(ctx context.Context) ( latest, err := oc.lp.LatestLogByEventSigWithConfs( oc.transmittedEventSig, *contractAddr, 1, pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { // No transmissions yet return configDigest, 0, nil } diff --git a/core/services/relay/evm/functions/logpoller_wrapper.go b/core/services/relay/evm/functions/logpoller_wrapper.go index a9da88deedc..f11b6bee1e0 100644 --- a/core/services/relay/evm/functions/logpoller_wrapper.go +++ b/core/services/relay/evm/functions/logpoller_wrapper.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -92,7 +92,7 @@ func NewLogPollerWrapper(routerContractAddress common.Address, pluginConfig conf } if blockOffset >= pastBlocksToPoll || requestBlockOffset >= pastBlocksToPoll || responseBlockOffset >= pastBlocksToPoll { lggr.Errorw("invalid config: number of required confirmation blocks >= pastBlocksToPoll", "pastBlocksToPoll", pastBlocksToPoll, "minIncomingConfirmations", pluginConfig.MinIncomingConfirmations, "minRequestConfirmations", pluginConfig.MinRequestConfirmations, "minResponseConfirmations", pluginConfig.MinResponseConfirmations) - return nil, pkgerrors.Errorf("invalid config: number of required confirmation blocks >= pastBlocksToPoll") + return nil, errors.Errorf("invalid config: number of required confirmation blocks >= pastBlocksToPoll") } return &logPollerWrapper{ @@ -118,7 +118,7 @@ func (l *logPollerWrapper) Start(context.Context) error { l.mu.Lock() defer l.mu.Unlock() if l.pluginConfig.ContractVersion != 1 { - return pkgerrors.New("only contract version 1 is supported") + return errors.New("only contract version 1 is supported") } l.closeWait.Add(1) go l.checkForRouteUpdates() @@ -168,7 +168,7 @@ func (l *logPollerWrapper) LatestEvents() ([]evmRelayTypes.OracleRequest, []evmR resultsResp := []evmRelayTypes.OracleResponse{} if len(coordinators) == 0 { l.lggr.Debug("LatestEvents: no non-zero coordinators to check") - return resultsReq, resultsResp, pkgerrors.New("no non-zero coordinators to check") + return resultsReq, resultsResp, errors.New("no non-zero coordinators to check") } for _, coordinator := range coordinators { @@ -304,12 +304,11 @@ func (l *logPollerWrapper) filterPreviouslyDetectedEvents(logs []logpoller.Log, expiredRequests := 0 for _, detectedEvent := range detectedEvents.detectedEventsOrdered { expirationTime := time.Now().Add(-time.Second * time.Duration(l.logPollerCacheDurationSec)) - if detectedEvent.timeDetected.Before(expirationTime) { - delete(detectedEvents.isPreviouslyDetected, detectedEvent.requestId) - expiredRequests++ - } else { + if !detectedEvent.timeDetected.Before(expirationTime) { break } + delete(detectedEvents.isPreviouslyDetected, detectedEvent.requestId) + expiredRequests++ } detectedEvents.detectedEventsOrdered = detectedEvents.detectedEventsOrdered[expiredRequests:] l.lggr.Debugw("filterPreviouslyDetectedEvents: done", "filterType", filterType, "nLogs", len(logs), "nFilteredLogs", len(filteredLogs), "nExpiredRequests", expiredRequests, "previouslyDetectedCacheSize", len(detectedEvents.detectedEventsOrdered)) diff --git a/core/services/relay/evm/median.go b/core/services/relay/evm/median.go index 756dc56371f..e3200d8e867 100644 --- a/core/services/relay/evm/median.go +++ b/core/services/relay/evm/median.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2/reportingplugin/median" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -34,17 +34,17 @@ func newMedianContract(configTracker types.ContractConfigTracker, contractAddres lggr = lggr.Named("MedianContract") contract, err := offchain_aggregator_wrapper.NewOffchainAggregator(contractAddress, chain.Client()) if err != nil { - return nil, pkgerrors.Wrap(err, "could not instantiate NewOffchainAggregator") + return nil, errors.Wrap(err, "could not instantiate NewOffchainAggregator") } contractFilterer, err := ocr2aggregator.NewOCR2AggregatorFilterer(contractAddress, chain.Client()) if err != nil { - return nil, pkgerrors.Wrap(err, "could not instantiate NewOffchainAggregatorFilterer") + return nil, errors.Wrap(err, "could not instantiate NewOffchainAggregatorFilterer") } contractCaller, err := ocr2aggregator.NewOCR2AggregatorCaller(contractAddress, chain.Client()) if err != nil { - return nil, pkgerrors.Wrap(err, "could not instantiate NewOffchainAggregatorCaller") + return nil, errors.Wrap(err, "could not instantiate NewOffchainAggregatorCaller") } return &medianContract{ @@ -86,7 +86,7 @@ func (oc *medianContract) HealthReport() map[string]error { func (oc *medianContract) LatestTransmissionDetails(ctx context.Context) (ocrtypes.ConfigDigest, uint32, uint8, *big.Int, time.Time, error) { opts := bind.CallOpts{Context: ctx, Pending: false} result, err := oc.contractCaller.LatestTransmissionDetails(&opts) - return result.ConfigDigest, result.Epoch, result.Round, result.LatestAnswer, time.Unix(int64(result.LatestTimestamp), 0), pkgerrors.Wrap(err, "error getting LatestTransmissionDetails") + return result.ConfigDigest, result.Epoch, result.Round, result.LatestAnswer, time.Unix(int64(result.LatestTimestamp), 0), errors.Wrap(err, "error getting LatestTransmissionDetails") } // LatestRoundRequested returns the configDigest, epoch, and round from the latest diff --git a/core/services/relay/evm/mercury/config_digest.go b/core/services/relay/evm/mercury/config_digest.go index b9431fe923f..291a723ee3a 100644 --- a/core/services/relay/evm/mercury/config_digest.go +++ b/core/services/relay/evm/mercury/config_digest.go @@ -61,7 +61,7 @@ func configDigest( panic("copy too little data") } binary.BigEndian.PutUint16(configDigest[:2], uint16(types.ConfigDigestPrefixMercuryV02)) - if !(configDigest[0] == 0 || configDigest[1] == 6) { + if !(configDigest[0] == 0 && configDigest[1] == 6) { // assertion panic("unexpected mismatch") } diff --git a/core/services/relay/evm/mercury/config_poller.go b/core/services/relay/evm/mercury/config_poller.go index dbc29754fed..98ef78020c7 100644 --- a/core/services/relay/evm/mercury/config_poller.go +++ b/core/services/relay/evm/mercury/config_poller.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" @@ -48,7 +48,7 @@ func unpackLogData(d []byte) (*verifier.VerifierConfigSet, error) { err := verifierABI.UnpackIntoInterface(unpacked, configSetEventName, d) if err != nil { - return nil, pkgerrors.Wrap(err, "failed to unpack log data") + return nil, errors.Wrap(err, "failed to unpack log data") } return unpacked, nil @@ -168,7 +168,7 @@ func (cp *ConfigPoller) LatestConfig(ctx context.Context, changedInBlock uint64) func (cp *ConfigPoller) LatestBlockHeight(ctx context.Context) (blockHeight uint64, err error) { latest, err := cp.destChainLogPoller.LatestBlock(pg.WithParentCtx(ctx)) if err != nil { - if pkgerrors.Is(err, sql.ErrNoRows) { + if errors.Is(err, sql.ErrNoRows) { return 0, nil } return 0, err diff --git a/core/services/relay/evm/mercury/config_poller_test.go b/core/services/relay/evm/mercury/config_poller_test.go index 44c61712b6d..f828938f954 100644 --- a/core/services/relay/evm/mercury/config_poller_test.go +++ b/core/services/relay/evm/mercury/config_poller_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/onsi/gomega" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" confighelper2 "github.com/smartcontractkit/libocr/offchainreporting2plus/confighelper" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -115,7 +115,7 @@ func TestMercuryConfigPoller(t *testing.T) { func onchainPublicKeyToAddress(publicKeys []types.OnchainPublicKey) (addresses []common.Address, err error) { for _, signer := range publicKeys { if len(signer) != 20 { - return []common.Address{}, pkgerrors.Errorf("address is not 20 bytes %s", signer) + return []common.Address{}, errors.Errorf("address is not 20 bytes %s", signer) } addresses = append(addresses, common.BytesToAddress(signer)) } diff --git a/core/services/relay/evm/mercury/helpers_test.go b/core/services/relay/evm/mercury/helpers_test.go index f1686ee00c8..8283e80916e 100644 --- a/core/services/relay/evm/mercury/helpers_test.go +++ b/core/services/relay/evm/mercury/helpers_test.go @@ -167,7 +167,7 @@ func SetupTH(t *testing.T, feedID common.Hash) TestHarness { ethClient := evmclient.NewSimulatedBackendClient(t, b, big.NewInt(1337)) lggr := logger.TestLogger(t) lorm := logpoller.NewORM(big.NewInt(1337), db, lggr, cfg) - lp := logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000) + lp := logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000, 0) servicetest.Run(t, lp) configPoller, err := NewConfigPoller(lggr, lp, verifierAddress, feedID) diff --git a/core/services/relay/evm/mercury/offchain_config_digester.go b/core/services/relay/evm/mercury/offchain_config_digester.go index 5188605d0e5..f9ba0b23095 100644 --- a/core/services/relay/evm/mercury/offchain_config_digester.go +++ b/core/services/relay/evm/mercury/offchain_config_digester.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/wsrpc/credentials" @@ -32,7 +32,7 @@ func (d OffchainConfigDigester) ConfigDigest(cc ocrtypes.ContractConfig) (ocrtyp signers := []common.Address{} for i, signer := range cc.Signers { if len(signer) != 20 { - return ocrtypes.ConfigDigest{}, pkgerrors.Errorf("%v-th evm signer should be a 20 byte address, but got %x", i, signer) + return ocrtypes.ConfigDigest{}, errors.Errorf("%v-th evm signer should be a 20 byte address, but got %x", i, signer) } a := common.BytesToAddress(signer) signers = append(signers, a) @@ -40,12 +40,12 @@ func (d OffchainConfigDigester) ConfigDigest(cc ocrtypes.ContractConfig) (ocrtyp transmitters := []credentials.StaticSizedPublicKey{} for i, transmitter := range cc.Transmitters { if len(transmitter) != 2*ed25519.PublicKeySize { - return ocrtypes.ConfigDigest{}, pkgerrors.Errorf("%v-th evm transmitter should be a 64 character hex-encoded ed25519 public key, but got '%v' (%d chars)", i, transmitter, len(transmitter)) + return ocrtypes.ConfigDigest{}, errors.Errorf("%v-th evm transmitter should be a 64 character hex-encoded ed25519 public key, but got '%v' (%d chars)", i, transmitter, len(transmitter)) } var t credentials.StaticSizedPublicKey b, err := hex.DecodeString(string(transmitter)) if err != nil { - return ocrtypes.ConfigDigest{}, pkgerrors.Wrapf(err, "%v-th evm transmitter is not valid hex, got: %q", i, transmitter) + return ocrtypes.ConfigDigest{}, errors.Wrapf(err, "%v-th evm transmitter is not valid hex, got: %q", i, transmitter) } copy(t[:], b) diff --git a/core/services/relay/evm/mercury/transmitter.go b/core/services/relay/evm/mercury/transmitter.go index 6a4bfeb6dd0..9444b904b89 100644 --- a/core/services/relay/evm/mercury/transmitter.go +++ b/core/services/relay/evm/mercury/transmitter.go @@ -108,7 +108,6 @@ type mercuryTransmitter struct { services.StateMachine lggr logger.Logger rpcClient wsrpc.Client - cfgTracker ConfigTracker persistenceManager *PersistenceManager codec TransmitterReportDecoder @@ -149,14 +148,13 @@ func getPayloadTypes() abi.Arguments { }) } -func NewTransmitter(lggr logger.Logger, cfgTracker ConfigTracker, rpcClient wsrpc.Client, fromAccount ed25519.PublicKey, jobID int32, feedID [32]byte, db *sqlx.DB, cfg pg.QConfig, codec TransmitterReportDecoder) *mercuryTransmitter { +func NewTransmitter(lggr logger.Logger, rpcClient wsrpc.Client, fromAccount ed25519.PublicKey, jobID int32, feedID [32]byte, db *sqlx.DB, cfg pg.QConfig, codec TransmitterReportDecoder) *mercuryTransmitter { feedIDHex := fmt.Sprintf("0x%x", feedID[:]) persistenceManager := NewPersistenceManager(lggr, NewORM(db, lggr, cfg), jobID, maxTransmitQueueSize, flushDeletesFrequency, pruneFrequency) return &mercuryTransmitter{ services.StateMachine{}, lggr.Named("MercuryTransmitter").With("feedID", feedIDHex), rpcClient, - cfgTracker, persistenceManager, codec, feedID, diff --git a/core/services/relay/evm/mercury/transmitter_test.go b/core/services/relay/evm/mercury/transmitter_test.go index 3be9fa0f407..188beff5113 100644 --- a/core/services/relay/evm/mercury/transmitter_test.go +++ b/core/services/relay/evm/mercury/transmitter_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/common/hexutil" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -27,6 +27,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { pgtest.MustExec(t, db, `SET CONSTRAINTS mercury_transmit_requests_job_id_fkey DEFERRED`) pgtest.MustExec(t, db, `SET CONSTRAINTS feed_latest_reports_job_id_fkey DEFERRED`) q := NewTransmitQueue(lggr, "", 0, nil, nil) + codec := new(mockCodec) t.Run("v1 report transmission successfully enqueued", func(t *testing.T) { report := sampleV1Report @@ -40,7 +41,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) mt.queue = q err := mt.Transmit(testutils.Context(t), sampleReportContext, report, sampleSigs) @@ -58,7 +59,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) mt.queue = q err := mt.Transmit(testutils.Context(t), sampleReportContext, report, sampleSigs) @@ -76,7 +77,7 @@ func Test_MercuryTransmitter_Transmit(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) mt.queue = q err := mt.Transmit(testutils.Context(t), sampleReportContext, report, sampleSigs) @@ -88,6 +89,8 @@ func Test_MercuryTransmitter_LatestTimestamp(t *testing.T) { t.Parallel() lggr := logger.TestLogger(t) db := pgtest.NewSqlxDB(t) + var jobID int32 + codec := new(mockCodec) t.Run("successful query", func(t *testing.T) { c := mocks.MockWSRPCClient{ @@ -101,7 +104,7 @@ func Test_MercuryTransmitter_LatestTimestamp(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) ts, err := mt.LatestTimestamp(testutils.Context(t)) require.NoError(t, err) @@ -116,7 +119,7 @@ func Test_MercuryTransmitter_LatestTimestamp(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) ts, err := mt.LatestTimestamp(testutils.Context(t)) require.NoError(t, err) @@ -126,10 +129,10 @@ func Test_MercuryTransmitter_LatestTimestamp(t *testing.T) { t.Run("failing query", func(t *testing.T) { c := mocks.MockWSRPCClient{ LatestReportF: func(ctx context.Context, in *pb.LatestReportRequest) (out *pb.LatestReportResponse, err error) { - return nil, pkgerrors.New("something exploded") + return nil, errors.New("something exploded") }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) _, err := mt.LatestTimestamp(testutils.Context(t)) require.Error(t, err) assert.Contains(t, err.Error(), "something exploded") @@ -151,6 +154,7 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { t.Parallel() lggr := logger.TestLogger(t) db := pgtest.NewSqlxDB(t) + var jobID int32 codec := new(mockCodec) @@ -167,7 +171,7 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), codec) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) t.Run("BenchmarkPriceFromReport succeeds", func(t *testing.T) { codec.val = originalPrice @@ -180,7 +184,7 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { }) t.Run("BenchmarkPriceFromReport fails", func(t *testing.T) { codec.val = nil - codec.err = pkgerrors.New("something exploded") + codec.err = errors.New("something exploded") _, err := mt.LatestPrice(testutils.Context(t), sampleFeedID) require.Error(t, err) @@ -197,7 +201,7 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) price, err := mt.LatestPrice(testutils.Context(t), sampleFeedID) require.NoError(t, err) @@ -207,10 +211,10 @@ func Test_MercuryTransmitter_LatestPrice(t *testing.T) { t.Run("failing query", func(t *testing.T) { c := mocks.MockWSRPCClient{ LatestReportF: func(ctx context.Context, in *pb.LatestReportRequest) (out *pb.LatestReportResponse, err error) { - return nil, pkgerrors.New("something exploded") + return nil, errors.New("something exploded") }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) _, err := mt.LatestPrice(testutils.Context(t), sampleFeedID) require.Error(t, err) assert.Contains(t, err.Error(), "something exploded") @@ -222,6 +226,8 @@ func Test_MercuryTransmitter_FetchInitialMaxFinalizedBlockNumber(t *testing.T) { lggr := logger.TestLogger(t) db := pgtest.NewSqlxDB(t) + var jobID int32 + codec := new(mockCodec) t.Run("successful query", func(t *testing.T) { c := mocks.MockWSRPCClient{ @@ -235,7 +241,7 @@ func Test_MercuryTransmitter_FetchInitialMaxFinalizedBlockNumber(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) bn, err := mt.FetchInitialMaxFinalizedBlockNumber(testutils.Context(t)) require.NoError(t, err) @@ -250,7 +256,7 @@ func Test_MercuryTransmitter_FetchInitialMaxFinalizedBlockNumber(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, jobID, sampleFeedID, db, pgtest.NewQConfig(true), codec) bn, err := mt.FetchInitialMaxFinalizedBlockNumber(testutils.Context(t)) require.NoError(t, err) @@ -259,10 +265,10 @@ func Test_MercuryTransmitter_FetchInitialMaxFinalizedBlockNumber(t *testing.T) { t.Run("failing query", func(t *testing.T) { c := mocks.MockWSRPCClient{ LatestReportF: func(ctx context.Context, in *pb.LatestReportRequest) (out *pb.LatestReportResponse, err error) { - return nil, pkgerrors.New("something exploded") + return nil, errors.New("something exploded") }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), codec) _, err := mt.FetchInitialMaxFinalizedBlockNumber(testutils.Context(t)) require.Error(t, err) assert.Contains(t, err.Error(), "something exploded") @@ -279,7 +285,7 @@ func Test_MercuryTransmitter_FetchInitialMaxFinalizedBlockNumber(t *testing.T) { return out, nil }, } - mt := NewTransmitter(lggr, nil, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), nil) + mt := NewTransmitter(lggr, c, sampleClientPubKey, 0, sampleFeedID, db, pgtest.NewQConfig(true), codec) _, err := mt.FetchInitialMaxFinalizedBlockNumber(testutils.Context(t)) require.Error(t, err) assert.Contains(t, err.Error(), "latestReport failed; mismatched feed IDs, expected: 0x1c916b4aa7e57ca7b68ae1bf45653f56b656fd3aa335ef7fae696b663f1b8472, got: 0x") diff --git a/core/services/relay/evm/mercury/v1/data_source_test.go b/core/services/relay/evm/mercury/v1/data_source_test.go index c96030297d7..e0769fe5b64 100644 --- a/core/services/relay/evm/mercury/v1/data_source_test.go +++ b/core/services/relay/evm/mercury/v1/data_source_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -140,7 +140,7 @@ func TestMercury_Observe(t *testing.T) { }) t.Run("if querying latest report fails", func(t *testing.T) { orm.report = nil - orm.err = pkgerrors.New("something exploded") + orm.err = errors.New("something exploded") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -164,7 +164,7 @@ func TestMercury_Observe(t *testing.T) { t.Run("without latest report in database", func(t *testing.T) { t.Run("if FetchInitialMaxFinalizedBlockNumber returns error", func(t *testing.T) { - fetcher.err = pkgerrors.New("mock fetcher error") + fetcher.err = errors.New("mock fetcher error") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -228,7 +228,7 @@ func TestMercury_Observe(t *testing.T) { t.Cleanup(func() { runner.Err = nil }) - runner.Err = pkgerrors.New("run execution failed") + runner.Err = errors.New("run execution failed") _, err := ds.Observe(ctx, repts, false) assert.EqualError(t, err, "Observe failed while executing run: error executing run for spec ID 0: run execution failed") diff --git a/core/services/relay/evm/mercury/v2/data_source_test.go b/core/services/relay/evm/mercury/v2/data_source_test.go index df736f76428..c9ae37ae018 100644 --- a/core/services/relay/evm/mercury/v2/data_source_test.go +++ b/core/services/relay/evm/mercury/v2/data_source_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -111,7 +111,7 @@ func Test_Datasource(t *testing.T) { }) t.Run("if querying latest report fails", func(t *testing.T) { orm.report = nil - orm.err = pkgerrors.New("something exploded") + orm.err = errors.New("something exploded") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -134,7 +134,7 @@ func Test_Datasource(t *testing.T) { orm.err = nil t.Run("if LatestTimestamp returns error", func(t *testing.T) { - fetcher.tsErr = pkgerrors.New("some error") + fetcher.tsErr = errors.New("some error") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -202,7 +202,7 @@ func Test_Datasource(t *testing.T) { ds.pipelineRunner = &mercurymocks.MockRunner{ Trrs: goodTrrs, - Err: pkgerrors.New("run execution failed"), + Err: errors.New("run execution failed"), } _, err := ds.Observe(ctx, repts, false) @@ -221,7 +221,7 @@ func Test_Datasource(t *testing.T) { badTrrs := []pipeline.TaskRunResult{ { // benchmark price - Result: pipeline.Result{Error: pkgerrors.New("some error with bp")}, + Result: pipeline.Result{Error: errors.New("some error with bp")}, Task: &mercurymocks.MockTask{}, }, } @@ -263,8 +263,8 @@ func Test_Datasource(t *testing.T) { fetcher.nativePriceErr = nil }) - fetcher.linkPriceErr = pkgerrors.New("some error fetching link price") - fetcher.nativePriceErr = pkgerrors.New("some error fetching native price") + fetcher.linkPriceErr = errors.New("some error fetching link price") + fetcher.nativePriceErr = errors.New("some error fetching native price") obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) diff --git a/core/services/relay/evm/mercury/v3/data_source_test.go b/core/services/relay/evm/mercury/v3/data_source_test.go index 27b3c0d62cf..4ff713abb21 100644 --- a/core/services/relay/evm/mercury/v3/data_source_test.go +++ b/core/services/relay/evm/mercury/v3/data_source_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" mercurytypes "github.com/smartcontractkit/chainlink-common/pkg/types/mercury" @@ -121,7 +121,7 @@ func Test_Datasource(t *testing.T) { }) t.Run("if querying latest report fails", func(t *testing.T) { orm.report = nil - orm.err = pkgerrors.New("something exploded") + orm.err = errors.New("something exploded") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -144,7 +144,7 @@ func Test_Datasource(t *testing.T) { orm.err = nil t.Run("if LatestTimestamp returns error", func(t *testing.T) { - fetcher.tsErr = pkgerrors.New("some error") + fetcher.tsErr = errors.New("some error") obs, err := ds.Observe(ctx, repts, true) assert.NoError(t, err) @@ -216,7 +216,7 @@ func Test_Datasource(t *testing.T) { ds.pipelineRunner = &mercurymocks.MockRunner{ Trrs: goodTrrs, - Err: pkgerrors.New("run execution failed"), + Err: errors.New("run execution failed"), } _, err := ds.Observe(ctx, repts, false) @@ -245,7 +245,7 @@ func Test_Datasource(t *testing.T) { }, { // ask - Result: pipeline.Result{Error: pkgerrors.New("some error with ask")}, + Result: pipeline.Result{Error: errors.New("some error with ask")}, Task: &mercurymocks.MockTask{}, }, } @@ -291,8 +291,8 @@ func Test_Datasource(t *testing.T) { fetcher.nativePriceErr = nil }) - fetcher.linkPriceErr = pkgerrors.New("some error fetching link price") - fetcher.nativePriceErr = pkgerrors.New("some error fetching native price") + fetcher.linkPriceErr = errors.New("some error fetching link price") + fetcher.nativePriceErr = errors.New("some error fetching native price") obs, err := ds.Observe(ctx, repts, false) assert.NoError(t, err) diff --git a/core/services/relay/evm/mercury/wsrpc/client.go b/core/services/relay/evm/mercury/wsrpc/client.go index 6812dd44c11..d420a17a1a4 100644 --- a/core/services/relay/evm/mercury/wsrpc/client.go +++ b/core/services/relay/evm/mercury/wsrpc/client.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ethereum/go-ethereum/common/hexutil" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -156,7 +156,7 @@ func (w *client) dial(ctx context.Context, opts ...wsrpc.DialOption) error { if err != nil { w.dialErrorCountMetric.Inc() setLivenessMetric(false) - return pkgerrors.Wrap(err, "failed to dial wsrpc client") + return errors.Wrap(err, "failed to dial wsrpc client") } w.dialSuccessCountMetric.Inc() setLivenessMetric(true) @@ -193,16 +193,16 @@ func (w *client) resetTransport() { b := utils.NewRedialBackoff() for { // Will block until successful dial, or context is canceled (i.e. on close) - if err := w.dial(ctx, wsrpc.WithBlock()); err != nil { - if ctx.Err() != nil { - w.logger.Debugw("ResetTransport exiting due to client Close", "err", err) - return - } - w.logger.Errorw("ResetTransport failed to redial", "err", err) - time.Sleep(b.Duration()) - } else { + err := w.dial(ctx, wsrpc.WithBlock()) + if err == nil { break } + if ctx.Err() != nil { + w.logger.Debugw("ResetTransport exiting due to client Close", "err", err) + return + } + w.logger.Errorw("ResetTransport failed to redial", "err", err) + time.Sleep(b.Duration()) } w.logger.Info("ResetTransport successfully redialled") } @@ -231,7 +231,7 @@ func (w *client) Healthy() (err error) { } state := w.conn.GetState() if state != connectivity.Ready { - return pkgerrors.Errorf("client state should be %s; got %s", connectivity.Ready, state) + return errors.Errorf("client state should be %s; got %s", connectivity.Ready, state) } return nil } @@ -239,12 +239,12 @@ func (w *client) Healthy() (err error) { func (w *client) waitForReady(ctx context.Context) (err error) { ok := w.IfStarted(func() { if ready := w.conn.WaitForReady(ctx); !ready { - err = pkgerrors.Errorf("websocket client not ready; got state: %v", w.conn.GetState()) + err = errors.Errorf("websocket client not ready; got state: %v", w.conn.GetState()) return } }) if !ok { - return pkgerrors.New("client is not started") + return errors.New("client is not started") } return } @@ -253,7 +253,7 @@ func (w *client) Transmit(ctx context.Context, req *pb.TransmitRequest) (resp *p w.logger.Trace("Transmit") start := time.Now() if err = w.waitForReady(ctx); err != nil { - return nil, pkgerrors.Wrap(err, "Transmit call failed") + return nil, errors.Wrap(err, "Transmit call failed") } resp, err = w.rawClient.Transmit(ctx, req) w.handleTimeout(err) @@ -269,7 +269,7 @@ func (w *client) Transmit(ctx context.Context, req *pb.TransmitRequest) (resp *p } func (w *client) handleTimeout(err error) { - if pkgerrors.Is(err, context.DeadlineExceeded) { + if errors.Is(err, context.DeadlineExceeded) { w.timeoutCountMetric.Inc() cnt := w.consecutiveTimeoutCnt.Add(1) if cnt == MaxConsecutiveRequestFailures { @@ -305,7 +305,7 @@ func (w *client) LatestReport(ctx context.Context, req *pb.LatestReportRequest) lggr := w.logger.With("req.FeedId", hexutil.Encode(req.FeedId)) lggr.Trace("LatestReport") if err = w.waitForReady(ctx); err != nil { - return nil, pkgerrors.Wrap(err, "LatestReport failed") + return nil, errors.Wrap(err, "LatestReport failed") } var cached bool if w.cache == nil { diff --git a/core/services/relay/evm/mercury/wsrpc/pb/generate.go b/core/services/relay/evm/mercury/wsrpc/pb/generate.go new file mode 100644 index 00000000000..2bb95012d1c --- /dev/null +++ b/core/services/relay/evm/mercury/wsrpc/pb/generate.go @@ -0,0 +1,2 @@ +//go:generate protoc --go_out=. --go_opt=paths=source_relative --go-wsrpc_out=. --go-wsrpc_opt=paths=source_relative mercury.proto +package pb diff --git a/core/services/relay/evm/mercury/wsrpc/pb/mercury.pb.go b/core/services/relay/evm/mercury/wsrpc/pb/mercury.pb.go index 4ffe41860e6..ab4d2f68dad 100644 --- a/core/services/relay/evm/mercury/wsrpc/pb/mercury.pb.go +++ b/core/services/relay/evm/mercury/wsrpc/pb/mercury.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.30.0 -// protoc v3.21.12 +// protoc-gen-go v1.32.0 +// protoc v4.25.1 // source: mercury.proto package pb @@ -25,7 +25,8 @@ type TransmitRequest struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` + Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` + ReportFormat uint32 `protobuf:"varint,2,opt,name=reportFormat,proto3" json:"reportFormat,omitempty"` } func (x *TransmitRequest) Reset() { @@ -67,6 +68,13 @@ func (x *TransmitRequest) GetPayload() []byte { return nil } +func (x *TransmitRequest) GetReportFormat() uint32 { + if x != nil { + return x.ReportFormat + } + return 0 +} + type TransmitResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -442,73 +450,76 @@ var File_mercury_proto protoreflect.FileDescriptor var file_mercury_proto_rawDesc = []byte{ 0x0a, 0x0d, 0x6d, 0x65, 0x72, 0x63, 0x75, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, - 0x02, 0x70, 0x62, 0x22, 0x2b, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, + 0x02, 0x70, 0x62, 0x22, 0x4f, 0x0a, 0x0f, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, - 0x22, 0x3c, 0x0a, 0x10, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, - 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x2d, - 0x0a, 0x13, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x65, 0x65, 0x64, 0x49, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x66, 0x65, 0x65, 0x64, 0x49, 0x64, 0x22, 0x50, 0x0a, - 0x14, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x22, 0x0a, 0x06, 0x72, - 0x65, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x70, 0x62, - 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x06, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x22, - 0xa1, 0x04, 0x0a, 0x06, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x65, - 0x65, 0x64, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x66, 0x65, 0x65, 0x64, - 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, - 0x6f, 0x61, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, - 0x61, 0x64, 0x12, 0x32, 0x0a, 0x14, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x46, 0x72, 0x6f, 0x6d, 0x42, - 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, - 0x52, 0x14, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x46, 0x72, 0x6f, 0x6d, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x2e, 0x0a, 0x12, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, - 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x03, 0x52, 0x12, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x2a, 0x0a, 0x10, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, - 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x61, 0x73, 0x68, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x10, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x61, - 0x73, 0x68, 0x12, 0x34, 0x0a, 0x15, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, - 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x07, 0x20, 0x01, 0x28, - 0x04, 0x52, 0x15, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x54, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x34, 0x0a, 0x15, 0x6f, 0x62, 0x73, 0x65, - 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, - 0x70, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x22, - 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x69, 0x67, 0x65, 0x73, 0x74, 0x18, 0x09, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x69, 0x67, 0x65, - 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x0a, 0x20, 0x01, 0x28, - 0x0d, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x6f, 0x75, 0x6e, - 0x64, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x12, 0x22, - 0x0a, 0x0c, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x0c, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x4e, 0x61, - 0x6d, 0x65, 0x12, 0x32, 0x0a, 0x14, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x74, 0x69, - 0x6e, 0x67, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x14, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x4f, 0x70, - 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x2b, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x64, 0x41, 0x74, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x70, 0x62, 0x2e, 0x54, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x64, 0x41, 0x74, 0x22, 0x3b, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, - 0x12, 0x18, 0x0a, 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x03, 0x52, 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x61, - 0x6e, 0x6f, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6e, 0x61, 0x6e, 0x6f, 0x73, - 0x32, 0x83, 0x01, 0x0a, 0x07, 0x4d, 0x65, 0x72, 0x63, 0x75, 0x72, 0x79, 0x12, 0x35, 0x0a, 0x08, - 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x12, 0x13, 0x2e, 0x70, 0x62, 0x2e, 0x54, 0x72, - 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, - 0x70, 0x62, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x41, 0x0a, 0x0c, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, - 0x6f, 0x72, 0x74, 0x12, 0x17, 0x2e, 0x70, 0x62, 0x2e, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, - 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x70, - 0x62, 0x2e, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x4e, 0x5a, 0x4c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, - 0x63, 0x74, 0x6b, 0x69, 0x74, 0x2f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x6b, 0x2f, - 0x76, 0x32, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x72, 0x65, 0x6c, 0x61, - 0x79, 0x2f, 0x65, 0x76, 0x6d, 0x2f, 0x6d, 0x65, 0x72, 0x63, 0x75, 0x72, 0x79, 0x2f, 0x77, 0x73, - 0x72, 0x70, 0x63, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x12, 0x22, 0x0a, 0x0c, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0c, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x46, 0x6f, + 0x72, 0x6d, 0x61, 0x74, 0x22, 0x3c, 0x0a, 0x10, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x14, 0x0a, 0x05, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x72, 0x72, + 0x6f, 0x72, 0x22, 0x2d, 0x0a, 0x13, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, + 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x65, 0x65, + 0x64, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x66, 0x65, 0x65, 0x64, 0x49, + 0x64, 0x22, 0x50, 0x0a, 0x14, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, + 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x72, 0x72, + 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, + 0x22, 0x0a, 0x06, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x0a, 0x2e, 0x70, 0x62, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x06, 0x72, 0x65, 0x70, + 0x6f, 0x72, 0x74, 0x22, 0xa1, 0x04, 0x0a, 0x06, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x16, + 0x0a, 0x06, 0x66, 0x65, 0x65, 0x64, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, + 0x66, 0x65, 0x65, 0x64, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x18, 0x0a, 0x07, + 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, + 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x32, 0x0a, 0x14, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x46, + 0x72, 0x6f, 0x6d, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x03, 0x52, 0x14, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x46, 0x72, 0x6f, 0x6d, 0x42, + 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x2e, 0x0a, 0x12, 0x63, 0x75, + 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x12, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, + 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x2a, 0x0a, 0x10, 0x63, 0x75, + 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x61, 0x73, 0x68, 0x18, 0x06, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x10, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x48, 0x61, 0x73, 0x68, 0x12, 0x34, 0x0a, 0x15, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, + 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, + 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x15, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x42, 0x6c, + 0x6f, 0x63, 0x6b, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x34, 0x0a, 0x15, + 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x54, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6f, 0x62, 0x73, + 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, + 0x6d, 0x70, 0x12, 0x22, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x69, 0x67, 0x65, + 0x73, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x44, 0x69, 0x67, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, + 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x14, 0x0a, 0x05, + 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x72, 0x6f, 0x75, + 0x6e, 0x64, 0x12, 0x22, 0x0a, 0x0c, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x4e, 0x61, + 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, + 0x6f, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x32, 0x0a, 0x14, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, + 0x69, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x18, 0x0d, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x14, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x74, 0x69, + 0x6e, 0x67, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x2b, 0x0a, 0x09, 0x63, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, + 0x70, 0x62, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x63, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x22, 0x3b, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x12, 0x14, + 0x0a, 0x05, 0x6e, 0x61, 0x6e, 0x6f, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6e, + 0x61, 0x6e, 0x6f, 0x73, 0x32, 0x83, 0x01, 0x0a, 0x07, 0x4d, 0x65, 0x72, 0x63, 0x75, 0x72, 0x79, + 0x12, 0x35, 0x0a, 0x08, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x12, 0x13, 0x2e, 0x70, + 0x62, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x14, 0x2e, 0x70, 0x62, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x74, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x41, 0x0a, 0x0c, 0x4c, 0x61, 0x74, 0x65, 0x73, + 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x17, 0x2e, 0x70, 0x62, 0x2e, 0x4c, 0x61, 0x74, + 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x18, 0x2e, 0x70, 0x62, 0x2e, 0x4c, 0x61, 0x74, 0x65, 0x73, 0x74, 0x52, 0x65, 0x70, 0x6f, + 0x72, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x4e, 0x5a, 0x4c, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x63, 0x6f, + 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x6b, 0x69, 0x74, 0x2f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x6c, + 0x69, 0x6e, 0x6b, 0x2f, 0x76, 0x32, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, + 0x72, 0x65, 0x6c, 0x61, 0x79, 0x2f, 0x65, 0x76, 0x6d, 0x2f, 0x6d, 0x65, 0x72, 0x63, 0x75, 0x72, + 0x79, 0x2f, 0x77, 0x73, 0x72, 0x70, 0x63, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x33, } var ( diff --git a/core/services/relay/evm/mercury/wsrpc/pb/mercury.proto b/core/services/relay/evm/mercury/wsrpc/pb/mercury.proto index 184b0572046..6b71404a6a6 100644 --- a/core/services/relay/evm/mercury/wsrpc/pb/mercury.proto +++ b/core/services/relay/evm/mercury/wsrpc/pb/mercury.proto @@ -11,7 +11,7 @@ service Mercury { message TransmitRequest { bytes payload = 1; - string reportFormat = 2; + uint32 reportFormat = 2; } message TransmitResponse { diff --git a/core/services/relay/evm/mercury/wsrpc/pb/mercury_wsrpc.pb.go b/core/services/relay/evm/mercury/wsrpc/pb/mercury_wsrpc.pb.go index 23c78abf533..0c31a1d7ac9 100644 --- a/core/services/relay/evm/mercury/wsrpc/pb/mercury_wsrpc.pb.go +++ b/core/services/relay/evm/mercury/wsrpc/pb/mercury_wsrpc.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go-wsrpc. DO NOT EDIT. // versions: // - protoc-gen-go-wsrpc v0.0.1 -// - protoc v4.23.2 +// - protoc v4.25.1 package pb diff --git a/core/services/relay/evm/ocr2keeper.go b/core/services/relay/evm/ocr2keeper.go index efb518f73ea..6563604945c 100644 --- a/core/services/relay/evm/ocr2keeper.go +++ b/core/services/relay/evm/ocr2keeper.go @@ -4,36 +4,30 @@ import ( "context" "encoding/json" "fmt" - "strings" - iregistry21 "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/i_keeper_registry_master_wrapper_2_1" - "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" - evm "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21" - "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding" - "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider" - "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/transmit" - "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" - - "github.com/smartcontractkit/chainlink-common/pkg/types/automation" - - "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" - "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-automation/pkg/v3/plugin" - commontypes "github.com/smartcontractkit/chainlink-common/pkg/types" + "github.com/smartcontractkit/chainlink-common/pkg/types/automation" "github.com/smartcontractkit/chainlink/v2/core/chains/legacyevm" + iregistry21 "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/i_keeper_registry_master_wrapper_2_1" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" + "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" + evm "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/encoding" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/logprovider" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/transmit" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate" + "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/types" ) @@ -90,13 +84,17 @@ func NewOCR2KeeperRelayer(db *sqlx.DB, chain legacyevm.Chain, lggr logger.Logger } func (r *ocr2keeperRelayer) NewOCR2KeeperProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (OCR2KeeperProvider, error) { + + // TODO https://smartcontract-it.atlassian.net/browse/BCF-2887 + ctx := context.Background() + cfgWatcher, err := newOCR2KeeperConfigProvider(r.lggr, r.chain, rargs) if err != nil { return nil, err } gasLimit := cfgWatcher.chain.Config().EVM().OCR2().Automation().GasLimit() - contractTransmitter, err := newContractTransmitter(r.lggr, rargs, pargs.TransmitterID, r.ethKeystore, cfgWatcher, configTransmitterOpts{pluginGasLimit: &gasLimit}) + contractTransmitter, err := newOnChainContractTransmitter(ctx, r.lggr, rargs, pargs.TransmitterID, r.ethKeystore, cfgWatcher, configTransmitterOpts{pluginGasLimit: &gasLimit}, OCR2AggregatorTransmissionContractABI) if err != nil { return nil, err } @@ -221,21 +219,20 @@ func newOCR2KeeperConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rarg } contractAddress := common.HexToAddress(rargs.ContractID) - contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorMetaData.ABI)) - if err != nil { - return nil, pkgerrors.Wrap(err, "could not get OCR2Aggregator ABI JSON") - } configPoller, err := NewConfigPoller( lggr.With("contractID", rargs.ContractID), - chain.Client(), - chain.LogPoller(), - contractAddress, - // TODO: Does ocr2keeper need to support config contract? DF-19182 - nil, + CPConfig{ + chain.Client(), + chain.LogPoller(), + contractAddress, + // TODO: Does ocr2keeper need to support config contract? DF-19182 + nil, + OCR2AggregatorLogDecoder, + }, ) if err != nil { - return nil, pkgerrors.Wrap(err, "failed to create config poller") + return nil, errors.Wrap(err, "failed to create config poller") } offchainConfigDigester := evmutil.EVMOffchainConfigDigester{ @@ -246,7 +243,6 @@ func newOCR2KeeperConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rarg return newConfigWatcher( lggr, contractAddress, - contractABI, offchainConfigDigester, configPoller, chain, diff --git a/core/services/relay/evm/ocr2vrf.go b/core/services/relay/evm/ocr2vrf.go index ed02ba06f91..98753655550 100644 --- a/core/services/relay/evm/ocr2vrf.go +++ b/core/services/relay/evm/ocr2vrf.go @@ -1,16 +1,13 @@ package evm import ( + "context" "encoding/json" "fmt" - "strings" - "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/jmoiron/sqlx" - pkgerrors "github.com/pkg/errors" - "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -63,11 +60,15 @@ func NewOCR2VRFRelayer(db *sqlx.DB, chain legacyevm.Chain, lggr logger.Logger, e } func (r *ocr2vrfRelayer) NewDKGProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (DKGProvider, error) { + + // TODO https://smartcontract-it.atlassian.net/browse/BCF-2887 + ctx := context.Background() + configWatcher, err := newOCR2VRFConfigProvider(r.lggr, r.chain, rargs) if err != nil { return nil, err } - contractTransmitter, err := newContractTransmitter(r.lggr, rargs, pargs.TransmitterID, r.ethKeystore, configWatcher, configTransmitterOpts{}) + contractTransmitter, err := newOnChainContractTransmitter(ctx, r.lggr, rargs, pargs.TransmitterID, r.ethKeystore, configWatcher, configTransmitterOpts{}, OCR2AggregatorTransmissionContractABI) if err != nil { return nil, err } @@ -86,11 +87,15 @@ func (r *ocr2vrfRelayer) NewDKGProvider(rargs commontypes.RelayArgs, pargs commo } func (r *ocr2vrfRelayer) NewOCR2VRFProvider(rargs commontypes.RelayArgs, pargs commontypes.PluginArgs) (OCR2VRFProvider, error) { + + // TODO https://smartcontract-it.atlassian.net/browse/BCF-2887 + ctx := context.Background() + configWatcher, err := newOCR2VRFConfigProvider(r.lggr, r.chain, rargs) if err != nil { return nil, err } - contractTransmitter, err := newContractTransmitter(r.lggr, rargs, pargs.TransmitterID, r.ethKeystore, configWatcher, configTransmitterOpts{}) + contractTransmitter, err := newOnChainContractTransmitter(ctx, r.lggr, rargs, pargs.TransmitterID, r.ethKeystore, configWatcher, configTransmitterOpts{}, OCR2AggregatorTransmissionContractABI) if err != nil { return nil, err } @@ -146,17 +151,16 @@ func newOCR2VRFConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rargs c } contractAddress := common.HexToAddress(rargs.ContractID) - contractABI, err := abi.JSON(strings.NewReader(ocr2aggregator.OCR2AggregatorABI)) - if err != nil { - return nil, pkgerrors.Wrap(err, "could not get OCR2Aggregator ABI JSON") - } configPoller, err := NewConfigPoller( lggr.With("contractID", rargs.ContractID), - chain.Client(), - chain.LogPoller(), - contractAddress, - // TODO: Does ocr2vrf need to support config contract? DF-19182 - nil, + CPConfig{ + chain.Client(), + chain.LogPoller(), + contractAddress, + // TODO: Does ocr2vrf need to support config contract? DF-19182 + nil, + OCR2AggregatorLogDecoder, + }, ) if err != nil { return nil, err @@ -170,7 +174,6 @@ func newOCR2VRFConfigProvider(lggr logger.Logger, chain legacyevm.Chain, rargs c return newConfigWatcher( lggr, contractAddress, - contractABI, offchainConfigDigester, configPoller, chain, diff --git a/core/services/relay/evm/relayer_extender.go b/core/services/relay/evm/relayer_extender.go index 79800a14b1a..83f03b47f9e 100644 --- a/core/services/relay/evm/relayer_extender.go +++ b/core/services/relay/evm/relayer_extender.go @@ -5,7 +5,7 @@ import ( "fmt" "math/big" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "go.uber.org/multierr" "github.com/smartcontractkit/chainlink-common/pkg/loop" @@ -16,7 +16,7 @@ import ( ) // ErrNoChains indicates that no EVM chains have been started -var ErrNoChains = pkgerrors.New("no EVM chains loaded") +var ErrNoChains = errors.New("no EVM chains loaded") type EVMChainRelayerExtender interface { loop.RelayerExt @@ -94,7 +94,7 @@ func (s *ChainRelayerExt) Chain() legacyevm.Chain { return s.chain } -var ErrCorruptEVMChain = pkgerrors.New("corrupt evm chain") +var ErrCorruptEVMChain = errors.New("corrupt evm chain") func (s *ChainRelayerExt) Start(ctx context.Context) error { return s.chain.Start(ctx) diff --git a/core/services/relay/evm/request_round_db.go b/core/services/relay/evm/request_round_db.go index a28c24837a3..b3a5b01bc2c 100644 --- a/core/services/relay/evm/request_round_db.go +++ b/core/services/relay/evm/request_round_db.go @@ -4,7 +4,7 @@ import ( "database/sql" "encoding/json" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -35,7 +35,7 @@ func NewRoundRequestedDB(sqldb *sql.DB, oracleSpecID int32, lggr logger.Logger) func (d *requestRoundDB) SaveLatestRoundRequested(tx pg.Queryer, rr ocr2aggregator.OCR2AggregatorRoundRequested) error { rawLog, err := json.Marshal(rr.Raw) if err != nil { - return pkgerrors.Wrap(err, "could not marshal log as JSON") + return errors.Wrap(err, "could not marshal log as JSON") } _, err = tx.Exec(` INSERT INTO ocr2_latest_round_requested (ocr2_oracle_spec_id, requester, config_digest, epoch, round, raw) @@ -47,7 +47,7 @@ VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (ocr2_oracle_spec_id) DO UPDATE SET raw = EXCLUDED.raw `, d.oracleSpecID, rr.Requester, rr.ConfigDigest[:], rr.Epoch, rr.Round, rawLog) - return pkgerrors.Wrap(err, "could not save latest round requested") + return errors.Wrap(err, "could not save latest round requested") } func (d *requestRoundDB) LoadLatestRoundRequested() (ocr2aggregator.OCR2AggregatorRoundRequested, error) { @@ -59,7 +59,7 @@ WHERE ocr2_oracle_spec_id = $1 LIMIT 1 `, d.oracleSpecID) if err != nil { - return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to query rows") + return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to query rows") } defer rows.Close() @@ -69,17 +69,17 @@ LIMIT 1 err = rows.Scan(&rr.Requester, &configDigest, &rr.Epoch, &rr.Round, &rawLog) if err != nil { - return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to scan row") + return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to scan row") } rr.ConfigDigest, err = ocrtypes.BytesToConfigDigest(configDigest) if err != nil { - return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to decode config digest") + return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to decode config digest") } err = json.Unmarshal(rawLog, &rr.Raw) if err != nil { - return rr, pkgerrors.Wrap(err, "LoadLatestRoundRequested failed to unmarshal raw log") + return rr, errors.Wrap(err, "LoadLatestRoundRequested failed to unmarshal raw log") } } diff --git a/core/services/relay/evm/request_round_tracker.go b/core/services/relay/evm/request_round_tracker.go index 6fe105adcd3..1f1ed71fc31 100644 --- a/core/services/relay/evm/request_round_tracker.go +++ b/core/services/relay/evm/request_round_tracker.go @@ -7,7 +7,7 @@ import ( gethCommon "github.com/ethereum/go-ethereum/common" gethTypes "github.com/ethereum/go-ethereum/core/types" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/jmoiron/sqlx" @@ -83,7 +83,7 @@ func (t *RequestRoundTracker) Start() error { return t.StartOnce("RequestRoundTracker", func() (err error) { t.latestRoundRequested, err = t.odb.LoadLatestRoundRequested() if err != nil { - return pkgerrors.Wrap(err, "RequestRoundTracker#Start: failed to load latest round requested") + return errors.Wrap(err, "RequestRoundTracker#Start: failed to load latest round requested") } t.unsubscribeLogs = t.logBroadcaster.Register(t, log.ListenerOpts{ diff --git a/core/services/relay/evm/request_round_tracker_test.go b/core/services/relay/evm/request_round_tracker_test.go index cd9eca822aa..cb2ee2a8d72 100644 --- a/core/services/relay/evm/request_round_tracker_test.go +++ b/core/services/relay/evm/request_round_tracker_test.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/common" gethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - pkgerrors "github.com/pkg/errors" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -244,7 +244,7 @@ func Test_OCRContractTracker_HandleLog_OCRContractLatestRoundRequested(t *testin logBroadcast.On("String").Return("").Maybe() uni.lb.On("WasAlreadyConsumed", mock.Anything, mock.Anything).Return(false, nil) - uni.db.On("SaveLatestRoundRequested", mock.Anything, mock.Anything).Return(pkgerrors.New("something exploded")) + uni.db.On("SaveLatestRoundRequested", mock.Anything, mock.Anything).Return(errors.New("something exploded")) uni.requestRoundTracker.HandleLog(logBroadcast) diff --git a/core/services/relay/evm/types/abi_types.go b/core/services/relay/evm/types/abi_types.go index 34b12d885b4..4d1328bcc12 100644 --- a/core/services/relay/evm/types/abi_types.go +++ b/core/services/relay/evm/types/abi_types.go @@ -53,6 +53,10 @@ var typeMap = map[string]*ABIEncodingType{ native: reflect.TypeOf(common.Address{}), checked: reflect.TypeOf(common.Address{}), }, + "bytes": { + native: reflect.TypeOf([]byte{}), + checked: reflect.TypeOf([]byte{}), + }, } type ABIEncodingType struct { diff --git a/core/services/relay/evm/types/codec_entry.go b/core/services/relay/evm/types/codec_entry.go index b87f7ced721..21e5ac59847 100644 --- a/core/services/relay/evm/types/codec_entry.go +++ b/core/services/relay/evm/types/codec_entry.go @@ -222,7 +222,7 @@ func getNativeAndCheckedTypes(curType *abi.Type) (reflect.Type, reflect.Type, er func createTupleType(curType *abi.Type, converter func(reflect.Type) reflect.Type) (reflect.Type, reflect.Type, error) { if len(curType.TupleElems) == 0 { if curType.TupleType == nil { - return nil, nil, fmt.Errorf("%w: unsupported solitidy type: %v", commontypes.ErrInvalidType, curType.String()) + return nil, nil, fmt.Errorf("%w: unsupported solidity type: %v", commontypes.ErrInvalidType, curType.String()) } return curType.TupleType, curType.TupleType, nil } From f0dd5234302f585d3d3131ef931a231a61468854 Mon Sep 17 00:00:00 2001 From: James Walker Date: Mon, 26 Feb 2024 22:28:09 -0500 Subject: [PATCH 11/11] fix merge errors --- core/chains/evm/client/erroring_node.go | 2 +- core/chains/evm/client/errors.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/chains/evm/client/erroring_node.go b/core/chains/evm/client/erroring_node.go index eb8f07b1558..00e8465bca3 100644 --- a/core/chains/evm/client/erroring_node.go +++ b/core/chains/evm/client/erroring_node.go @@ -104,7 +104,7 @@ func (e *erroringNode) CallContract(ctx context.Context, msg ethereum.CallMsg, b } func (e *erroringNode) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) { - return nil, errors.New(e.errMsg) + return nil, pkgerrors.New(e.errMsg) } func (e *erroringNode) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { diff --git a/core/chains/evm/client/errors.go b/core/chains/evm/client/errors.go index 265285fb535..42a983b40d7 100644 --- a/core/chains/evm/client/errors.go +++ b/core/chains/evm/client/errors.go @@ -327,7 +327,7 @@ func (s *SendError) IsCanceled() bool { if s.err == nil { return false } - return errors.Is(s.err, context.Canceled) + return pkgerrors.Is(s.err, context.Canceled) } func NewFatalSendError(e error) *SendError {