diff --git a/.changeset/fresh-lizards-love.md b/.changeset/fresh-lizards-love.md new file mode 100644 index 00000000000..8e6e5d5cfef --- /dev/null +++ b/.changeset/fresh-lizards-love.md @@ -0,0 +1,5 @@ +--- +"chainlink": minor +--- + +#internal Updates required to work with chainlink-common changes to support grpc streams for capabilities diff --git a/.changeset/lucky-ghosts-give.md b/.changeset/lucky-ghosts-give.md new file mode 100644 index 00000000000..2ce47a6978b --- /dev/null +++ b/.changeset/lucky-ghosts-give.md @@ -0,0 +1,5 @@ +--- +"chainlink": patch +--- + +core/services/keystore: switch to sqlutil.DataStore #internal diff --git a/.changeset/plenty-wombats-grab.md b/.changeset/plenty-wombats-grab.md new file mode 100644 index 00000000000..84fb96f8b80 --- /dev/null +++ b/.changeset/plenty-wombats-grab.md @@ -0,0 +1,5 @@ +--- +"chainlink": patch +--- + +#wip Regenerate Keystone wrappers diff --git a/.github/actions/golangci-lint/action.yml b/.github/actions/golangci-lint/action.yml index 3542c865959..e52dd1aed7b 100644 --- a/.github/actions/golangci-lint/action.yml +++ b/.github/actions/golangci-lint/action.yml @@ -2,6 +2,9 @@ name: CI lint for Golang description: Runs CI lint for Golang inputs: # general inputs + id: + description: Unique metrics collection id + required: true name: description: Name of the lint action default: lint @@ -72,7 +75,7 @@ runs: if: always() uses: smartcontractkit/push-gha-metrics-action@dea9b546553cb4ca936607c2267a09c004e4ab3f # v3.0.0 with: - id: chainlink-golang-ci + id: chainlink-golang-ci-${{ inputs.id }} basic-auth: ${{ inputs.gc-basic-auth }} hostname: ${{ inputs.gc-host }} org-id: ${{ inputs.gc-org-id }} diff --git a/.github/workflows/ci-core.yml b/.github/workflows/ci-core.yml index 9d9ff595ed0..c97af329639 100644 --- a/.github/workflows/ci-core.yml +++ b/.github/workflows/ci-core.yml @@ -63,6 +63,7 @@ jobs: uses: ./.github/actions/golangci-lint if: ${{ needs.filter.outputs.changes == 'true' }} with: + id: core gc-basic-auth: ${{ secrets.GRAFANA_INTERNAL_BASIC_AUTH }} gc-host: ${{ secrets.GRAFANA_INTERNAL_HOST }} gc-org-id: ${{ secrets.GRAFANA_INTERNAL_TENANT_ID }} diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index 78c26ff258e..814c354cfe6 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -13,6 +13,7 @@ jobs: - name: Golang Lint uses: ./.github/actions/golangci-lint with: + id: scripts name: lint-scripts go-directory: core/scripts go-version-file: core/scripts/go.mod diff --git a/.github/workflows/helm-chart.yml b/.github/workflows/helm-chart.yml index 1a12a512e39..f0dd25c5dbb 100644 --- a/.github/workflows/helm-chart.yml +++ b/.github/workflows/helm-chart.yml @@ -9,24 +9,29 @@ on: jobs: ci-lint-helm-charts: runs-on: ubuntu-latest - permissions: - id-token: write - contents: read - actions: read steps: - - name: Add repositories - run: | - helm repo add mockserver https://www.mock-server.com - helm repo add opentelemetry-collector https://open-telemetry.github.io/opentelemetry-helm-charts - helm repo add tempo https://grafana.github.io/helm-charts - helm repo add grafana https://grafana.github.io/helm-charts - name: ci-lint-helm-charts - uses: smartcontractkit/.github/actions/ci-lint-charts@6b08487b176ef7cad086526d0b54ddff6691c044 # ci-lint-charts@0.1.2 + uses: smartcontractkit/.github/actions/ci-lint-charts@7fa39741b11e66ed59f8aad786d4b9356c389f3f # ci-lint-charts@0.2.0 with: # chart testing inputs chart-testing-extra-args: "--lint-conf=lintconf.yaml" + charts-dir: charts/chainlink-cluster # grafana inputs metrics-job-name: ci-lint-helm-charts gc-basic-auth: ${{ secrets.GRAFANA_INTERNAL_BASIC_AUTH }} gc-host: ${{ secrets.GRAFANA_INTERNAL_HOST }} gc-org-id: ${{ secrets.GRAFANA_INTERNAL_TENANT_ID }} + + ci-kubeconform: + runs-on: ubuntu-latest + steps: + - name: ci-kubeconform + uses: smartcontractkit/.github/actions/ci-kubeconform@1ae8a9a984814c4daf50aa96f03be2cba0ef3fec # ci-kubeconform@0.2.0 + with: + # kubeform inputs + charts-dir: charts/chainlink-cluster + # grafana inputs + metrics-job-name: ci-kubeconform + gc-basic-auth: ${{ secrets.GRAFANA_INTERNAL_BASIC_AUTH }} + gc-host: ${{ secrets.GRAFANA_INTERNAL_HOST }} + gc-org-id: ${{ secrets.GRAFANA_INTERNAL_TENANT_ID }} diff --git a/.goreleaser.devspace.yaml b/.goreleaser.devspace.yaml index 1c6b4768d98..bca65e90454 100644 --- a/.goreleaser.devspace.yaml +++ b/.goreleaser.devspace.yaml @@ -24,8 +24,8 @@ builds: post: ./tools/bin/goreleaser_utils build_post_hook {{ dir .Path }} {{ .Os }} {{ .Arch }} env: - CGO_ENABLED=1 - - CC=$ZIG_EXEC cc -target x86_64-linux-gnu - - CCX=$ZIG_EXEC c++ -target x86_64-linux-gnu + - CC=$ZIG_EXEC cc -target x86_64-linux-gnu -Wno-error=unused-command-line-argument + - CCX=$ZIG_EXEC c++ -target x86_64-linux-gnu -Wno-error=unused-command-line-argument flags: - -trimpath - -buildmode=pie diff --git a/contracts/.changeset/old-pianos-trade.md b/contracts/.changeset/old-pianos-trade.md new file mode 100644 index 00000000000..10c0097bded --- /dev/null +++ b/contracts/.changeset/old-pianos-trade.md @@ -0,0 +1,5 @@ +--- +"@chainlink/contracts": patch +--- + +#wip Add Capability Registry skeleton diff --git a/contracts/scripts/native_solc_compile_all_keystone b/contracts/scripts/native_solc_compile_all_keystone index 49bd6527843..1530b307dbd 100755 --- a/contracts/scripts/native_solc_compile_all_keystone +++ b/contracts/scripts/native_solc_compile_all_keystone @@ -28,5 +28,6 @@ compileContract () { "$ROOT"/contracts/src/v0.8/"$1" } +compileContract keystone/CapabilityRegistry.sol compileContract keystone/KeystoneForwarder.sol compileContract keystone/OCR3Capability.sol diff --git a/contracts/src/v0.8/keystone/CapabilityRegistry.sol b/contracts/src/v0.8/keystone/CapabilityRegistry.sol new file mode 100644 index 00000000000..7c870bed7fb --- /dev/null +++ b/contracts/src/v0.8/keystone/CapabilityRegistry.sol @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {TypeAndVersionInterface} from "../interfaces/TypeAndVersionInterface.sol"; +import {OwnerIsCreator} from "../shared/access/OwnerIsCreator.sol"; + +struct Capability { + // Capability type, e.g. "data-streams-reports" + // bytes32(string); validation regex: ^[a-z0-9_\-:]{1,32}$ + // Not "type" because that's a reserved keyword in Solidity. + bytes32 capabilityType; + // Semver, e.g., "1.2.3" + // bytes32(string); must be valid Semver + max 32 characters. + bytes32 version; +} + +contract CapabilityRegistry is OwnerIsCreator, TypeAndVersionInterface { + mapping(bytes32 => Capability) private s_capabilities; + + event CapabilityAdded(bytes32 indexed capabilityId); + + function typeAndVersion() external pure override returns (string memory) { + return "CapabilityRegistry 1.0.0"; + } + + function addCapability(Capability calldata capability) external onlyOwner { + bytes32 capabilityId = getCapabilityID(capability.capabilityType, capability.version); + s_capabilities[capabilityId] = capability; + emit CapabilityAdded(capabilityId); + } + + function getCapability(bytes32 capabilityID) public view returns (Capability memory) { + return s_capabilities[capabilityID]; + } + + /// @notice This functions returns a Capability ID packed into a bytes32 for cheaper access + /// @return A unique identifier for the capability + function getCapabilityID(bytes32 capabilityType, bytes32 version) public pure returns (bytes32) { + return keccak256(abi.encodePacked(capabilityType, version)); + } +} diff --git a/contracts/src/v0.8/keystone/test/CapabilityRegistry.t.sol b/contracts/src/v0.8/keystone/test/CapabilityRegistry.t.sol new file mode 100644 index 00000000000..f5d539d8e34 --- /dev/null +++ b/contracts/src/v0.8/keystone/test/CapabilityRegistry.t.sol @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.19; + +import {Test} from "forge-std/Test.sol"; +import {Capability, CapabilityRegistry} from "../CapabilityRegistry.sol"; + +contract CapabilityRegistryTest is Test { + function setUp() public virtual {} + + function testAddCapability() public { + CapabilityRegistry capabilityRegistry = new CapabilityRegistry(); + + capabilityRegistry.addCapability(Capability("data-streams-reports", "1.0.0")); + + bytes32 capabilityId = capabilityRegistry.getCapabilityID(bytes32("data-streams-reports"), bytes32("1.0.0")); + Capability memory capability = capabilityRegistry.getCapability(capabilityId); + + assertEq(capability.capabilityType, "data-streams-reports"); + assertEq(capability.version, "1.0.0"); + } +} diff --git a/core/capabilities/registry_test.go b/core/capabilities/registry_test.go index 3f8ca397495..3bed31a957a 100644 --- a/core/capabilities/registry_test.go +++ b/core/capabilities/registry_test.go @@ -19,8 +19,8 @@ type mockCapability struct { capabilities.CapabilityInfo } -func (m *mockCapability) Execute(ctx context.Context, callback chan<- capabilities.CapabilityResponse, req capabilities.CapabilityRequest) error { - return nil +func (m *mockCapability) Execute(ctx context.Context, req capabilities.CapabilityRequest) (<-chan capabilities.CapabilityResponse, error) { + return nil, nil } func (m *mockCapability) RegisterToWorkflow(ctx context.Context, request capabilities.RegisterToWorkflowRequest) error { @@ -140,7 +140,7 @@ func TestRegistry_ChecksExecutionAPIByType(t *testing.T) { { name: "trigger", newCapability: func(ctx context.Context, reg *coreCapabilities.Registry) (string, error) { - odt := triggers.NewOnDemand() + odt := triggers.NewOnDemand(logger.TestLogger(t)) info, err := odt.Info(ctx) require.NoError(t, err) return info.ID, reg.Add(ctx, odt) diff --git a/core/capabilities/remote/target.go b/core/capabilities/remote/target.go index bacc06c0310..92b0724512a 100644 --- a/core/capabilities/remote/target.go +++ b/core/capabilities/remote/target.go @@ -50,7 +50,7 @@ func (c *remoteTargetCaller) UnregisterFromWorkflow(ctx context.Context, request return errors.New("not implemented") } -func (c *remoteTargetCaller) Execute(ctx context.Context, callback chan<- commoncap.CapabilityResponse, request commoncap.CapabilityRequest) error { +func (c *remoteTargetCaller) Execute(ctx context.Context, request commoncap.CapabilityRequest) (<-chan commoncap.CapabilityResponse, error) { c.lggr.Debugw("not implemented - executing fake remote target capability", "capabilityId", c.capInfo.ID, "nMembers", len(c.donInfo.Members)) for _, peerID := range c.donInfo.Members { m := &types.MessageBody{ @@ -60,10 +60,12 @@ func (c *remoteTargetCaller) Execute(ctx context.Context, callback chan<- common } err := c.dispatcher.Send(peerID, m) if err != nil { - return err + return nil, err } } - return nil + + // TODO: return a channel that will be closed when all responses are received + return nil, nil } func (c *remoteTargetCaller) Receive(msg *types.MessageBody) { diff --git a/core/capabilities/remote/target_test.go b/core/capabilities/remote/target_test.go index 904cd5b9c71..a9e72d778df 100644 --- a/core/capabilities/remote/target_test.go +++ b/core/capabilities/remote/target_test.go @@ -3,8 +3,8 @@ package remote_test import ( "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" commoncap "github.com/smartcontractkit/chainlink-common/pkg/capabilities" "github.com/smartcontractkit/chainlink/v2/core/capabilities/remote" @@ -24,5 +24,7 @@ func TestTarget_Placeholder(t *testing.T) { dispatcher := remoteMocks.NewDispatcher(t) dispatcher.On("Send", mock.Anything, mock.Anything).Return(nil) target := remote.NewRemoteTargetCaller(commoncap.CapabilityInfo{}, donInfo, dispatcher, lggr) - require.NoError(t, target.Execute(ctx, nil, commoncap.CapabilityRequest{})) + + _, err := target.Execute(ctx, commoncap.CapabilityRequest{}) + assert.NoError(t, err) } diff --git a/core/capabilities/remote/trigger_publisher.go b/core/capabilities/remote/trigger_publisher.go index fac01fdead6..d06254657c7 100644 --- a/core/capabilities/remote/trigger_publisher.go +++ b/core/capabilities/remote/trigger_publisher.go @@ -41,7 +41,7 @@ type registrationKey struct { } type pubRegState struct { - callback chan<- commoncap.CapabilityResponse + callback <-chan commoncap.CapabilityResponse request commoncap.CapabilityRequest } @@ -112,9 +112,8 @@ func (p *triggerPublisher) Receive(msg *types.MessageBody) { p.lggr.Errorw("failed to unmarshal request", "capabilityId", p.capInfo.ID, "err", err) return } - callbackCh := make(chan commoncap.CapabilityResponse) ctx, cancel := p.stopCh.NewCtx() - err = p.underlying.RegisterTrigger(ctx, callbackCh, unmarshaled) + callbackCh, err := p.underlying.RegisterTrigger(ctx, unmarshaled) cancel() if err == nil { p.registrations[key] = &pubRegState{ @@ -153,7 +152,6 @@ func (p *triggerPublisher) registrationCleanupLoop() { cancel() p.lggr.Infow("unregistered trigger", "capabilityId", p.capInfo.ID, "callerDonID", key.callerDonId, "workflowId", key.workflowId, "err", err) // after calling UnregisterTrigger, the underlying trigger will not send any more events to the channel - close(req.callback) delete(p.registrations, key) p.messageCache.Delete(key) } @@ -163,7 +161,7 @@ func (p *triggerPublisher) registrationCleanupLoop() { } } -func (p *triggerPublisher) triggerEventLoop(callbackCh chan commoncap.CapabilityResponse, key registrationKey) { +func (p *triggerPublisher) triggerEventLoop(callbackCh <-chan commoncap.CapabilityResponse, key registrationKey) { defer p.wg.Done() for { select { diff --git a/core/capabilities/remote/trigger_publisher_test.go b/core/capabilities/remote/trigger_publisher_test.go index 2a31646de5b..dd107e12e61 100644 --- a/core/capabilities/remote/trigger_publisher_test.go +++ b/core/capabilities/remote/trigger_publisher_test.go @@ -87,9 +87,9 @@ func (t *testTrigger) Info(_ context.Context) (commoncap.CapabilityInfo, error) return t.info, nil } -func (t *testTrigger) RegisterTrigger(_ context.Context, _ chan<- commoncap.CapabilityResponse, request commoncap.CapabilityRequest) error { +func (t *testTrigger) RegisterTrigger(_ context.Context, request commoncap.CapabilityRequest) (<-chan commoncap.CapabilityResponse, error) { t.registrationsCh <- request - return nil + return nil, nil } func (t *testTrigger) UnregisterTrigger(_ context.Context, request commoncap.CapabilityRequest) error { diff --git a/core/capabilities/remote/trigger_subscriber.go b/core/capabilities/remote/trigger_subscriber.go index 4b46935eab6..a7cb58c008b 100644 --- a/core/capabilities/remote/trigger_subscriber.go +++ b/core/capabilities/remote/trigger_subscriber.go @@ -51,7 +51,11 @@ var _ commoncap.TriggerCapability = &triggerSubscriber{} var _ types.Receiver = &triggerSubscriber{} var _ services.Service = &triggerSubscriber{} -func NewTriggerSubscriber(config types.RemoteTriggerConfig, capInfo commoncap.CapabilityInfo, capDonInfo types.DON, localDonInfo types.DON, dispatcher types.Dispatcher, aggregator types.Aggregator, lggr logger.Logger) *triggerSubscriber { +// TODO makes this configurable with a default +const defaultSendChannelBufferSize = 1000 + +func NewTriggerSubscriber(config types.RemoteTriggerConfig, capInfo commoncap.CapabilityInfo, capDonInfo types.DON, localDonInfo types.DON, + dispatcher types.Dispatcher, aggregator types.Aggregator, lggr logger.Logger) *triggerSubscriber { if aggregator == nil { lggr.Warnw("no aggregator provided, using default MODE aggregator", "capabilityId", capInfo.ID) aggregator = NewDefaultModeAggregator(uint32(capDonInfo.F + 1)) @@ -88,22 +92,25 @@ func (s *triggerSubscriber) Info(ctx context.Context) (commoncap.CapabilityInfo, return s.capInfo, nil } -func (s *triggerSubscriber) RegisterTrigger(ctx context.Context, callback chan<- commoncap.CapabilityResponse, request commoncap.CapabilityRequest) error { +func (s *triggerSubscriber) RegisterTrigger(ctx context.Context, request commoncap.CapabilityRequest) (<-chan commoncap.CapabilityResponse, error) { rawRequest, err := pb.MarshalCapabilityRequest(request) if err != nil { - return err + return nil, err } if request.Metadata.WorkflowID == "" { - return errors.New("empty workflowID") + return nil, errors.New("empty workflowID") } s.mu.Lock() defer s.mu.Unlock() + + callback := make(chan commoncap.CapabilityResponse, defaultSendChannelBufferSize) s.registeredWorkflows[request.Metadata.WorkflowID] = &subRegState{ callback: callback, rawRequest: rawRequest, } + s.lggr.Infow("RegisterTrigger called", "capabilityId", s.capInfo.ID, "donId", s.capDonInfo.ID, "workflowID", request.Metadata.WorkflowID) - return nil + return callback, nil } func (s *triggerSubscriber) registrationLoop() { @@ -141,6 +148,8 @@ func (s *triggerSubscriber) registrationLoop() { func (s *triggerSubscriber) UnregisterTrigger(ctx context.Context, request commoncap.CapabilityRequest) error { s.mu.Lock() defer s.mu.Unlock() + + close(s.registeredWorkflows[request.Metadata.WorkflowID].callback) delete(s.registeredWorkflows, request.Metadata.WorkflowID) // Registrations will quickly expire on all remote nodes. // Alternatively, we could send UnregisterTrigger messages right away. diff --git a/core/capabilities/remote/trigger_subscriber_test.go b/core/capabilities/remote/trigger_subscriber_test.go index ce901169f10..df04306e2b0 100644 --- a/core/capabilities/remote/trigger_subscriber_test.go +++ b/core/capabilities/remote/trigger_subscriber_test.go @@ -67,12 +67,13 @@ func TestTriggerSubscriber_RegisterAndReceive(t *testing.T) { } subscriber := remote.NewTriggerSubscriber(config, capInfo, capDonInfo, workflowDonInfo, dispatcher, nil, lggr) require.NoError(t, subscriber.Start(ctx)) - triggerEventCallbackCh := make(chan commoncap.CapabilityResponse, 2) - require.NoError(t, subscriber.RegisterTrigger(ctx, triggerEventCallbackCh, commoncap.CapabilityRequest{ + + triggerEventCallbackCh, err := subscriber.RegisterTrigger(ctx, commoncap.CapabilityRequest{ Metadata: commoncap.RequestMetadata{ WorkflowID: workflowID1, }, - })) + }) + require.NoError(t, err) <-awaitRegistrationMessageCh // receive trigger event diff --git a/core/capabilities/targets/write_target.go b/core/capabilities/targets/write_target.go index 677b1148ebb..43b02939c04 100644 --- a/core/capabilities/targets/write_target.go +++ b/core/capabilities/targets/write_target.go @@ -28,7 +28,8 @@ import ( var forwardABI = evmtypes.MustGetABI(forwarder.KeystoneForwarderMetaData.ABI) -func InitializeWrite(registry commontypes.CapabilitiesRegistry, legacyEVMChains legacyevm.LegacyChainContainer, lggr logger.Logger) error { +func InitializeWrite(registry commontypes.CapabilitiesRegistry, legacyEVMChains legacyevm.LegacyChainContainer, + lggr logger.Logger) error { for _, chain := range legacyEVMChains.Slice() { capability := NewEvmWrite(chain, lggr) if err := registry.Add(context.TODO(), capability); err != nil { @@ -157,7 +158,7 @@ func encodePayload(args []any, rawSelector string) ([]byte, error) { // return append(method.ID, arguments...), nil } -func (cap *EvmWrite) Execute(ctx context.Context, callback chan<- capabilities.CapabilityResponse, request capabilities.CapabilityRequest) error { +func (cap *EvmWrite) Execute(ctx context.Context, request capabilities.CapabilityRequest) (<-chan capabilities.CapabilityResponse, error) { cap.lggr.Debugw("Execute", "request", request) // TODO: idempotency @@ -168,22 +169,23 @@ func (cap *EvmWrite) Execute(ctx context.Context, callback chan<- capabilities.C reqConfig, err := parseConfig(request.Config) if err != nil { - return err + return nil, err } inputsAny, err := request.Inputs.Unwrap() if err != nil { - return err + return nil, err } inputs := inputsAny.(map[string]any) rep, ok := inputs["report"] if !ok { - return errors.New("malformed data: inputs doesn't contain a report key") + return nil, errors.New("malformed data: inputs doesn't contain a report key") } if rep == nil { // We received any empty report -- this means we should skip transmission. cap.lggr.Debugw("Skipping empty report", "request", request) + callback := make(chan capabilities.CapabilityResponse) go func() { // TODO: cast tx.Error to Err (or Value to Value?) callback <- capabilities.CapabilityResponse{ @@ -192,18 +194,18 @@ func (cap *EvmWrite) Execute(ctx context.Context, callback chan<- capabilities.C } close(callback) }() - return nil + return callback, nil } // evaluate any variables in reqConfig.Params args, err := evaluateParams(reqConfig.Params, inputs) if err != nil { - return err + return nil, err } data, err := encodePayload(args, reqConfig.ABI) if err != nil { - return err + return nil, err } // TODO: validate encoded report is prefixed with workflowID and executionID that match the request meta @@ -214,7 +216,7 @@ func (cap *EvmWrite) Execute(ctx context.Context, callback chan<- capabilities.C // construct forwarding payload calldata, err := forwardABI.Pack("report", common.HexToAddress(reqConfig.Address), data, signatures) if err != nil { - return err + return nil, err } txMeta := &txmgr.TxMeta{ @@ -238,9 +240,11 @@ func (cap *EvmWrite) Execute(ctx context.Context, callback chan<- capabilities.C } tx, err := txm.CreateTransaction(ctx, req) if err != nil { - return err + return nil, err } cap.lggr.Debugw("Transaction submitted", "request", request, "transaction", tx) + + callback := make(chan capabilities.CapabilityResponse) go func() { // TODO: cast tx.Error to Err (or Value to Value?) callback <- capabilities.CapabilityResponse{ @@ -249,7 +253,7 @@ func (cap *EvmWrite) Execute(ctx context.Context, callback chan<- capabilities.C } close(callback) }() - return nil + return callback, nil } func (cap *EvmWrite) RegisterToWorkflow(ctx context.Context, request capabilities.RegisterToWorkflowRequest) error { diff --git a/core/capabilities/targets/write_target_test.go b/core/capabilities/targets/write_target_test.go index fd68234ca70..744fcd9d2e7 100644 --- a/core/capabilities/targets/write_target_test.go +++ b/core/capabilities/targets/write_target_test.go @@ -82,9 +82,7 @@ func TestEvmWrite(t *testing.T) { }) - ch := make(chan capabilities.CapabilityResponse) - - err = capability.Execute(ctx, ch, req) + ch, err := capability.Execute(ctx, req) require.NoError(t, err) response := <-ch @@ -134,9 +132,7 @@ func TestEvmWrite_EmptyReport(t *testing.T) { Inputs: inputs, } - ch := make(chan capabilities.CapabilityResponse) - - err = capability.Execute(ctx, ch, req) + ch, err := capability.Execute(ctx, req) require.NoError(t, err) response := <-ch diff --git a/core/chains/evm/log/helpers_test.go b/core/chains/evm/log/helpers_test.go index 85c2fe783bb..8919b848aca 100644 --- a/core/chains/evm/log/helpers_test.go +++ b/core/chains/evm/log/helpers_test.go @@ -94,7 +94,7 @@ func newBroadcasterHelperWithEthClient(t *testing.T, ethClient evmclient.Client, db := pgtest.NewSqlxDB(t) orm := log.NewORM(db, cltest.FixtureChainID) lb := log.NewTestBroadcaster(orm, ethClient, config.EVM(), lggr, highestSeenHead, mailMon) - kst := cltest.NewKeyStore(t, db, globalConfig.Database()) + kst := cltest.NewKeyStore(t, db) cc := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{ Client: ethClient, diff --git a/core/chains/evm/log/orm_test.go b/core/chains/evm/log/orm_test.go index 1a6d927cd50..dc3611e8e6f 100644 --- a/core/chains/evm/log/orm_test.go +++ b/core/chains/evm/log/orm_test.go @@ -13,14 +13,12 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" ) func TestORM_broadcasts(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() orm := log.NewORM(db, cltest.FixtureChainID) @@ -108,8 +106,7 @@ func TestORM_pending(t *testing.T) { func TestORM_MarkUnconsumed(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() orm := log.NewORM(db, cltest.FixtureChainID) diff --git a/core/chains/evm/monitor/balance_test.go b/core/chains/evm/monitor/balance_test.go index 85e0ec669bf..a27e2cec9a7 100644 --- a/core/chains/evm/monitor/balance_test.go +++ b/core/chains/evm/monitor/balance_test.go @@ -20,7 +20,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/chains/evm/monitor" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" ) @@ -35,11 +34,9 @@ func newEthClientMock(t *testing.T) *evmclimocks.Client { func TestBalanceMonitor_Start(t *testing.T) { t.Parallel() - cfg := configtest.NewGeneralConfig(t, nil) - t.Run("updates balance from nil for multiple keys", func(t *testing.T) { db := pgtest.NewSqlxDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := newEthClientMock(t) _, k1Addr := cltest.MustInsertRandomKey(t, ethKeyStore) _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -66,7 +63,7 @@ func TestBalanceMonitor_Start(t *testing.T) { t.Run("handles nil head", func(t *testing.T) { db := pgtest.NewSqlxDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := newEthClientMock(t) _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -85,7 +82,7 @@ func TestBalanceMonitor_Start(t *testing.T) { t.Run("cancelled context", func(t *testing.T) { db := pgtest.NewSqlxDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := newEthClientMock(t) _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -114,7 +111,7 @@ func TestBalanceMonitor_Start(t *testing.T) { t.Run("recovers on error", func(t *testing.T) { db := pgtest.NewSqlxDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := newEthClientMock(t) _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -136,11 +133,9 @@ func TestBalanceMonitor_Start(t *testing.T) { func TestBalanceMonitor_OnNewLongestChain_UpdatesBalance(t *testing.T) { t.Parallel() - cfg := configtest.NewGeneralConfig(t, nil) - t.Run("updates balance for multiple keys", func(t *testing.T) { db := pgtest.NewSqlxDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := newEthClientMock(t) _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -190,8 +185,7 @@ func TestBalanceMonitor_FewerRPCCallsWhenBehind(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() cltest.MustInsertRandomKey(t, ethKeyStore) diff --git a/core/chains/evm/txmgr/broadcaster_test.go b/core/chains/evm/txmgr/broadcaster_test.go index 070c2c37473..14968126bf9 100644 --- a/core/chains/evm/txmgr/broadcaster_test.go +++ b/core/chains/evm/txmgr/broadcaster_test.go @@ -81,7 +81,7 @@ func TestEthBroadcaster_Lifecycle(t *testing.T) { txStore := cltest.NewTestTxStore(t, db) evmcfg := evmtest.NewChainScopedConfig(t, cfg) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) estimator := gasmocks.NewEvmFeeEstimator(t) txBuilder := txmgr.NewEvmTxAttemptBuilder(*ethClient.ConfiguredChainID(), evmcfg.EVM().GasEstimator(), ethKeyStore, estimator) @@ -139,7 +139,7 @@ func TestEthBroadcaster_LoadNextSequenceMapFailure_StartupSuccess(t *testing.T) txStore := cltest.NewTestTxStore(t, db) evmcfg := evmtest.NewChainScopedConfig(t, cfg) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) estimator := gasmocks.NewEvmFeeEstimator(t) txBuilder := txmgr.NewEvmTxAttemptBuilder(*ethClient.ConfiguredChainID(), evmcfg.EVM().GasEstimator(), ethKeyStore, estimator) @@ -170,7 +170,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Success(t *testing.T) { cfg := configtest.NewTestGeneralConfig(t) ctx := testutils.Context(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) _, otherAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -525,7 +525,7 @@ func TestEthBroadcaster_TransmitChecking(t *testing.T) { cfg := configtest.NewTestGeneralConfig(t) ctx := testutils.Context(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) @@ -611,7 +611,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_OptimisticLockingOnEthTx(t *testi ccfg := evmtest.NewChainScopedConfig(t, cfg) evmcfg := txmgr.NewEvmTxmConfig(ccfg.EVM()) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) estimator := gasmocks.NewEvmFeeEstimator(t) txBuilder := txmgr.NewEvmTxAttemptBuilder(*ethClient.ConfiguredChainID(), ccfg.EVM().GasEstimator(), ethKeyStore, estimator) @@ -674,7 +674,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Success_WithMultiplier(t *testing }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -723,7 +723,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) firstInProgress := txmgr.Tx{ @@ -758,7 +758,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) @@ -797,7 +797,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) @@ -834,7 +834,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) @@ -870,7 +870,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) @@ -908,7 +908,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) @@ -944,7 +944,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { db := pgtest.NewSqlxDB(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Nonce: nextNonce.Int64()}.MustInsertWithState(t, ethKeyStore) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -1013,7 +1013,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { cfg := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -1655,7 +1655,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_KeystoreErrors(t *testing.T) { cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - realKeystore := cltest.NewKeyStore(t, db, cfg.Database()) + realKeystore := cltest.NewKeyStore(t, db) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, realKeystore.Eth()) evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -1712,7 +1712,7 @@ func TestEthBroadcaster_Trigger(t *testing.T) { cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) evmcfg := evmtest.NewChainScopedConfig(t, cfg) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) lggr := logger.Test(t) nonceTracker := txmgr.NewNonceTracker(lggr, txStore, txmgr.NewEvmTxmClient(ethClient)) @@ -1735,7 +1735,7 @@ func TestEthBroadcaster_SyncNonce(t *testing.T) { evmTxmCfg := txmgr.NewEvmTxmConfig(evmcfg.EVM()) txStore := cltest.NewTestTxStore(t, db) - kst := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + kst := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.RandomKey{Disabled: false}.MustInsertWithState(t, kst) estimator := gas.NewEvmFeeEstimator(lggr, func(lggr logger.Logger) gas.EvmEstimator { @@ -1770,7 +1770,7 @@ func TestEthBroadcaster_NonceTracker_InProgressTx(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) diff --git a/core/chains/evm/txmgr/confirmer_test.go b/core/chains/evm/txmgr/confirmer_test.go index 89e88d5a6dc..f368aea9c57 100644 --- a/core/chains/evm/txmgr/confirmer_test.go +++ b/core/chains/evm/txmgr/confirmer_test.go @@ -118,7 +118,7 @@ func TestEthConfirmer_Lifecycle(t *testing.T) { txStore := newTxStore(t, db) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() // Add some fromAddresses cltest.MustInsertRandomKey(t, ethKeyStore) @@ -188,7 +188,7 @@ func TestEthConfirmer_CheckForReceipts(t *testing.T) { txStore := cltest.NewTestTxStore(t, db) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -601,7 +601,7 @@ func TestEthConfirmer_CheckForReceipts_batching(t *testing.T) { }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -664,7 +664,7 @@ func TestEthConfirmer_CheckForReceipts_HandlesNonFwdTxsWithForwardingEnabled(t * }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -714,7 +714,7 @@ func TestEthConfirmer_CheckForReceipts_only_likely_confirmed(t *testing.T) { }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -770,7 +770,7 @@ func TestEthConfirmer_CheckForReceipts_should_not_check_for_likely_unconfirmed(t config := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -797,7 +797,7 @@ func TestEthConfirmer_CheckForReceipts_confirmed_missing_receipt_scoped_to_key(t db := pgtest.NewSqlxDB(t) cfg := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress1_1 := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) _, fromAddress1_2 := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -866,7 +866,7 @@ func TestEthConfirmer_CheckForReceipts_confirmed_missing_receipt(t *testing.T) { }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1126,7 +1126,7 @@ func TestEthConfirmer_CheckConfirmedMissingReceipt(t *testing.T) { }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1205,7 +1205,7 @@ func TestEthConfirmer_CheckConfirmedMissingReceipt_batchSendTransactions_fails(t }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1269,7 +1269,7 @@ func TestEthConfirmer_CheckConfirmedMissingReceipt_smallEvmRPCBatchSize_middleBa }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1341,7 +1341,7 @@ func TestEthConfirmer_FindTxsRequiringRebroadcast(t *testing.T) { evmcfg := evmtest.NewChainScopedConfig(t, cfg) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) evmFromAddress := fromAddress @@ -1639,7 +1639,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WithConnectivityCheck(t *testing ctx := testutils.Context(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) kst := ksmocks.NewEth(t) @@ -1686,7 +1686,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WithConnectivityCheck(t *testing ctx := testutils.Context(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) kst := ksmocks.NewEth(t) @@ -1735,7 +1735,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_MaxFeeScenario(t *testing.T) { ctx := testutils.Context(t) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -1803,7 +1803,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { ctx := testutils.Context(t) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -2414,7 +2414,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_TerminallyUnderpriced_ThenGoesTh }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() evmcfg := evmtest.NewChainScopedConfig(t, cfg) @@ -2521,12 +2521,11 @@ func TestEthConfirmer_RebroadcastWhereNecessary_TerminallyUnderpriced_ThenGoesTh func TestEthConfirmer_RebroadcastWhereNecessary_WhenOutOfEth(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) ctx := testutils.Context(t) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -2660,11 +2659,10 @@ func TestEthConfirmer_EnsureConfirmedTransactionsInLongestChain(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) ctx := testutils.Context(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -2835,10 +2833,9 @@ func TestEthConfirmer_ForceRebroadcast(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) config := newTestChainScopedConfig(t) @@ -2939,7 +2936,7 @@ func TestEthConfirmer_ResumePendingRuns(t *testing.T) { config := configtest.NewTestGeneralConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) diff --git a/core/chains/evm/txmgr/evm_tx_store_test.go b/core/chains/evm/txmgr/evm_tx_store_test.go index ff5c7ec4abc..1d1d85c0960 100644 --- a/core/chains/evm/txmgr/evm_tx_store_test.go +++ b/core/chains/evm/txmgr/evm_tx_store_test.go @@ -8,6 +8,10 @@ import ( "time" "github.com/ethereum/go-ethereum/common" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/guregu/null.v4" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" "github.com/smartcontractkit/chainlink-common/pkg/logger" @@ -27,18 +31,12 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/pipeline" - - "github.com/google/uuid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "gopkg.in/guregu/null.v4" ) func TestORM_TransactionsWithAttempts(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ctx := testutils.Context(t) _, from := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -82,9 +80,8 @@ func TestORM_TransactionsWithAttempts(t *testing.T) { func TestORM_Transactions(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ctx := testutils.Context(t) _, from := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -122,8 +119,7 @@ func TestORM(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) orm := cltest.NewTestTxStore(t, db) _, fromAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) ctx := testutils.Context(t) @@ -190,9 +186,8 @@ func TestORM(t *testing.T) { func TestORM_FindTxAttemptConfirmedByTxIDs(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) orm := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ctx := testutils.Context(t) _, from := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -241,11 +236,10 @@ func TestORM_FindTxAttemptsRequiringResend(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - logCfg := pgtest.NewQConfig(true) txStore := cltest.NewTestTxStore(t, db) ctx := testutils.Context(t) - ethKeyStore := cltest.NewKeyStore(t, db, logCfg).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -329,8 +323,7 @@ func TestORM_UpdateBroadcastAts(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) orm := cltest.NewTestTxStore(t, db) _, fromAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) @@ -380,7 +373,7 @@ func TestORM_SetBroadcastBeforeBlockNum(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) etx := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 0, fromAddress) @@ -447,9 +440,8 @@ func TestORM_FindTxAttemptsConfirmedMissingReceipt(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -471,9 +463,8 @@ func TestORM_UpdateTxsUnconfirmed(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) originalBroadcastAt := time.Unix(1616509100, 0) @@ -491,9 +482,8 @@ func TestORM_FindTxAttemptsRequiringReceiptFetch(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -512,9 +502,8 @@ func TestORM_SaveFetchedReceipts(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) ctx := testutils.Context(t) @@ -547,9 +536,8 @@ func TestORM_MarkAllConfirmedMissingReceipt(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) ctx := testutils.Context(t) @@ -578,9 +566,8 @@ func TestORM_PreloadTxes(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("loads eth transaction", func(t *testing.T) { @@ -612,9 +599,8 @@ func TestORM_GetInProgressTxAttempts(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -633,9 +619,8 @@ func TestORM_FindTxesPendingCallback(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -709,7 +694,7 @@ func Test_FindTxWithIdempotencyKey(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("returns nil if no results", func(t *testing.T) { @@ -737,9 +722,8 @@ func TestORM_FindTxWithSequence(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("returns nil if no results", func(t *testing.T) { @@ -762,9 +746,8 @@ func TestORM_UpdateTxForRebroadcast(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) ctx := testutils.Context(t) @@ -827,9 +810,8 @@ func TestORM_FindTransactionsConfirmedInBlockRange(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -863,9 +845,8 @@ func TestORM_FindEarliestUnconfirmedBroadcastTime(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -887,9 +868,8 @@ func TestORM_FindEarliestUnconfirmedTxAttemptBlock(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) _, fromAddress2 := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -919,9 +899,8 @@ func TestORM_SaveInsufficientEthAttempt(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) defaultDuration, err := time.ParseDuration("5s") require.NoError(t, err) @@ -944,9 +923,8 @@ func TestORM_SaveSentAttempt(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) defaultDuration, err := time.ParseDuration("5s") require.NoError(t, err) @@ -970,9 +948,8 @@ func TestORM_SaveConfirmedMissingReceiptAttempt(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) defaultDuration, err := time.ParseDuration("5s") require.NoError(t, err) @@ -996,9 +973,8 @@ func TestORM_DeleteInProgressAttempt(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("deletes in_progress attempt", func(t *testing.T) { @@ -1019,9 +995,8 @@ func TestORM_SaveInProgressAttempt(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("saves new in_progress attempt if attempt is new", func(t *testing.T) { @@ -1061,9 +1036,8 @@ func TestORM_FindTxsRequiringGasBump(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1101,11 +1075,10 @@ func TestEthConfirmer_FindTxsRequiringResubmissionDueToInsufficientEth(t *testin t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) ctx := testutils.Context(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) _, otherAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1163,10 +1136,9 @@ func TestORM_MarkOldTxesMissingReceiptAsErrored(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) ctx := testutils.Context(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1200,9 +1172,8 @@ func TestORM_LoadEthTxesAttempts(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("load eth tx attempt", func(t *testing.T) { @@ -1254,9 +1225,8 @@ func TestORM_SaveReplacementInProgressAttempt(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("replace eth tx attempt", func(t *testing.T) { @@ -1278,9 +1248,8 @@ func TestORM_FindNextUnstartedTransactionFromAddress(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1306,9 +1275,8 @@ func TestORM_UpdateTxFatalError(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1331,9 +1299,8 @@ func TestORM_UpdateTxAttemptInProgressToBroadcast(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("update successful", func(t *testing.T) { @@ -1363,9 +1330,8 @@ func TestORM_UpdateTxUnstartedToInProgress(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) nonce := evmtypes.Nonce(123) @@ -1397,9 +1363,8 @@ func TestORM_UpdateTxUnstartedToInProgress(t *testing.T) { }) db = pgtest.NewSqlxDB(t) - cfg = newTestChainScopedConfig(t) txStore = cltest.NewTestTxStore(t, db) - ethKeyStore = cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore = cltest.NewKeyStore(t, db).Eth() _, fromAddress = cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("update replaces abandoned tx with same hash", func(t *testing.T) { @@ -1452,9 +1417,8 @@ func TestORM_GetTxInProgress(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("gets 0 in progress eth transaction", func(t *testing.T) { @@ -1476,9 +1440,8 @@ func TestORM_GetAbandonedTransactionsByBatch(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) _, enabled := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1534,9 +1497,8 @@ func TestORM_GetTxByID(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("no transaction", func(t *testing.T) { @@ -1557,9 +1519,8 @@ func TestORM_GetFatalTransactions(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) t.Run("gets 0 fatal eth transactions", func(t *testing.T) { @@ -1580,9 +1541,8 @@ func TestORM_HasInProgressTransaction(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1605,9 +1565,8 @@ func TestORM_CountUnconfirmedTransactions(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) _, otherAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -1626,9 +1585,8 @@ func TestORM_CountTransactionsByState(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress1 := cltest.MustInsertRandomKey(t, ethKeyStore) _, fromAddress2 := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -1647,9 +1605,8 @@ func TestORM_CountUnstartedTransactions(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) _, otherAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -1668,9 +1625,8 @@ func TestORM_CheckTxQueueCapacity(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) _, otherAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -1764,9 +1720,8 @@ func TestORM_CreateTransaction(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := newTxStore(t, db) - kst := cltest.NewKeyStore(t, db, cfg.Database()) + kst := cltest.NewKeyStore(t, db) _, fromAddress := cltest.MustInsertRandomKey(t, kst.Eth()) toAddress := testutils.NewAddress() @@ -1864,9 +1819,8 @@ func TestORM_PruneUnstartedTxQueue(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := txmgr.NewTxStore(db, logger.Test(t)) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() evmtest.NewEthClientMockWithDefaultChain(t) _, fromAddress := cltest.MustInsertRandomKeyReturningState(t, ethKeyStore) @@ -1893,9 +1847,8 @@ func TestORM_FindTxesWithAttemptsAndReceiptsByIdsAndState(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ctx := testutils.Context(t) _, from := cltest.MustInsertRandomKey(t, ethKeyStore) diff --git a/core/chains/evm/txmgr/reaper_test.go b/core/chains/evm/txmgr/reaper_test.go index 7918ed0e2ca..b3ce48b702c 100644 --- a/core/chains/evm/txmgr/reaper_test.go +++ b/core/chains/evm/txmgr/reaper_test.go @@ -15,7 +15,6 @@ import ( txmgrmocks "github.com/smartcontractkit/chainlink/v2/common/txmgr/types/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" ) @@ -44,9 +43,8 @@ func TestReaper_ReapTxes(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, from := cltest.MustInsertRandomKey(t, ethKeyStore) var nonce int64 diff --git a/core/chains/evm/txmgr/resender_test.go b/core/chains/evm/txmgr/resender_test.go index 57605c61785..8df5344f57c 100644 --- a/core/chains/evm/txmgr/resender_test.go +++ b/core/chains/evm/txmgr/resender_test.go @@ -30,9 +30,8 @@ func Test_EthResender_resendUnconfirmed(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - logCfg := pgtest.NewQConfig(true) lggr := logger.Test(t) - ethKeyStore := cltest.NewKeyStore(t, db, logCfg).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) {}) ccfg := evmtest.NewChainScopedConfig(t, cfg) @@ -101,9 +100,8 @@ func Test_EthResender_alertUnconfirmed(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - logCfg := pgtest.NewQConfig(true) lggr, o := logger.TestObserved(t, zapcore.DebugLevel) - ethKeyStore := cltest.NewKeyStore(t, db, logCfg).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) // Set this to the smallest non-zero value possible for the attempt to be eligible for resend delay := commonconfig.MustNewDuration(1 * time.Nanosecond) @@ -149,7 +147,7 @@ func Test_EthResender_Start(t *testing.T) { c.EVM[0].RPCDefaultBatchSize = ptr[uint32](1) }) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ccfg := evmtest.NewChainScopedConfig(t, cfg) _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) lggr := logger.Test(t) diff --git a/core/chains/evm/txmgr/tracker_test.go b/core/chains/evm/txmgr/tracker_test.go index eefd89c69eb..a0503253591 100644 --- a/core/chains/evm/txmgr/tracker_test.go +++ b/core/chains/evm/txmgr/tracker_test.go @@ -22,9 +22,8 @@ const waitTime = 5 * time.Millisecond func newTestEvmTrackerSetup(t *testing.T) (*txmgr.Tracker, txmgr.TestEvmTxStore, keystore.Eth, []common.Address) { db := pgtest.NewSqlxDB(t) - cfg := newTestChainScopedConfig(t) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() chainID := big.NewInt(0) var enabledAddresses []common.Address _, addr1 := cltest.MustInsertRandomKey(t, ethKeyStore, *ubig.NewI(chainID.Int64())) diff --git a/core/chains/evm/txmgr/txmgr_test.go b/core/chains/evm/txmgr/txmgr_test.go index 1774a2ad86e..691b83f8e4c 100644 --- a/core/chains/evm/txmgr/txmgr_test.go +++ b/core/chains/evm/txmgr/txmgr_test.go @@ -92,7 +92,7 @@ func TestTxm_SendNativeToken_DoesNotSendToZero(t *testing.T) { config, dbConfig, evmConfig := txmgr.MakeTestConfigs(t) - keyStore := cltest.NewKeyStore(t, db, dbConfig).Eth() + keyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) estimator := gas.NewEstimator(logger.Test(t), ethClient, config, evmConfig.GasEstimator()) txm, err := makeTestEvmTxm(t, db, ethClient, estimator, evmConfig, evmConfig.GasEstimator(), evmConfig.Transactions(), dbConfig, dbConfig.Listener(), keyStore) @@ -107,9 +107,8 @@ func TestTxm_CreateTransaction(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - kst := cltest.NewKeyStore(t, db, cfg.Database()) + kst := cltest.NewKeyStore(t, db) _, fromAddress := cltest.MustInsertRandomKey(t, kst.Eth()) toAddress := testutils.NewAddress() @@ -387,9 +386,8 @@ func newMockTxStrategy(t *testing.T) *commontxmmocks.TxStrategy { func TestTxm_CreateTransaction_OutOfEth(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - etKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + etKeyStore := cltest.NewKeyStore(t, db).Eth() thisKey, _ := cltest.RandomKey{Nonce: 1}.MustInsert(t, etKeyStore) otherKey, _ := cltest.RandomKey{Nonce: 1}.MustInsert(t, etKeyStore) @@ -528,7 +526,7 @@ func TestTxm_Reset(t *testing.T) { db := pgtest.NewSqlxDB(t) gcfg := configtest.NewTestGeneralConfig(t) cfg := evmtest.NewChainScopedConfig(t, gcfg) - kst := cltest.NewKeyStore(t, db, cfg.Database()) + kst := cltest.NewKeyStore(t, db) _, addr := cltest.RandomKey{}.MustInsert(t, kst.Eth()) _, addr2 := cltest.RandomKey{}.MustInsert(t, kst.Eth()) diff --git a/core/chains/evm/types/models_test.go b/core/chains/evm/types/models_test.go index 38dbfa76a0a..ef355a01bda 100644 --- a/core/chains/evm/types/models_test.go +++ b/core/chains/evm/types/models_test.go @@ -25,7 +25,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" ) @@ -93,8 +92,7 @@ func TestEthTx_GetID(t *testing.T) { func TestEthTxAttempt_GetSignedTx(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) tx := cltest.NewLegacyTransaction(uint64(42), testutils.NewAddress(), big.NewInt(142), 242, big.NewInt(342), []byte{1, 2, 3}) diff --git a/core/cmd/cosmos_keys_commands_test.go b/core/cmd/cosmos_keys_commands_test.go index 16609daadc6..7c3b4ed19f7 100644 --- a/core/cmd/cosmos_keys_commands_test.go +++ b/core/cmd/cosmos_keys_commands_test.go @@ -2,6 +2,7 @@ package cmd_test import ( "bytes" + "context" "flag" "fmt" "os" @@ -14,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/cosmoskey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -58,18 +60,20 @@ func TestShell_CosmosKeys(t *testing.T) { app := startNewApplicationV2(t, nil) ks := app.GetKeyStore().Cosmos() cleanup := func() { + ctx := context.Background() keys, err := ks.GetAll() require.NoError(t, err) for _, key := range keys { - require.NoError(t, utils.JustError(ks.Delete(key.ID()))) + require.NoError(t, utils.JustError(ks.Delete(ctx, key.ID()))) } requireCosmosKeyCount(t, app, 0) } t.Run("ListCosmosKeys", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().Cosmos().Create() + key, err := app.GetKeyStore().Cosmos().Create(ctx) require.NoError(t, err) requireCosmosKeyCount(t, app, 1) assert.Nil(t, cmd.NewCosmosKeysClient(client).ListKeys(cltest.EmptyCLIContext())) @@ -90,8 +94,9 @@ func TestShell_CosmosKeys(t *testing.T) { t.Run("DeleteCosmosKey", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - key, err := app.GetKeyStore().Cosmos().Create() + key, err := app.GetKeyStore().Cosmos().Create(ctx) require.NoError(t, err) requireCosmosKeyCount(t, app, 1) set := flag.NewFlagSet("test", 0) @@ -110,9 +115,10 @@ func TestShell_CosmosKeys(t *testing.T) { t.Run("ImportExportCosmosKey", func(tt *testing.T) { defer cleanup() defer deleteKeyExportFile(t) + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().Cosmos().Create() + _, err := app.GetKeyStore().Cosmos().Create(ctx) require.NoError(t, err) keys := requireCosmosKeyCount(t, app, 1) @@ -146,7 +152,7 @@ func TestShell_CosmosKeys(t *testing.T) { require.NoError(t, tclient.ExportKey(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, utils.JustError(app.GetKeyStore().Cosmos().Delete(key.ID()))) + require.NoError(t, utils.JustError(app.GetKeyStore().Cosmos().Delete(ctx, key.ID()))) requireCosmosKeyCount(t, app, 0) set = flag.NewFlagSet("test Cosmos import", 0) diff --git a/core/cmd/cosmos_transaction_commands_test.go b/core/cmd/cosmos_transaction_commands_test.go index 5b5454eed44..c3e6a048103 100644 --- a/core/cmd/cosmos_transaction_commands_test.go +++ b/core/cmd/cosmos_transaction_commands_test.go @@ -40,6 +40,7 @@ func TestMain(m *testing.M) { } func TestShell_SendCosmosCoins(t *testing.T) { + ctx := testutils.Context(t) // TODO(BCI-978): cleanup once SetupLocalCosmosNode is updated chainID := cosmostest.RandomChainID() cosmosChain := coscfg.Chain{} @@ -57,7 +58,7 @@ func TestShell_SendCosmosCoins(t *testing.T) { from := accounts[0] to := accounts[1] - require.NoError(t, app.GetKeyStore().Cosmos().Add(cosmoskey.Raw(from.PrivateKey.Bytes()).Key())) + require.NoError(t, app.GetKeyStore().Cosmos().Add(ctx, cosmoskey.Raw(from.PrivateKey.Bytes()).Key())) chain, err := app.GetRelayers().LegacyCosmosChains().Get(chainID) require.NoError(t, err) diff --git a/core/cmd/csa_keys_commands_test.go b/core/cmd/csa_keys_commands_test.go index a181922979a..86e1b7d544f 100644 --- a/core/cmd/csa_keys_commands_test.go +++ b/core/cmd/csa_keys_commands_test.go @@ -14,6 +14,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -53,9 +54,10 @@ func TestCSAKeyPresenter_RenderTable(t *testing.T) { func TestShell_ListCSAKeys(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) - key, err := app.GetKeyStore().CSA().Create() + key, err := app.GetKeyStore().CSA().Create(ctx) require.NoError(t, err) requireCSAKeyCount(t, app, 1) @@ -85,11 +87,12 @@ func TestShell_ImportExportCsaKey(t *testing.T) { t.Parallel() defer deleteKeyExportFile(t) + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().CSA().Create() + _, err := app.GetKeyStore().CSA().Create(ctx) require.NoError(t, err) keys := requireCSAKeyCount(t, app, 1) @@ -122,7 +125,7 @@ func TestShell_ImportExportCsaKey(t *testing.T) { require.NoError(t, client.ExportCSAKey(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, utils.JustError(app.GetKeyStore().CSA().Delete(key.ID()))) + require.NoError(t, utils.JustError(app.GetKeyStore().CSA().Delete(ctx, key.ID()))) requireCSAKeyCount(t, app, 0) //Import test diff --git a/core/cmd/dkgencrypt_keys_commands_test.go b/core/cmd/dkgencrypt_keys_commands_test.go index b4c6d6f6e91..7b0de4f7774 100644 --- a/core/cmd/dkgencrypt_keys_commands_test.go +++ b/core/cmd/dkgencrypt_keys_commands_test.go @@ -2,6 +2,7 @@ package cmd_test import ( "bytes" + "context" "flag" "fmt" "os" @@ -14,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/dkgencryptkey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -58,18 +60,20 @@ func TestShell_DKGEncryptKeys(t *testing.T) { app := startNewApplicationV2(t, nil) ks := app.GetKeyStore().DKGEncrypt() cleanup := func() { + ctx := context.Background() keys, err := ks.GetAll() assert.NoError(t, err) for _, key := range keys { - assert.NoError(t, utils.JustError(ks.Delete(key.ID()))) + assert.NoError(t, utils.JustError(ks.Delete(ctx, key.ID()))) } requireDKGEncryptKeyCount(t, app, 0) } t.Run("ListDKGEncryptKeys", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().DKGEncrypt().Create() + key, err := app.GetKeyStore().DKGEncrypt().Create(ctx) assert.NoError(tt, err) requireDKGEncryptKeyCount(t, app, 1) assert.Nil(t, cmd.NewDKGEncryptKeysClient(client).ListKeys(cltest.EmptyCLIContext())) @@ -89,8 +93,9 @@ func TestShell_DKGEncryptKeys(t *testing.T) { t.Run("DeleteDKGEncryptKey", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - key, err := app.GetKeyStore().DKGEncrypt().Create() + key, err := app.GetKeyStore().DKGEncrypt().Create(ctx) assert.NoError(tt, err) requireDKGEncryptKeyCount(tt, app, 1) set := flag.NewFlagSet("test", 0) @@ -110,9 +115,10 @@ func TestShell_DKGEncryptKeys(t *testing.T) { t.Run("ImportExportDKGEncryptKey", func(tt *testing.T) { defer cleanup() defer deleteKeyExportFile(tt) + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().DKGEncrypt().Create() + _, err := app.GetKeyStore().DKGEncrypt().Create(ctx) require.NoError(tt, err) keys := requireDKGEncryptKeyCount(tt, app, 1) @@ -146,7 +152,7 @@ func TestShell_DKGEncryptKeys(t *testing.T) { require.NoError(tt, cmd.NewDKGEncryptKeysClient(client).ExportKey(c)) require.NoError(tt, utils.JustError(os.Stat(keyName))) - require.NoError(tt, utils.JustError(app.GetKeyStore().DKGEncrypt().Delete(key.ID()))) + require.NoError(tt, utils.JustError(app.GetKeyStore().DKGEncrypt().Delete(ctx, key.ID()))) requireDKGEncryptKeyCount(tt, app, 0) //Import test diff --git a/core/cmd/dkgsign_keys_commands_test.go b/core/cmd/dkgsign_keys_commands_test.go index 717f988b328..777e8a0a3c3 100644 --- a/core/cmd/dkgsign_keys_commands_test.go +++ b/core/cmd/dkgsign_keys_commands_test.go @@ -2,6 +2,7 @@ package cmd_test import ( "bytes" + "context" "flag" "fmt" "os" @@ -14,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/dkgsignkey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -58,18 +60,20 @@ func TestShell_DKGSignKeys(t *testing.T) { app := startNewApplicationV2(t, nil) ks := app.GetKeyStore().DKGSign() cleanup := func() { + ctx := context.Background() keys, err := ks.GetAll() assert.NoError(t, err) for _, key := range keys { - assert.NoError(t, utils.JustError(ks.Delete(key.ID()))) + assert.NoError(t, utils.JustError(ks.Delete(ctx, key.ID()))) } requireDKGSignKeyCount(t, app, 0) } t.Run("ListDKGSignKeys", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().DKGSign().Create() + key, err := app.GetKeyStore().DKGSign().Create(ctx) assert.NoError(tt, err) requireDKGSignKeyCount(t, app, 1) assert.Nil(t, cmd.NewDKGSignKeysClient(client).ListKeys(cltest.EmptyCLIContext())) @@ -89,8 +93,9 @@ func TestShell_DKGSignKeys(t *testing.T) { t.Run("DeleteDKGSignKey", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - key, err := app.GetKeyStore().DKGSign().Create() + key, err := app.GetKeyStore().DKGSign().Create(ctx) assert.NoError(tt, err) requireDKGSignKeyCount(tt, app, 1) set := flag.NewFlagSet("test", 0) @@ -109,9 +114,10 @@ func TestShell_DKGSignKeys(t *testing.T) { t.Run("ImportExportDKGSignKey", func(tt *testing.T) { defer cleanup() defer deleteKeyExportFile(tt) + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().DKGSign().Create() + _, err := app.GetKeyStore().DKGSign().Create(ctx) require.NoError(tt, err) keys := requireDKGSignKeyCount(tt, app, 1) @@ -145,7 +151,7 @@ func TestShell_DKGSignKeys(t *testing.T) { require.NoError(tt, cmd.NewDKGSignKeysClient(client).ExportKey(c)) require.NoError(tt, utils.JustError(os.Stat(keyName))) - require.NoError(tt, utils.JustError(app.GetKeyStore().DKGSign().Delete(key.ID()))) + require.NoError(tt, utils.JustError(app.GetKeyStore().DKGSign().Delete(ctx, key.ID()))) requireDKGSignKeyCount(tt, app, 0) set = flag.NewFlagSet("test DKGSign import", 0) diff --git a/core/cmd/key_store_authenticator.go b/core/cmd/key_store_authenticator.go index 0707aa5087d..6ad4b0ef2ba 100644 --- a/core/cmd/key_store_authenticator.go +++ b/core/cmd/key_store_authenticator.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "fmt" "strings" @@ -20,8 +21,8 @@ type keystorePassword interface { Keystore() string } -func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, password keystorePassword) error { - isEmpty, err := keyStore.IsEmpty() +func (auth TerminalKeyStoreAuthenticator) authenticate(ctx context.Context, keyStore keystore.Master, password keystorePassword) error { + isEmpty, err := keyStore.IsEmpty(ctx) if err != nil { return errors.Wrap(err, "error determining if keystore is empty") } @@ -34,7 +35,7 @@ func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, if err = auth.validatePasswordStrength(pw); err != nil && isEmpty { return err } - return keyStore.Unlock(pw) + return keyStore.Unlock(ctx, pw) } interactive := auth.Prompter.IsTerminal() if !interactive { @@ -47,7 +48,7 @@ func (auth TerminalKeyStoreAuthenticator) authenticate(keyStore keystore.Master, if err != nil { return err } - return keyStore.Unlock(pw) + return keyStore.Unlock(ctx, pw) } func (auth TerminalKeyStoreAuthenticator) validatePasswordStrength(password string) error { diff --git a/core/cmd/ocr2_keys_commands_test.go b/core/cmd/ocr2_keys_commands_test.go index eff44685612..b0c62f01aa5 100644 --- a/core/cmd/ocr2_keys_commands_test.go +++ b/core/cmd/ocr2_keys_commands_test.go @@ -2,6 +2,7 @@ package cmd_test import ( "bytes" + "context" "encoding/hex" "flag" "os" @@ -14,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocr2key" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -71,19 +73,21 @@ func TestShell_OCR2Keys(t *testing.T) { app := startNewApplicationV2(t, nil) ks := app.GetKeyStore().OCR2() cleanup := func() { + ctx := context.Background() keys, err := app.GetKeyStore().OCR2().GetAll() require.NoError(t, err) for _, key := range keys { - require.NoError(t, ks.Delete(key.ID())) + require.NoError(t, ks.Delete(ctx, key.ID())) } requireOCR2KeyCount(t, app, 0) } t.Run("ListOCR2KeyBundles", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().OCR2().Create("evm") + key, err := app.GetKeyStore().OCR2().Create(ctx, "evm") require.NoError(t, err) requireOCR2KeyCount(t, app, 1) assert.Nil(t, client.ListOCR2KeyBundles(cltest.EmptyCLIContext())) @@ -113,9 +117,10 @@ func TestShell_OCR2Keys(t *testing.T) { t.Run("DeleteOCR2KeyBundle", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().OCR2().Create("evm") + key, err := app.GetKeyStore().OCR2().Create(ctx, "evm") require.NoError(t, err) requireOCR2KeyCount(t, app, 1) set := flag.NewFlagSet("test", 0) @@ -136,9 +141,10 @@ func TestShell_OCR2Keys(t *testing.T) { t.Run("ImportExportOCR2Key", func(tt *testing.T) { defer cleanup() defer deleteKeyExportFile(t) + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - err := app.KeyStore.OCR2().Add(cltest.DefaultOCR2Key) + err := app.KeyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key) require.NoError(t, err) keys := requireOCR2KeyCount(t, app, 1) @@ -171,7 +177,7 @@ func TestShell_OCR2Keys(t *testing.T) { require.NoError(t, client.ExportOCR2Key(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, app.GetKeyStore().OCR2().Delete(key.ID())) + require.NoError(t, app.GetKeyStore().OCR2().Delete(ctx, key.ID())) requireOCR2KeyCount(t, app, 0) set = flag.NewFlagSet("test OCR2 import", 0) diff --git a/core/cmd/ocr2vrf_configure_commands.go b/core/cmd/ocr2vrf_configure_commands.go index 1f9e3f0bc98..7f5b0321480 100644 --- a/core/cmd/ocr2vrf_configure_commands.go +++ b/core/cmd/ocr2vrf_configure_commands.go @@ -352,7 +352,7 @@ func (s *Shell) authorizeForwarder(c *cli.Context, db *sqlx.DB, chainID int64, e } 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 { + if err := cli.KeyStoreAuthenticator.authenticate(ctx, keyStore, cli.Config.Password()); err != nil { return errors.Wrap(err, "error authenticating keystore") } @@ -382,19 +382,19 @@ func setupKeystore(ctx context.Context, cli *Shell, app chainlink.Application, k enabledChains = append(enabledChains, chaintype.StarkNet) } - if err := keyStore.OCR2().EnsureKeys(enabledChains...); err != nil { + if err := keyStore.OCR2().EnsureKeys(ctx, enabledChains...); err != nil { return errors.Wrap(err, "failed to ensure ocr key") } - if err := keyStore.DKGSign().EnsureKey(); err != nil { + if err := keyStore.DKGSign().EnsureKey(ctx); err != nil { return errors.Wrap(err, "failed to ensure dkgsign key") } - if err := keyStore.DKGEncrypt().EnsureKey(); err != nil { + if err := keyStore.DKGEncrypt().EnsureKey(ctx); err != nil { return errors.Wrap(err, "failed to ensure dkgencrypt key") } - if err := keyStore.P2P().EnsureKey(); err != nil { + if err := keyStore.P2P().EnsureKey(ctx); err != nil { return errors.Wrap(err, "failed to ensure p2p key") } diff --git a/core/cmd/ocr_keys_commands_test.go b/core/cmd/ocr_keys_commands_test.go index f5da3294903..42d7451edbe 100644 --- a/core/cmd/ocr_keys_commands_test.go +++ b/core/cmd/ocr_keys_commands_test.go @@ -14,6 +14,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocrkey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -65,11 +66,12 @@ func TestOCRKeyBundlePresenter_RenderTable(t *testing.T) { func TestShell_ListOCRKeyBundles(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().OCR().Create() + key, err := app.GetKeyStore().OCR().Create(ctx) require.NoError(t, err) requireOCRKeyCount(t, app, 1) @@ -101,11 +103,12 @@ func TestShell_CreateOCRKeyBundle(t *testing.T) { func TestShell_DeleteOCRKeyBundle(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().OCR().Create() + key, err := app.GetKeyStore().OCR().Create(ctx) require.NoError(t, err) requireOCRKeyCount(t, app, 1) @@ -128,11 +131,12 @@ func TestShell_DeleteOCRKeyBundle(t *testing.T) { func TestShell_ImportExportOCRKey(t *testing.T) { defer deleteKeyExportFile(t) + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) client, _ := app.NewShellAndRenderer() - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) keys := requireOCRKeyCount(t, app, 1) key := keys[0] @@ -164,7 +168,7 @@ func TestShell_ImportExportOCRKey(t *testing.T) { require.NoError(t, client.ExportOCRKey(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, utils.JustError(app.GetKeyStore().OCR().Delete(key.ID()))) + require.NoError(t, utils.JustError(app.GetKeyStore().OCR().Delete(ctx, key.ID()))) requireOCRKeyCount(t, app, 0) set = flag.NewFlagSet("test OCR import", 0) diff --git a/core/cmd/p2p_keys_commands_test.go b/core/cmd/p2p_keys_commands_test.go index 87269e02711..12d22e7c16b 100644 --- a/core/cmd/p2p_keys_commands_test.go +++ b/core/cmd/p2p_keys_commands_test.go @@ -14,6 +14,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/p2pkey" @@ -61,9 +62,10 @@ func TestP2PKeyPresenter_RenderTable(t *testing.T) { func TestShell_ListP2PKeys(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) - key, err := app.GetKeyStore().P2P().Create() + key, err := app.GetKeyStore().P2P().Create(ctx) require.NoError(t, err) requireP2PKeyCount(t, app, 1) @@ -92,11 +94,12 @@ func TestShell_CreateP2PKey(t *testing.T) { func TestShell_DeleteP2PKey(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) app := startNewApplicationV2(t, nil) client, _ := app.NewShellAndRenderer() - key, err := app.GetKeyStore().P2P().Create() + key, err := app.GetKeyStore().P2P().Create(ctx) require.NoError(t, err) requireP2PKeyCount(t, app, 1) @@ -118,12 +121,13 @@ func TestShell_DeleteP2PKey(t *testing.T) { func TestShell_ImportExportP2PKeyBundle(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) defer deleteKeyExportFile(t) app := startNewApplicationV2(t, nil) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().P2P().Create() + _, err := app.GetKeyStore().P2P().Create(ctx) require.NoError(t, err) keys := requireP2PKeyCount(t, app, 1) @@ -156,7 +160,7 @@ func TestShell_ImportExportP2PKeyBundle(t *testing.T) { require.NoError(t, client.ExportP2PKey(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, utils.JustError(app.GetKeyStore().P2P().Delete(key.PeerID()))) + require.NoError(t, utils.JustError(app.GetKeyStore().P2P().Delete(ctx, key.PeerID()))) requireP2PKeyCount(t, app, 0) set = flag.NewFlagSet("test P2P import", 0) diff --git a/core/cmd/shell.go b/core/cmd/shell.go index de84ed401a6..bc58c5cab6d 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -154,7 +154,7 @@ func (n ChainlinkAppFactory) NewApplication(ctx context.Context, cfg chainlink.G return nil, err } - keyStore := keystore.New(sqlxDB, utils.GetScryptParams(cfg), appLggr, cfg.Database()) + keyStore := keystore.New(db, utils.GetScryptParams(cfg), appLggr) mailMon := mailbox.NewMonitor(cfg.AppID().String(), appLggr.Named("Mailbox")) loopRegistry := plugins.NewLoopRegistry(appLggr, cfg.Tracing()) diff --git a/core/cmd/shell_local.go b/core/cmd/shell_local.go index 0639d5a21df..66ceafa5cb2 100644 --- a/core/cmd/shell_local.go +++ b/core/cmd/shell_local.go @@ -364,7 +364,7 @@ func (s *Shell) runNode(c *cli.Context) error { // Local shell initialization always uses local auth users table for admin auth authProviderORM := app.BasicAdminUsersORM() keyStore := app.GetKeyStore() - err = s.KeyStoreAuthenticator.authenticate(keyStore, s.Config.Password()) + err = s.KeyStoreAuthenticator.authenticate(rootCtx, keyStore, s.Config.Password()) if err != nil { return errors.Wrap(err, "error authenticating keystore") } @@ -390,7 +390,7 @@ func (s *Shell) runNode(c *cli.Context) error { } if s.Config.OCR().Enabled() { - err2 := app.GetKeyStore().OCR().EnsureKey() + err2 := app.GetKeyStore().OCR().EnsureKey(rootCtx) if err2 != nil { return errors.Wrap(err2, "failed to ensure ocr key") } @@ -409,37 +409,37 @@ func (s *Shell) runNode(c *cli.Context) error { if s.Config.StarkNetEnabled() { enabledChains = append(enabledChains, chaintype.StarkNet) } - err2 := app.GetKeyStore().OCR2().EnsureKeys(enabledChains...) + err2 := app.GetKeyStore().OCR2().EnsureKeys(rootCtx, enabledChains...) if err2 != nil { return errors.Wrap(err2, "failed to ensure ocr key") } } if s.Config.P2P().Enabled() { - err2 := app.GetKeyStore().P2P().EnsureKey() + err2 := app.GetKeyStore().P2P().EnsureKey(rootCtx) if err2 != nil { return errors.Wrap(err2, "failed to ensure p2p key") } } if s.Config.CosmosEnabled() { - err2 := app.GetKeyStore().Cosmos().EnsureKey() + err2 := app.GetKeyStore().Cosmos().EnsureKey(rootCtx) if err2 != nil { return errors.Wrap(err2, "failed to ensure cosmos key") } } if s.Config.SolanaEnabled() { - err2 := app.GetKeyStore().Solana().EnsureKey() + err2 := app.GetKeyStore().Solana().EnsureKey(rootCtx) if err2 != nil { return errors.Wrap(err2, "failed to ensure solana key") } } if s.Config.StarkNetEnabled() { - err2 := app.GetKeyStore().StarkNet().EnsureKey() + err2 := app.GetKeyStore().StarkNet().EnsureKey(rootCtx) if err2 != nil { return errors.Wrap(err2, "failed to ensure starknet key") } } - err2 := app.GetKeyStore().CSA().EnsureKey() + err2 := app.GetKeyStore().CSA().EnsureKey(rootCtx) if err2 != nil { return errors.Wrap(err2, "failed to ensure CSA key") } @@ -621,7 +621,7 @@ func (s *Shell) RebroadcastTransactions(c *cli.Context) (err error) { return s.errorOut(fmt.Errorf("error validating configuration: %+v", err)) } - err = keyStore.Unlock(s.Config.Password().Keystore()) + err = keyStore.Unlock(ctx, s.Config.Password().Keystore()) if err != nil { return s.errorOut(errors.Wrap(err, "error authenticating keystore")) } diff --git a/core/cmd/shell_local_test.go b/core/cmd/shell_local_test.go index 6ac401e906c..0db99d1a57a 100644 --- a/core/cmd/shell_local_test.go +++ b/core/cmd/shell_local_test.go @@ -80,7 +80,7 @@ func TestShell_RunNodeWithPasswords(t *testing.T) { c.Insecure.OCRDevelopmentMode = nil }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) authProviderORM := localauth.NewORM(db, time.Minute, logger.TestLogger(t), audit.NoopLogger) lggr := logger.TestLogger(t) @@ -181,7 +181,7 @@ func TestShell_RunNodeWithAPICredentialsFile(t *testing.T) { // create/run with a new admin user pgtest.MustExec(t, db, "DELETE FROM users;") - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) _, err := keyStore.Eth().Create(testutils.Context(t), &cltest.FixtureChainID) require.NoError(t, err) @@ -290,7 +290,7 @@ func TestShell_RebroadcastTransactions_Txm(t *testing.T) { // seems to be needed for config validate c.Insecure.OCRDevelopmentMode = nil }) - keyStore := cltest.NewKeyStore(t, sqlxDB, config.Database()) + keyStore := cltest.NewKeyStore(t, sqlxDB) _, fromAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) txStore := cltest.NewTestTxStore(t, sqlxDB) @@ -370,7 +370,7 @@ func TestShell_RebroadcastTransactions_OutsideRange_Txm(t *testing.T) { c.Insecure.OCRDevelopmentMode = nil }) - keyStore := cltest.NewKeyStore(t, sqlxDB, config.Database()) + keyStore := cltest.NewKeyStore(t, sqlxDB) _, fromAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) @@ -446,7 +446,7 @@ func TestShell_RebroadcastTransactions_AddressCheck(t *testing.T) { c.Insecure.OCRDevelopmentMode = nil }) - keyStore := cltest.NewKeyStore(t, sqlxDB, config.Database()) + keyStore := cltest.NewKeyStore(t, sqlxDB) _, fromAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) diff --git a/core/cmd/shell_remote_test.go b/core/cmd/shell_remote_test.go index 0d8d0b7b459..a8c054cd9be 100644 --- a/core/cmd/shell_remote_test.go +++ b/core/cmd/shell_remote_test.go @@ -565,6 +565,7 @@ func TestShell_ConfigV2(t *testing.T) { func TestShell_RunOCRJob_HappyPath(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].Enabled = ptr(true) c.OCR.Enabled = ptr(true) @@ -577,7 +578,7 @@ func TestShell_RunOCRJob_HappyPath(t *testing.T) { }) client, _ := app.NewShellAndRenderer() - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) _, bridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) _, bridge2 := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) diff --git a/core/cmd/solana_keys_commands_test.go b/core/cmd/solana_keys_commands_test.go index d58c3657019..897031877c1 100644 --- a/core/cmd/solana_keys_commands_test.go +++ b/core/cmd/solana_keys_commands_test.go @@ -2,6 +2,7 @@ package cmd_test import ( "bytes" + "context" "flag" "fmt" "os" @@ -14,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/solkey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -58,18 +60,20 @@ func TestShell_SolanaKeys(t *testing.T) { app := startNewApplicationV2(t, nil) ks := app.GetKeyStore().Solana() cleanup := func() { + ctx := context.Background() keys, err := ks.GetAll() require.NoError(t, err) for _, key := range keys { - require.NoError(t, utils.JustError(ks.Delete(key.ID()))) + require.NoError(t, utils.JustError(ks.Delete(ctx, key.ID()))) } requireSolanaKeyCount(t, app, 0) } t.Run("ListSolanaKeys", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().Solana().Create() + key, err := app.GetKeyStore().Solana().Create(ctx) require.NoError(t, err) requireSolanaKeyCount(t, app, 1) assert.Nil(t, cmd.NewSolanaKeysClient(client).ListKeys(cltest.EmptyCLIContext())) @@ -90,8 +94,9 @@ func TestShell_SolanaKeys(t *testing.T) { t.Run("DeleteSolanaKey", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - key, err := app.GetKeyStore().Solana().Create() + key, err := app.GetKeyStore().Solana().Create(ctx) require.NoError(t, err) requireSolanaKeyCount(t, app, 1) set := flag.NewFlagSet("test", 0) @@ -111,9 +116,10 @@ func TestShell_SolanaKeys(t *testing.T) { t.Run("ImportExportSolanaKey", func(tt *testing.T) { defer cleanup() defer deleteKeyExportFile(t) + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().Solana().Create() + _, err := app.GetKeyStore().Solana().Create(ctx) require.NoError(t, err) keys := requireSolanaKeyCount(t, app, 1) @@ -146,7 +152,7 @@ func TestShell_SolanaKeys(t *testing.T) { require.NoError(t, cmd.NewSolanaKeysClient(client).ExportKey(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, utils.JustError(app.GetKeyStore().Solana().Delete(key.ID()))) + require.NoError(t, utils.JustError(app.GetKeyStore().Solana().Delete(ctx, key.ID()))) requireSolanaKeyCount(t, app, 0) set = flag.NewFlagSet("test Solana import", 0) diff --git a/core/cmd/solana_transaction_commands_test.go b/core/cmd/solana_transaction_commands_test.go index b190caec51b..c26bd89ab94 100644 --- a/core/cmd/solana_transaction_commands_test.go +++ b/core/cmd/solana_transaction_commands_test.go @@ -19,11 +19,13 @@ import ( "github.com/smartcontractkit/chainlink-solana/pkg/solana" solanaClient "github.com/smartcontractkit/chainlink-solana/pkg/solana/client" solcfg "github.com/smartcontractkit/chainlink-solana/pkg/solana/config" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/cmd" ) func TestShell_SolanaSendSol(t *testing.T) { + ctx := testutils.Context(t) chainID := "localnet" url := solanaClient.SetupLocalSolNode(t) node := solcfg.Node{ @@ -36,7 +38,7 @@ func TestShell_SolanaSendSol(t *testing.T) { Enabled: ptr(true), } app := solanaStartNewApplication(t, &cfg) - from, err := app.GetKeyStore().Solana().Create() + from, err := app.GetKeyStore().Solana().Create(ctx) require.NoError(t, err) to, err := solanago.NewRandomPrivateKey() require.NoError(t, err) diff --git a/core/cmd/starknet_keys_commands_test.go b/core/cmd/starknet_keys_commands_test.go index 0cf0065129d..5823a80b46d 100644 --- a/core/cmd/starknet_keys_commands_test.go +++ b/core/cmd/starknet_keys_commands_test.go @@ -2,6 +2,7 @@ package cmd_test import ( "bytes" + "context" "flag" "fmt" "os" @@ -14,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/cmd" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/starkkey" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" @@ -57,18 +59,20 @@ func TestShell_StarkNetKeys(t *testing.T) { app := startNewApplicationV2(t, nil) ks := app.GetKeyStore().StarkNet() cleanup := func() { + ctx := context.Background() keys, err := ks.GetAll() require.NoError(t, err) for _, key := range keys { - require.NoError(t, utils.JustError(ks.Delete(key.ID()))) + require.NoError(t, utils.JustError(ks.Delete(ctx, key.ID()))) } requireStarkNetKeyCount(t, app, 0) } t.Run("ListStarkNetKeys", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, r := app.NewShellAndRenderer() - key, err := app.GetKeyStore().StarkNet().Create() + key, err := app.GetKeyStore().StarkNet().Create(ctx) require.NoError(t, err) requireStarkNetKeyCount(t, app, 1) assert.Nil(t, cmd.NewStarkNetKeysClient(client).ListKeys(cltest.EmptyCLIContext())) @@ -89,8 +93,9 @@ func TestShell_StarkNetKeys(t *testing.T) { t.Run("DeleteStarkNetKey", func(tt *testing.T) { defer cleanup() + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - key, err := app.GetKeyStore().StarkNet().Create() + key, err := app.GetKeyStore().StarkNet().Create(ctx) require.NoError(t, err) requireStarkNetKeyCount(t, app, 1) set := flag.NewFlagSet("test", 0) @@ -110,9 +115,10 @@ func TestShell_StarkNetKeys(t *testing.T) { t.Run("ImportExportStarkNetKey", func(tt *testing.T) { defer cleanup() defer deleteKeyExportFile(t) + ctx := testutils.Context(t) client, _ := app.NewShellAndRenderer() - _, err := app.GetKeyStore().StarkNet().Create() + _, err := app.GetKeyStore().StarkNet().Create(ctx) require.NoError(t, err) keys := requireStarkNetKeyCount(t, app, 1) @@ -145,7 +151,7 @@ func TestShell_StarkNetKeys(t *testing.T) { require.NoError(t, cmd.NewStarkNetKeysClient(client).ExportKey(c)) require.NoError(t, utils.JustError(os.Stat(keyName))) - require.NoError(t, utils.JustError(app.GetKeyStore().StarkNet().Delete(key.ID()))) + require.NoError(t, utils.JustError(app.GetKeyStore().StarkNet().Delete(ctx, key.ID()))) requireStarkNetKeyCount(t, app, 0) set = flag.NewFlagSet("test StarkNet import", 0) diff --git a/core/gethwrappers/keystone/generated/keystone_capability_registry/keystone_capability_registry.go b/core/gethwrappers/keystone/generated/keystone_capability_registry/keystone_capability_registry.go new file mode 100644 index 00000000000..45ae103ac56 --- /dev/null +++ b/core/gethwrappers/keystone/generated/keystone_capability_registry/keystone_capability_registry.go @@ -0,0 +1,768 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package keystone_capability_registry + +import ( + "errors" + "fmt" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" + "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated" +) + +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +type Capability struct { + CapabilityType [32]byte + Version [32]byte +} + +var CapabilityRegistryMetaData = &bind.MetaData{ + ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"capabilityId\",\"type\":\"bytes32\"}],\"name\":\"CapabilityAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"OwnershipTransferRequested\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"acceptOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"capabilityType\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"version\",\"type\":\"bytes32\"}],\"internalType\":\"structCapability\",\"name\":\"capability\",\"type\":\"tuple\"}],\"name\":\"addCapability\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"capabilityID\",\"type\":\"bytes32\"}],\"name\":\"getCapability\",\"outputs\":[{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"capabilityType\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"version\",\"type\":\"bytes32\"}],\"internalType\":\"structCapability\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"capabilityType\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"version\",\"type\":\"bytes32\"}],\"name\":\"getCapabilityID\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"typeAndVersion\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}]", + Bin: "0x608060405234801561001057600080fd5b5033806000816100675760405162461bcd60e51b815260206004820152601860248201527f43616e6e6f7420736574206f776e657220746f207a65726f000000000000000060448201526064015b60405180910390fd5b600080546001600160a01b0319166001600160a01b0384811691909117909155811615610097576100978161009f565b505050610148565b336001600160a01b038216036100f75760405162461bcd60e51b815260206004820152601760248201527f43616e6e6f74207472616e7366657220746f2073656c66000000000000000000604482015260640161005e565b600180546001600160a01b0319166001600160a01b0383811691821790925560008054604051929316917fed8889f560326eb138920d842192f0eb3dd22b4f139c87a2c57538e05bae12789190a350565b6105e5806101576000396000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c806379ba50971161005b57806379ba5097146101275780638da5cb5b1461012f5780639cb7c5f414610157578063f2fde38b146101be57600080fd5b8063181f5a7714610082578063229111f5146100ca5780636e5f286914610112575b600080fd5b604080518082018252601881527f4361706162696c697479526567697374727920312e302e300000000000000000602082015290516100c191906104dc565b60405180910390f35b6101046100d8366004610548565b604080516020808201949094528082019290925280518083038201815260609092019052805191012090565b6040519081526020016100c1565b61012561012036600461056a565b6101d1565b005b61012561024e565b60005460405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100c1565b6101a3610165366004610582565b604080518082019091526000808252602082015250600090815260026020908152604091829020825180840190935280548352600101549082015290565b604080518251815260209283015192810192909252016100c1565b6101256101cc36600461059b565b610350565b6101d9610364565b60408051823560208083018290528085013583850181905284518085038601815260609094018086528451948301949094206000818152600290935294822092835560019092019190915582917f65610e5677eedff94555572640e442f89848a109ef8593fa927ac30b2565ff069190a25050565b60015473ffffffffffffffffffffffffffffffffffffffff1633146102d4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f4d7573742062652070726f706f736564206f776e65720000000000000000000060448201526064015b60405180910390fd5b60008054337fffffffffffffffffffffffff00000000000000000000000000000000000000008083168217845560018054909116905560405173ffffffffffffffffffffffffffffffffffffffff90921692909183917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a350565b610358610364565b610361816103e7565b50565b60005473ffffffffffffffffffffffffffffffffffffffff1633146103e5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f4f6e6c792063616c6c61626c65206279206f776e65720000000000000000000060448201526064016102cb565b565b3373ffffffffffffffffffffffffffffffffffffffff821603610466576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f43616e6e6f74207472616e7366657220746f2073656c6600000000000000000060448201526064016102cb565b600180547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83811691821790925560008054604051929316917fed8889f560326eb138920d842192f0eb3dd22b4f139c87a2c57538e05bae12789190a350565b600060208083528351808285015260005b81811015610509578581018301518582016040015282016104ed565b5060006040828601015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8301168501019250505092915050565b6000806040838503121561055b57600080fd5b50508035926020909101359150565b60006040828403121561057c57600080fd5b50919050565b60006020828403121561059457600080fd5b5035919050565b6000602082840312156105ad57600080fd5b813573ffffffffffffffffffffffffffffffffffffffff811681146105d157600080fd5b939250505056fea164736f6c6343000813000a", +} + +var CapabilityRegistryABI = CapabilityRegistryMetaData.ABI + +var CapabilityRegistryBin = CapabilityRegistryMetaData.Bin + +func DeployCapabilityRegistry(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *CapabilityRegistry, error) { + parsed, err := CapabilityRegistryMetaData.GetAbi() + if err != nil { + return common.Address{}, nil, nil, err + } + if parsed == nil { + return common.Address{}, nil, nil, errors.New("GetABI returned nil") + } + + address, tx, contract, err := bind.DeployContract(auth, *parsed, common.FromHex(CapabilityRegistryBin), backend) + if err != nil { + return common.Address{}, nil, nil, err + } + return address, tx, &CapabilityRegistry{address: address, abi: *parsed, CapabilityRegistryCaller: CapabilityRegistryCaller{contract: contract}, CapabilityRegistryTransactor: CapabilityRegistryTransactor{contract: contract}, CapabilityRegistryFilterer: CapabilityRegistryFilterer{contract: contract}}, nil +} + +type CapabilityRegistry struct { + address common.Address + abi abi.ABI + CapabilityRegistryCaller + CapabilityRegistryTransactor + CapabilityRegistryFilterer +} + +type CapabilityRegistryCaller struct { + contract *bind.BoundContract +} + +type CapabilityRegistryTransactor struct { + contract *bind.BoundContract +} + +type CapabilityRegistryFilterer struct { + contract *bind.BoundContract +} + +type CapabilityRegistrySession struct { + Contract *CapabilityRegistry + CallOpts bind.CallOpts + TransactOpts bind.TransactOpts +} + +type CapabilityRegistryCallerSession struct { + Contract *CapabilityRegistryCaller + CallOpts bind.CallOpts +} + +type CapabilityRegistryTransactorSession struct { + Contract *CapabilityRegistryTransactor + TransactOpts bind.TransactOpts +} + +type CapabilityRegistryRaw struct { + Contract *CapabilityRegistry +} + +type CapabilityRegistryCallerRaw struct { + Contract *CapabilityRegistryCaller +} + +type CapabilityRegistryTransactorRaw struct { + Contract *CapabilityRegistryTransactor +} + +func NewCapabilityRegistry(address common.Address, backend bind.ContractBackend) (*CapabilityRegistry, error) { + abi, err := abi.JSON(strings.NewReader(CapabilityRegistryABI)) + if err != nil { + return nil, err + } + contract, err := bindCapabilityRegistry(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &CapabilityRegistry{address: address, abi: abi, CapabilityRegistryCaller: CapabilityRegistryCaller{contract: contract}, CapabilityRegistryTransactor: CapabilityRegistryTransactor{contract: contract}, CapabilityRegistryFilterer: CapabilityRegistryFilterer{contract: contract}}, nil +} + +func NewCapabilityRegistryCaller(address common.Address, caller bind.ContractCaller) (*CapabilityRegistryCaller, error) { + contract, err := bindCapabilityRegistry(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &CapabilityRegistryCaller{contract: contract}, nil +} + +func NewCapabilityRegistryTransactor(address common.Address, transactor bind.ContractTransactor) (*CapabilityRegistryTransactor, error) { + contract, err := bindCapabilityRegistry(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &CapabilityRegistryTransactor{contract: contract}, nil +} + +func NewCapabilityRegistryFilterer(address common.Address, filterer bind.ContractFilterer) (*CapabilityRegistryFilterer, error) { + contract, err := bindCapabilityRegistry(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &CapabilityRegistryFilterer{contract: contract}, nil +} + +func bindCapabilityRegistry(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := CapabilityRegistryMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +func (_CapabilityRegistry *CapabilityRegistryRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _CapabilityRegistry.Contract.CapabilityRegistryCaller.contract.Call(opts, result, method, params...) +} + +func (_CapabilityRegistry *CapabilityRegistryRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.CapabilityRegistryTransactor.contract.Transfer(opts) +} + +func (_CapabilityRegistry *CapabilityRegistryRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.CapabilityRegistryTransactor.contract.Transact(opts, method, params...) +} + +func (_CapabilityRegistry *CapabilityRegistryCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _CapabilityRegistry.Contract.contract.Call(opts, result, method, params...) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.contract.Transfer(opts) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.contract.Transact(opts, method, params...) +} + +func (_CapabilityRegistry *CapabilityRegistryCaller) GetCapability(opts *bind.CallOpts, capabilityID [32]byte) (Capability, error) { + var out []interface{} + err := _CapabilityRegistry.contract.Call(opts, &out, "getCapability", capabilityID) + + if err != nil { + return *new(Capability), err + } + + out0 := *abi.ConvertType(out[0], new(Capability)).(*Capability) + + return out0, err + +} + +func (_CapabilityRegistry *CapabilityRegistrySession) GetCapability(capabilityID [32]byte) (Capability, error) { + return _CapabilityRegistry.Contract.GetCapability(&_CapabilityRegistry.CallOpts, capabilityID) +} + +func (_CapabilityRegistry *CapabilityRegistryCallerSession) GetCapability(capabilityID [32]byte) (Capability, error) { + return _CapabilityRegistry.Contract.GetCapability(&_CapabilityRegistry.CallOpts, capabilityID) +} + +func (_CapabilityRegistry *CapabilityRegistryCaller) GetCapabilityID(opts *bind.CallOpts, capabilityType [32]byte, version [32]byte) ([32]byte, error) { + var out []interface{} + err := _CapabilityRegistry.contract.Call(opts, &out, "getCapabilityID", capabilityType, version) + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +func (_CapabilityRegistry *CapabilityRegistrySession) GetCapabilityID(capabilityType [32]byte, version [32]byte) ([32]byte, error) { + return _CapabilityRegistry.Contract.GetCapabilityID(&_CapabilityRegistry.CallOpts, capabilityType, version) +} + +func (_CapabilityRegistry *CapabilityRegistryCallerSession) GetCapabilityID(capabilityType [32]byte, version [32]byte) ([32]byte, error) { + return _CapabilityRegistry.Contract.GetCapabilityID(&_CapabilityRegistry.CallOpts, capabilityType, version) +} + +func (_CapabilityRegistry *CapabilityRegistryCaller) Owner(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _CapabilityRegistry.contract.Call(opts, &out, "owner") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +func (_CapabilityRegistry *CapabilityRegistrySession) Owner() (common.Address, error) { + return _CapabilityRegistry.Contract.Owner(&_CapabilityRegistry.CallOpts) +} + +func (_CapabilityRegistry *CapabilityRegistryCallerSession) Owner() (common.Address, error) { + return _CapabilityRegistry.Contract.Owner(&_CapabilityRegistry.CallOpts) +} + +func (_CapabilityRegistry *CapabilityRegistryCaller) TypeAndVersion(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _CapabilityRegistry.contract.Call(opts, &out, "typeAndVersion") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +func (_CapabilityRegistry *CapabilityRegistrySession) TypeAndVersion() (string, error) { + return _CapabilityRegistry.Contract.TypeAndVersion(&_CapabilityRegistry.CallOpts) +} + +func (_CapabilityRegistry *CapabilityRegistryCallerSession) TypeAndVersion() (string, error) { + return _CapabilityRegistry.Contract.TypeAndVersion(&_CapabilityRegistry.CallOpts) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactor) AcceptOwnership(opts *bind.TransactOpts) (*types.Transaction, error) { + return _CapabilityRegistry.contract.Transact(opts, "acceptOwnership") +} + +func (_CapabilityRegistry *CapabilityRegistrySession) AcceptOwnership() (*types.Transaction, error) { + return _CapabilityRegistry.Contract.AcceptOwnership(&_CapabilityRegistry.TransactOpts) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactorSession) AcceptOwnership() (*types.Transaction, error) { + return _CapabilityRegistry.Contract.AcceptOwnership(&_CapabilityRegistry.TransactOpts) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactor) AddCapability(opts *bind.TransactOpts, capability Capability) (*types.Transaction, error) { + return _CapabilityRegistry.contract.Transact(opts, "addCapability", capability) +} + +func (_CapabilityRegistry *CapabilityRegistrySession) AddCapability(capability Capability) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.AddCapability(&_CapabilityRegistry.TransactOpts, capability) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactorSession) AddCapability(capability Capability) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.AddCapability(&_CapabilityRegistry.TransactOpts, capability) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactor) TransferOwnership(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) { + return _CapabilityRegistry.contract.Transact(opts, "transferOwnership", to) +} + +func (_CapabilityRegistry *CapabilityRegistrySession) TransferOwnership(to common.Address) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.TransferOwnership(&_CapabilityRegistry.TransactOpts, to) +} + +func (_CapabilityRegistry *CapabilityRegistryTransactorSession) TransferOwnership(to common.Address) (*types.Transaction, error) { + return _CapabilityRegistry.Contract.TransferOwnership(&_CapabilityRegistry.TransactOpts, to) +} + +type CapabilityRegistryCapabilityAddedIterator struct { + Event *CapabilityRegistryCapabilityAdded + + contract *bind.BoundContract + event string + + logs chan types.Log + sub ethereum.Subscription + done bool + fail error +} + +func (it *CapabilityRegistryCapabilityAddedIterator) Next() bool { + + if it.fail != nil { + return false + } + + if it.done { + select { + case log := <-it.logs: + it.Event = new(CapabilityRegistryCapabilityAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + + select { + case log := <-it.logs: + it.Event = new(CapabilityRegistryCapabilityAdded) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +func (it *CapabilityRegistryCapabilityAddedIterator) Error() error { + return it.fail +} + +func (it *CapabilityRegistryCapabilityAddedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +type CapabilityRegistryCapabilityAdded struct { + CapabilityId [32]byte + Raw types.Log +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) FilterCapabilityAdded(opts *bind.FilterOpts, capabilityId [][32]byte) (*CapabilityRegistryCapabilityAddedIterator, error) { + + var capabilityIdRule []interface{} + for _, capabilityIdItem := range capabilityId { + capabilityIdRule = append(capabilityIdRule, capabilityIdItem) + } + + logs, sub, err := _CapabilityRegistry.contract.FilterLogs(opts, "CapabilityAdded", capabilityIdRule) + if err != nil { + return nil, err + } + return &CapabilityRegistryCapabilityAddedIterator{contract: _CapabilityRegistry.contract, event: "CapabilityAdded", logs: logs, sub: sub}, nil +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) WatchCapabilityAdded(opts *bind.WatchOpts, sink chan<- *CapabilityRegistryCapabilityAdded, capabilityId [][32]byte) (event.Subscription, error) { + + var capabilityIdRule []interface{} + for _, capabilityIdItem := range capabilityId { + capabilityIdRule = append(capabilityIdRule, capabilityIdItem) + } + + logs, sub, err := _CapabilityRegistry.contract.WatchLogs(opts, "CapabilityAdded", capabilityIdRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + + event := new(CapabilityRegistryCapabilityAdded) + if err := _CapabilityRegistry.contract.UnpackLog(event, "CapabilityAdded", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) ParseCapabilityAdded(log types.Log) (*CapabilityRegistryCapabilityAdded, error) { + event := new(CapabilityRegistryCapabilityAdded) + if err := _CapabilityRegistry.contract.UnpackLog(event, "CapabilityAdded", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +type CapabilityRegistryOwnershipTransferRequestedIterator struct { + Event *CapabilityRegistryOwnershipTransferRequested + + contract *bind.BoundContract + event string + + logs chan types.Log + sub ethereum.Subscription + done bool + fail error +} + +func (it *CapabilityRegistryOwnershipTransferRequestedIterator) Next() bool { + + if it.fail != nil { + return false + } + + if it.done { + select { + case log := <-it.logs: + it.Event = new(CapabilityRegistryOwnershipTransferRequested) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + + select { + case log := <-it.logs: + it.Event = new(CapabilityRegistryOwnershipTransferRequested) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +func (it *CapabilityRegistryOwnershipTransferRequestedIterator) Error() error { + return it.fail +} + +func (it *CapabilityRegistryOwnershipTransferRequestedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +type CapabilityRegistryOwnershipTransferRequested struct { + From common.Address + To common.Address + Raw types.Log +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) FilterOwnershipTransferRequested(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*CapabilityRegistryOwnershipTransferRequestedIterator, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _CapabilityRegistry.contract.FilterLogs(opts, "OwnershipTransferRequested", fromRule, toRule) + if err != nil { + return nil, err + } + return &CapabilityRegistryOwnershipTransferRequestedIterator{contract: _CapabilityRegistry.contract, event: "OwnershipTransferRequested", logs: logs, sub: sub}, nil +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) WatchOwnershipTransferRequested(opts *bind.WatchOpts, sink chan<- *CapabilityRegistryOwnershipTransferRequested, from []common.Address, to []common.Address) (event.Subscription, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _CapabilityRegistry.contract.WatchLogs(opts, "OwnershipTransferRequested", fromRule, toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + + event := new(CapabilityRegistryOwnershipTransferRequested) + if err := _CapabilityRegistry.contract.UnpackLog(event, "OwnershipTransferRequested", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) ParseOwnershipTransferRequested(log types.Log) (*CapabilityRegistryOwnershipTransferRequested, error) { + event := new(CapabilityRegistryOwnershipTransferRequested) + if err := _CapabilityRegistry.contract.UnpackLog(event, "OwnershipTransferRequested", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +type CapabilityRegistryOwnershipTransferredIterator struct { + Event *CapabilityRegistryOwnershipTransferred + + contract *bind.BoundContract + event string + + logs chan types.Log + sub ethereum.Subscription + done bool + fail error +} + +func (it *CapabilityRegistryOwnershipTransferredIterator) Next() bool { + + if it.fail != nil { + return false + } + + if it.done { + select { + case log := <-it.logs: + it.Event = new(CapabilityRegistryOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + + select { + case log := <-it.logs: + it.Event = new(CapabilityRegistryOwnershipTransferred) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +func (it *CapabilityRegistryOwnershipTransferredIterator) Error() error { + return it.fail +} + +func (it *CapabilityRegistryOwnershipTransferredIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +type CapabilityRegistryOwnershipTransferred struct { + From common.Address + To common.Address + Raw types.Log +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*CapabilityRegistryOwnershipTransferredIterator, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _CapabilityRegistry.contract.FilterLogs(opts, "OwnershipTransferred", fromRule, toRule) + if err != nil { + return nil, err + } + return &CapabilityRegistryOwnershipTransferredIterator{contract: _CapabilityRegistry.contract, event: "OwnershipTransferred", logs: logs, sub: sub}, nil +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *CapabilityRegistryOwnershipTransferred, from []common.Address, to []common.Address) (event.Subscription, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _CapabilityRegistry.contract.WatchLogs(opts, "OwnershipTransferred", fromRule, toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + + event := new(CapabilityRegistryOwnershipTransferred) + if err := _CapabilityRegistry.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +func (_CapabilityRegistry *CapabilityRegistryFilterer) ParseOwnershipTransferred(log types.Log) (*CapabilityRegistryOwnershipTransferred, error) { + event := new(CapabilityRegistryOwnershipTransferred) + if err := _CapabilityRegistry.contract.UnpackLog(event, "OwnershipTransferred", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +func (_CapabilityRegistry *CapabilityRegistry) ParseLog(log types.Log) (generated.AbigenLog, error) { + switch log.Topics[0] { + case _CapabilityRegistry.abi.Events["CapabilityAdded"].ID: + return _CapabilityRegistry.ParseCapabilityAdded(log) + case _CapabilityRegistry.abi.Events["OwnershipTransferRequested"].ID: + return _CapabilityRegistry.ParseOwnershipTransferRequested(log) + case _CapabilityRegistry.abi.Events["OwnershipTransferred"].ID: + return _CapabilityRegistry.ParseOwnershipTransferred(log) + + default: + return nil, fmt.Errorf("abigen wrapper received unknown log topic: %v", log.Topics[0]) + } +} + +func (CapabilityRegistryCapabilityAdded) Topic() common.Hash { + return common.HexToHash("0x65610e5677eedff94555572640e442f89848a109ef8593fa927ac30b2565ff06") +} + +func (CapabilityRegistryOwnershipTransferRequested) Topic() common.Hash { + return common.HexToHash("0xed8889f560326eb138920d842192f0eb3dd22b4f139c87a2c57538e05bae1278") +} + +func (CapabilityRegistryOwnershipTransferred) Topic() common.Hash { + return common.HexToHash("0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0") +} + +func (_CapabilityRegistry *CapabilityRegistry) Address() common.Address { + return _CapabilityRegistry.address +} + +type CapabilityRegistryInterface interface { + GetCapability(opts *bind.CallOpts, capabilityID [32]byte) (Capability, error) + + GetCapabilityID(opts *bind.CallOpts, capabilityType [32]byte, version [32]byte) ([32]byte, error) + + Owner(opts *bind.CallOpts) (common.Address, error) + + TypeAndVersion(opts *bind.CallOpts) (string, error) + + AcceptOwnership(opts *bind.TransactOpts) (*types.Transaction, error) + + AddCapability(opts *bind.TransactOpts, capability Capability) (*types.Transaction, error) + + TransferOwnership(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) + + FilterCapabilityAdded(opts *bind.FilterOpts, capabilityId [][32]byte) (*CapabilityRegistryCapabilityAddedIterator, error) + + WatchCapabilityAdded(opts *bind.WatchOpts, sink chan<- *CapabilityRegistryCapabilityAdded, capabilityId [][32]byte) (event.Subscription, error) + + ParseCapabilityAdded(log types.Log) (*CapabilityRegistryCapabilityAdded, error) + + FilterOwnershipTransferRequested(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*CapabilityRegistryOwnershipTransferRequestedIterator, error) + + WatchOwnershipTransferRequested(opts *bind.WatchOpts, sink chan<- *CapabilityRegistryOwnershipTransferRequested, from []common.Address, to []common.Address) (event.Subscription, error) + + ParseOwnershipTransferRequested(log types.Log) (*CapabilityRegistryOwnershipTransferRequested, error) + + FilterOwnershipTransferred(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*CapabilityRegistryOwnershipTransferredIterator, error) + + WatchOwnershipTransferred(opts *bind.WatchOpts, sink chan<- *CapabilityRegistryOwnershipTransferred, from []common.Address, to []common.Address) (event.Subscription, error) + + ParseOwnershipTransferred(log types.Log) (*CapabilityRegistryOwnershipTransferred, error) + + ParseLog(log types.Log) (generated.AbigenLog, error) + + Address() common.Address +} diff --git a/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt index 8b1c830405d..98fd35e188b 100644 --- a/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/core/gethwrappers/keystone/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,3 +1,4 @@ GETH_VERSION: 1.13.8 forwarder: ../../../contracts/solc/v0.8.19/KeystoneForwarder/KeystoneForwarder.abi ../../../contracts/solc/v0.8.19/KeystoneForwarder/KeystoneForwarder.bin b4c900aae9e022f01abbac7993d41f93912247613ac6270b0c4da4ef6f2016e3 +keystone_capability_registry: ../../../contracts/solc/v0.8.19/CapabilityRegistry/CapabilityRegistry.abi ../../../contracts/solc/v0.8.19/CapabilityRegistry/CapabilityRegistry.bin fbaf8eceb929494bdfe0028921a0742da525cb4ec1b6d57a1382eda46fa32c64 ocr3_capability: ../../../contracts/solc/v0.8.19/OCR3Capability/OCR3Capability.abi ../../../contracts/solc/v0.8.19/OCR3Capability/OCR3Capability.bin 9dcbdf55bd5729ba266148da3f17733eb592c871c2108ccca546618628fd9ad2 diff --git a/core/gethwrappers/keystone/go_generate.go b/core/gethwrappers/keystone/go_generate.go index 0c49456f29c..679b678b8f2 100644 --- a/core/gethwrappers/keystone/go_generate.go +++ b/core/gethwrappers/keystone/go_generate.go @@ -6,3 +6,4 @@ package gethwrappers //go:generate go run ../generation/generate/wrap.go ../../../contracts/solc/v0.8.19/KeystoneForwarder/KeystoneForwarder.abi ../../../contracts/solc/v0.8.19/KeystoneForwarder/KeystoneForwarder.bin KeystoneForwarder forwarder //go:generate go run ../generation/generate/wrap.go ../../../contracts/solc/v0.8.19/OCR3Capability/OCR3Capability.abi ../../../contracts/solc/v0.8.19/OCR3Capability/OCR3Capability.bin OCR3Capability ocr3_capability +//go:generate go run ../generation/generate/wrap.go ../../../contracts/solc/v0.8.19/CapabilityRegistry/CapabilityRegistry.abi ../../../contracts/solc/v0.8.19/CapabilityRegistry/CapabilityRegistry.bin CapabilityRegistry keystone_capability_registry diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index ba182d60515..8123439dafb 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -38,6 +38,7 @@ import ( ocrtypes "github.com/smartcontractkit/libocr/offchainreporting/types" "github.com/smartcontractkit/chainlink-common/pkg/loop" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils/mailbox" "github.com/smartcontractkit/chainlink/v2/common/client" @@ -263,18 +264,19 @@ func NewApplicationWithConfigAndKey(t testing.TB, c chainlink.GeneralConfig, fla } func setKeys(t testing.TB, app *TestApplication, flagsAndDeps ...interface{}) (chainID ubig.Big) { - require.NoError(t, app.KeyStore.Unlock(Password)) + ctx := testutils.Context(t) + require.NoError(t, app.KeyStore.Unlock(ctx, Password)) for _, dep := range flagsAndDeps { switch v := dep.(type) { case ethkey.KeyV2: app.Keys = append(app.Keys, v) case p2pkey.KeyV2: - require.NoError(t, app.GetKeyStore().P2P().Add(v)) + require.NoError(t, app.GetKeyStore().P2P().Add(ctx, v)) case csakey.KeyV2: - require.NoError(t, app.GetKeyStore().CSA().Add(v)) + require.NoError(t, app.GetKeyStore().CSA().Add(ctx, v)) case ocr2key.KeyBundle: - require.NoError(t, app.GetKeyStore().OCR2().Add(v)) + require.NoError(t, app.GetKeyStore().OCR2().Add(ctx, v)) } } @@ -341,7 +343,7 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn } } - keyStore := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg.Database()) + keyStore := keystore.NewInMemory(db, utils.FastScryptParams, lggr) mailMon := mailbox.NewMonitor(cfg.AppID().String(), lggr.Named("Mailbox")) loopRegistry := plugins.NewLoopRegistry(lggr, nil) @@ -534,7 +536,7 @@ func NewEthMocksWithTransactionsOnBlocksAssertions(t testing.TB) *evmclimocks.Cl func (ta *TestApplication) Start(ctx context.Context) error { ta.t.Helper() ta.Started = true - err := ta.ChainlinkApplication.KeyStore.Unlock(Password) + err := ta.ChainlinkApplication.KeyStore.Unlock(ctx, Password) if err != nil { return err } @@ -576,7 +578,7 @@ func (ta *TestApplication) MustSeedNewSession(email string) (id string) { // ImportKey adds private key to the application keystore and database func (ta *TestApplication) Import(ctx context.Context, content string) { - require.NoError(ta.t, ta.KeyStore.Unlock(Password)) + require.NoError(ta.t, ta.KeyStore.Unlock(ctx, Password)) _, err := ta.KeyStore.Eth().Import(ctx, []byte(content), Password, &FixtureChainID) require.NoError(ta.t, err) } @@ -661,9 +663,10 @@ func (ta *TestApplication) NewAuthenticatingShell(prompter cmd.Prompter) *cmd.Sh } // NewKeyStore returns a new, unlocked keystore -func NewKeyStore(t testing.TB, db *sqlx.DB, cfg pg.QConfig) keystore.Master { - keystore := keystore.NewInMemory(db, utils.FastScryptParams, logger.TestLogger(t), cfg) - require.NoError(t, keystore.Unlock(Password)) +func NewKeyStore(t testing.TB, ds sqlutil.DataSource) keystore.Master { + ctx := testutils.Context(t) + keystore := keystore.NewInMemory(ds, utils.FastScryptParams, logger.TestLogger(t)) + require.NoError(t, keystore.Unlock(ctx, Password)) return keystore } @@ -1511,8 +1514,8 @@ func EventuallyExpectationsMet(t *testing.T, mock testifyExpectationsAsserter, t } } -func AssertCount(t *testing.T, db *sqlx.DB, tableName string, expected int64) { - testutils.AssertCount(t, db, tableName, expected) +func AssertCount(t *testing.T, ds sqlutil.DataSource, tableName string, expected int64) { + testutils.AssertCount(t, ds, tableName, expected) } func WaitForCount(t *testing.T, db *sqlx.DB, tableName string, want int64) { @@ -1560,8 +1563,8 @@ func NewTestChainScopedConfig(t testing.TB) evmconfig.ChainScopedConfig { return evmtest.NewChainScopedConfig(t, cfg) } -func NewTestTxStore(t *testing.T, db *sqlx.DB) txmgr.TestEvmTxStore { - return txmgr.NewTxStore(db, logger.TestLogger(t)) +func NewTestTxStore(t *testing.T, ds sqlutil.DataSource) txmgr.TestEvmTxStore { + return txmgr.NewTxStore(ds, logger.TestLogger(t)) } // ClearDBTables deletes all rows from the given tables diff --git a/core/internal/cltest/job_factories.go b/core/internal/cltest/job_factories.go index 2b527fbc29c..d78440838b2 100644 --- a/core/internal/cltest/job_factories.go +++ b/core/internal/cltest/job_factories.go @@ -62,7 +62,7 @@ func MustInsertWebhookSpec(t *testing.T, db *sqlx.DB) (job.Job, job.WebhookSpec) func getORMs(t *testing.T, db *sqlx.DB) (jobORM job.ORM, pipelineORM pipeline.ORM) { config := configtest.NewTestGeneralConfig(t) - keyStore := NewKeyStore(t, db, config.Database()) + keyStore := NewKeyStore(t, db) lggr := logger.TestLogger(t) pipelineORM = pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) bridgeORM := bridges.NewORM(db) diff --git a/core/internal/features/features_test.go b/core/internal/features/features_test.go index 4afad453110..516f0ae0907 100644 --- a/core/internal/features/features_test.go +++ b/core/internal/features/features_test.go @@ -681,6 +681,7 @@ func setupOCRContracts(t *testing.T) (*bind.TransactOpts, *backends.SimulatedBac func setupNode(t *testing.T, owner *bind.TransactOpts, portV2 int, b *backends.SimulatedBackend, overrides func(c *chainlink.Config, s *chainlink.Secrets), ) (*cltest.TestApplication, string, common.Address, ocrkey.KeyV2) { + ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) config, _ := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Insecure.OCRDevelopmentMode = ptr(true) // Disables ocr spec validation so we can have fast polling for the test. @@ -719,12 +720,13 @@ func setupNode(t *testing.T, owner *bind.TransactOpts, portV2 int, require.NoError(t, err) b.Commit() - key, err := app.GetKeyStore().OCR().Create() + key, err := app.GetKeyStore().OCR().Create(ctx) require.NoError(t, err) return app, p2pKey.PeerID().Raw(), transmitter, key } func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 int, b *backends.SimulatedBackend, overrides func(c *chainlink.Config, s *chainlink.Secrets)) (*cltest.TestApplication, string, common.Address, common.Address, ocrkey.KeyV2) { + ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) config, _ := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Insecure.OCRDevelopmentMode = ptr(true) // Disables ocr spec validation so we can have fast polling for the test. @@ -761,7 +763,7 @@ func setupForwarderEnabledNode(t *testing.T, owner *bind.TransactOpts, portV2 in require.NoError(t, err) b.Commit() - key, err := app.GetKeyStore().OCR().Create() + key, err := app.GetKeyStore().OCR().Create(ctx) require.NoError(t, err) // deploy a forwarder @@ -1241,6 +1243,7 @@ observationSource = """ func TestIntegration_BlockHistoryEstimator(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) var initialDefaultGasPrice int64 = 5_000_000_000 maxGasPrice := assets.NewWeiI(10 * initialDefaultGasPrice) @@ -1260,8 +1263,8 @@ func TestIntegration_BlockHistoryEstimator(t *testing.T) { chchNewHeads := make(chan evmtest.RawSub[*evmtypes.Head], 1) db := pgtest.NewSqlxDB(t) - kst := cltest.NewKeyStore(t, db, cfg.Database()) - require.NoError(t, kst.Unlock(cltest.Password)) + kst := cltest.NewKeyStore(t, db) + require.NoError(t, kst.Unlock(ctx, cltest.Password)) cc := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, KeyStore: kst.Eth(), Client: ethClient, GeneralConfig: cfg}) diff --git a/core/internal/features/ocr2/features_ocr2_test.go b/core/internal/features/ocr2/features_ocr2_test.go index 06f57c805ec..07e0fc21d9a 100644 --- a/core/internal/features/ocr2/features_ocr2_test.go +++ b/core/internal/features/ocr2/features_ocr2_test.go @@ -111,6 +111,7 @@ func setupNodeOCR2( b *backends.SimulatedBackend, p2pV2Bootstrappers []commontypes.BootstrapperLocator, ) *ocr2Node { + ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) config, _ := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Insecure.OCRDevelopmentMode = ptr(true) // Disables ocr spec validation so we can have fast polling for the test. @@ -157,7 +158,7 @@ func setupNodeOCR2( require.NoError(t, err) b.Commit() - kb, err := app.GetKeyStore().OCR2().Create("evm") + kb, err := app.GetKeyStore().OCR2().Create(ctx, "evm") require.NoError(t, err) if useForwarder { diff --git a/core/internal/testutils/testutils.go b/core/internal/testutils/testutils.go index 9fdd50625cc..ba7e697fb62 100644 --- a/core/internal/testutils/testutils.go +++ b/core/internal/testutils/testutils.go @@ -24,15 +24,14 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/google/uuid" "github.com/gorilla/websocket" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "go.uber.org/zap/zaptest/observer" - "github.com/jmoiron/sqlx" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" // NOTE: To avoid circular dependencies, this package MUST NOT import // anything from "github.com/smartcontractkit/chainlink/v2/core" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" ) const ( @@ -419,10 +418,10 @@ func SkipShortDB(tb testing.TB) { SkipShort(tb, "DB dependency") } -func AssertCount(t *testing.T, db *sqlx.DB, tableName string, expected int64) { +func AssertCount(t *testing.T, ds sqlutil.DataSource, tableName string, expected int64) { t.Helper() var count int64 - err := db.Get(&count, fmt.Sprintf(`SELECT count(*) FROM %s;`, tableName)) + err := ds.GetContext(Context(t), &count, fmt.Sprintf(`SELECT count(*) FROM %s;`, tableName)) require.NoError(t, err) require.Equal(t, expected, count) } diff --git a/core/scripts/go.mod b/core/scripts/go.mod index 8c68d33c604..7e1ee1f10d7 100644 --- a/core/scripts/go.mod +++ b/core/scripts/go.mod @@ -21,7 +21,7 @@ require ( github.com/prometheus/client_golang v1.17.0 github.com/shopspring/decimal v1.3.1 github.com/smartcontractkit/chainlink-automation v1.0.3 - github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 + github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e github.com/smartcontractkit/chainlink-vrf v0.0.0-20240222010609-cd67d123c772 github.com/smartcontractkit/chainlink/v2 v2.0.0-00010101000000-000000000000 github.com/smartcontractkit/libocr v0.0.0-20240326191951-2bbe9382d052 @@ -257,7 +257,7 @@ require ( github.com/shirou/gopsutil/v3 v3.23.11 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartcontractkit/chain-selectors v1.0.10 // indirect - github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 // indirect + github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 // indirect github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 // indirect github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 // indirect github.com/smartcontractkit/chainlink-solana v1.0.3-0.20240216142700-c5869534c19e // indirect diff --git a/core/scripts/go.sum b/core/scripts/go.sum index 2883ee68528..d43d5df8eea 100644 --- a/core/scripts/go.sum +++ b/core/scripts/go.sum @@ -1185,10 +1185,10 @@ github.com/smartcontractkit/chain-selectors v1.0.10 h1:t9kJeE6B6G+hKD0GYR4kGJSCq github.com/smartcontractkit/chain-selectors v1.0.10/go.mod h1:d4Hi+E1zqjy9HqMkjBE5q1vcG9VGgxf5VxiRHfzi2kE= github.com/smartcontractkit/chainlink-automation v1.0.3 h1:h/ijT0NiyV06VxYVgcNfsE3+8OEzT3Q0Z9au0z1BPWs= github.com/smartcontractkit/chainlink-automation v1.0.3/go.mod h1:RjboV0Qd7YP+To+OrzHGXaxUxoSONveCoAK2TQ1INLU= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 h1:K7Y+gd0lEumrhgaIQFjC8reXadJOMVgDI4xsCAsiuSo= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 h1:I326nw5GwHQHsLKHwtu5Sb9EBLylC8CfUd7BFAS0jtg= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8/go.mod h1:a65NtrK4xZb01mf0dDNghPkN2wXgcqFQ55ADthVBgMc= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e h1:nHs5mFOR7FPII20GrCGIPywDW43MhEUlD7DqHnTgu6Q= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 h1:MvaNzuaQh1vX4CAYLM8qFd99cf0ZF1JNwtDZtLU7WvU= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92/go.mod h1:uATrrJ8IsuBkOBJ46USuf73gz9gZy5k5bzGE5/ji/rc= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 h1:xFSv8561jsLtF6gYZr/zW2z5qUUAkcFkApin2mnbYTo= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540/go.mod h1:sjAmX8K2kbQhvDarZE1ZZgDgmHJ50s0BBc/66vKY2ek= github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 h1:1BcjXuviSAKttOX7BZoVHRZZGfxqoA2+AL8tykmkdoc= diff --git a/core/scripts/vrfv2/testnet/main.go b/core/scripts/vrfv2/testnet/main.go index 34070c90d8a..88f4d9e0f73 100644 --- a/core/scripts/vrfv2/testnet/main.go +++ b/core/scripts/vrfv2/testnet/main.go @@ -44,7 +44,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/blockhashstore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/services/vrf/proof" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -54,6 +53,7 @@ var ( ) func main() { + ctx := context.Background() e := helpers.SetupEnv(false) switch os.Args[1] { @@ -218,8 +218,8 @@ func main() { db := sqlx.MustOpen("postgres", *dbURL) lggr, _ := logger.NewLogger() - keyStore := keystore.New(db, utils.DefaultScryptParams, lggr, pg.NewQConfig(false)) - err = keyStore.Unlock(*keystorePassword) + keyStore := keystore.New(db, utils.DefaultScryptParams, lggr) + err = keyStore.Unlock(ctx, *keystorePassword) helpers.PanicErr(err) k, err := keyStore.VRF().Get(*pubKeyHex) @@ -310,8 +310,8 @@ func main() { db := sqlx.MustOpen("postgres", *dbURL) lggr, _ := logger.NewLogger() - keyStore := keystore.New(db, utils.DefaultScryptParams, lggr, pg.NewQConfig(false)) - err = keyStore.Unlock(*keystorePassword) + keyStore := keystore.New(db, utils.DefaultScryptParams, lggr) + err = keyStore.Unlock(ctx, *keystorePassword) helpers.PanicErr(err) k, err := keyStore.VRF().Get(*pubKeyHex) diff --git a/core/scripts/vrfv2plus/testnet/main.go b/core/scripts/vrfv2plus/testnet/main.go index 45ef7314bee..9c7d212fc82 100644 --- a/core/scripts/vrfv2plus/testnet/main.go +++ b/core/scripts/vrfv2plus/testnet/main.go @@ -45,7 +45,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/blockhashstore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/services/vrf/extraargs" "github.com/smartcontractkit/chainlink/v2/core/services/vrf/proof" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -56,6 +55,7 @@ var ( ) func main() { + ctx := context.Background() e := helpers.SetupEnv(false) switch os.Args[1] { @@ -196,8 +196,8 @@ func main() { db := sqlx.MustOpen("postgres", *dbURL) lggr, _ := logger.NewLogger() - keyStore := keystore.New(db, utils.DefaultScryptParams, lggr, pg.NewQConfig(false)) - err = keyStore.Unlock(*keystorePassword) + keyStore := keystore.New(db, utils.DefaultScryptParams, lggr) + err = keyStore.Unlock(ctx, *keystorePassword) helpers.PanicErr(err) k, err := keyStore.VRF().Get(*pubKeyHex) @@ -292,8 +292,8 @@ func main() { db := sqlx.MustOpen("postgres", *dbURL) lggr, _ := logger.NewLogger() - keyStore := keystore.New(db, utils.DefaultScryptParams, lggr, pg.NewQConfig(false)) - err = keyStore.Unlock(*keystorePassword) + keyStore := keystore.New(db, utils.DefaultScryptParams, lggr) + err = keyStore.Unlock(ctx, *keystorePassword) helpers.PanicErr(err) k, err := keyStore.VRF().Get(*pubKeyHex) @@ -597,6 +597,24 @@ func main() { tx, err := coordinator.DeregisterProvingKey(e.Owner, [2]*big.Int{pk.X, pk.Y}) helpers.PanicErr(err) helpers.ConfirmTXMined(context.Background(), e.Ec, tx, e.ChainID) + case "coordinator-register-migratable-coordinator": + coordinatorRegisterMigratableCoordinator := flag.NewFlagSet("coordinator-register-migratable-coordinator", flag.ExitOnError) + coordinatorAddress := coordinatorRegisterMigratableCoordinator.String("address", "", "coordinator address from which to register migratable coordinator") + coordinatorMigrateToAddress := coordinatorRegisterMigratableCoordinator.String("coordinator-migrate-to-address", "", "coordinator address to register in order for perform sub migration to") + helpers.ParseArgs(coordinatorRegisterMigratableCoordinator, os.Args[2:], "address", "coordinator-migrate-to-address") + coordinator, err := vrf_coordinator_v2_5.NewVRFCoordinatorV25(common.HexToAddress(*coordinatorAddress), e.Ec) + helpers.PanicErr(err) + v2plusscripts.RegisterMigratableCoordinator(e, *coordinator, common.HexToAddress(*coordinatorMigrateToAddress)) + case "coordinator-migrate-sub": + coordinatorMigrateSub := flag.NewFlagSet("coordinator-migrate-sub", flag.ExitOnError) + coordinatorAddress := coordinatorMigrateSub.String("address", "", "coordinator address from which to migrate a sub") + coordinatorMigrateToAddress := coordinatorMigrateSub.String("coordinator-migrate-to-address", "", "coordinator address to migrate sub to") + subID := coordinatorMigrateSub.String("sub-id", "", "sub-id") + helpers.ParseArgs(coordinatorMigrateSub, os.Args[2:], "address", "coordinator-migrate-to-address", "sub-id") + parsedSubID := parseUInt256String(*subID) + coordinator, err := vrf_coordinator_v2_5.NewVRFCoordinatorV25(common.HexToAddress(*coordinatorAddress), e.Ec) + helpers.PanicErr(err) + v2plusscripts.MigrateSub(e, *coordinator, common.HexToAddress(*coordinatorMigrateToAddress), parsedSubID) case "coordinator-subscription": coordinatorSub := flag.NewFlagSet("coordinator-subscription", flag.ExitOnError) address := coordinatorSub.String("address", "", "coordinator address") diff --git a/core/scripts/vrfv2plus/testnet/v2plusscripts/util.go b/core/scripts/vrfv2plus/testnet/v2plusscripts/util.go index 8becb31239c..ae57c4caae5 100644 --- a/core/scripts/vrfv2plus/testnet/v2plusscripts/util.go +++ b/core/scripts/vrfv2plus/testnet/v2plusscripts/util.go @@ -198,6 +198,41 @@ func RegisterCoordinatorProvingKey(e helpers.Environment, ) } +func RegisterMigratableCoordinator( + e helpers.Environment, + coordinator vrf_coordinator_v2_5.VRFCoordinatorV25, + coordinatorMigrateToAddress common.Address, +) { + tx, err := coordinator.RegisterMigratableCoordinator(e.Owner, coordinatorMigrateToAddress) + helpers.PanicErr(err) + helpers.ConfirmTXMined( + context.Background(), + e.Ec, + tx, + e.ChainID, + fmt.Sprintf("Coordinator %s registered migratable coordinator %s", coordinator.Address().String(), coordinatorMigrateToAddress.String()), + ) +} + +func MigrateSub( + e helpers.Environment, + coordinatorMigrateSubFrom vrf_coordinator_v2_5.VRFCoordinatorV25, + coordinatorMigrateSubTo common.Address, + subID *big.Int, +) { + tx, err := coordinatorMigrateSubFrom.Migrate(e.Owner, subID, coordinatorMigrateSubTo) + helpers.PanicErr(err) + helpers.ConfirmTXMined( + context.Background(), + e.Ec, + tx, + e.ChainID, + fmt.Sprintf("Sub Migrated from Coordinator: %s,", coordinatorMigrateSubFrom.Address().String()), + fmt.Sprintf("Sub Migrated TO Coordinator: %s,", coordinatorMigrateSubTo.String()), + fmt.Sprintf("Sub ID which was migrated: %s,", subID.String()), + ) +} + func WrapperDeploy( e helpers.Environment, link, linkEthFeed, coordinator common.Address, subID *big.Int, diff --git a/core/services/blockhashstore/bhs_test.go b/core/services/blockhashstore/bhs_test.go index 75424ee8059..94e9f22ee7c 100644 --- a/core/services/blockhashstore/bhs_test.go +++ b/core/services/blockhashstore/bhs_test.go @@ -28,15 +28,15 @@ func TestStoreRotatesFromAddresses(t *testing.T) { db := pgtest.NewSqlxDB(t) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) cfg := configtest.NewTestGeneralConfig(t) - kst := cltest.NewKeyStore(t, db, cfg.Database()) - require.NoError(t, kst.Unlock(cltest.Password)) + kst := cltest.NewKeyStore(t, db) + require.NoError(t, kst.Unlock(ctx, cltest.Password)) relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, KeyStore: kst.Eth(), GeneralConfig: cfg, Client: ethClient}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) chain, err := legacyChains.Get(cltest.FixtureChainID.String()) require.NoError(t, err) lggr := logger.TestLogger(t) - ks := keystore.New(db, utils.FastScryptParams, lggr, cfg.Database()) - require.NoError(t, ks.Unlock("blah")) + ks := keystore.New(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, "blah")) k1, err := ks.Eth().Create(ctx, &cltest.FixtureChainID) require.NoError(t, err) k2, err := ks.Eth().Create(ctx, &cltest.FixtureChainID) diff --git a/core/services/blockhashstore/delegate_test.go b/core/services/blockhashstore/delegate_test.go index 4c37273f161..6aaeb59152a 100644 --- a/core/services/blockhashstore/delegate_test.go +++ b/core/services/blockhashstore/delegate_test.go @@ -55,7 +55,7 @@ func createTestDelegate(t *testing.T) (*blockhashstore.Delegate, *testData) { c.Feature.LogPoller = func(b bool) *bool { return &b }(true) }) db := pgtest.NewSqlxDB(t) - kst := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + kst := cltest.NewKeyStore(t, db).Eth() sendingKey, _ := cltest.MustInsertRandomKey(t, kst) lp := &mocklp.LogPoller{} lp.On("RegisterFilter", mock.Anything, mock.Anything).Return(nil) diff --git a/core/services/chainlink/relayer_chain_interoperators_test.go b/core/services/chainlink/relayer_chain_interoperators_test.go index c90811de768..38aae37c134 100644 --- a/core/services/chainlink/relayer_chain_interoperators_test.go +++ b/core/services/chainlink/relayer_chain_interoperators_test.go @@ -172,7 +172,7 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) lggr := logger.TestLogger(t) diff --git a/core/services/cron/cron_test.go b/core/services/cron/cron_test.go index c3ecc0957c7..b31a06a9591 100644 --- a/core/services/cron/cron_test.go +++ b/core/services/cron/cron_test.go @@ -25,7 +25,7 @@ func TestCronV2Pipeline(t *testing.T) { cfg := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) lggr := logger.TestLogger(t) orm := pipeline.NewORM(db, lggr, cfg.JobPipeline().MaxSuccessfulRuns()) btORM := bridges.NewORM(db) diff --git a/core/services/directrequest/delegate_test.go b/core/services/directrequest/delegate_test.go index 0235a0c4eec..08f38865bec 100644 --- a/core/services/directrequest/delegate_test.go +++ b/core/services/directrequest/delegate_test.go @@ -44,7 +44,7 @@ func TestDelegate_ServicesForSpec(t *testing.T) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].MinIncomingConfirmations = ptr[uint32](1) }) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) mailMon := servicetest.Run(t, mailboxtest.NewMonitor(t)) relayerExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, Client: ethClient, MailMon: mailMon, KeyStore: keyStore.Eth()}) @@ -85,7 +85,7 @@ func NewDirectRequestUniverseWithConfig(t *testing.T, cfg chainlink.GeneralConfi mailMon := servicetest.Run(t, mailboxtest.NewMonitor(t)) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, Client: ethClient, LogBroadcaster: broadcaster, MailMon: mailMon, KeyStore: keyStore.Eth()}) lggr := logger.TestLogger(t) orm := pipeline.NewORM(db, lggr, cfg.JobPipeline().MaxSuccessfulRuns()) diff --git a/core/services/feeds/orm_test.go b/core/services/feeds/orm_test.go index 51a85a33a46..0cf20cf9800 100644 --- a/core/services/feeds/orm_test.go +++ b/core/services/feeds/orm_test.go @@ -15,6 +15,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" @@ -1647,18 +1648,19 @@ func createFeedsManager(t *testing.T, orm feeds.ORM) int64 { func createJob(t *testing.T, db *sqlx.DB, externalJobID uuid.UUID) *job.Job { t.Helper() + ctx := testutils.Context(t) var ( config = configtest.NewGeneralConfig(t, nil) - keyStore = cltest.NewKeyStore(t, db, config.Database()) + keyStore = cltest.NewKeyStore(t, db) lggr = logger.TestLogger(t) pipelineORM = pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) bridgeORM = bridges.NewORM(db) relayExtenders = evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: config, KeyStore: keyStore.Eth()}) ) orm := job.NewORM(db, pipelineORM, bridgeORM, keyStore, lggr, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) defer func() { assert.NoError(t, orm.Close()) }() diff --git a/core/services/feeds/service_test.go b/core/services/feeds/service_test.go index 0dc07b57d43..536584a0846 100644 --- a/core/services/feeds/service_test.go +++ b/core/services/feeds/service_test.go @@ -178,7 +178,7 @@ func setupTestServiceCfg(t *testing.T, overrideCfg func(c *chainlink.Config, s * gcfg := configtest.NewGeneralConfig(t, overrideCfg) keyStore := new(ksmocks.Master) scopedConfig := evmtest.NewChainScopedConfig(t, gcfg) - ethKeyStore := cltest.NewKeyStore(t, db, gcfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: gcfg, HeadTracker: headtracker.NullTracker, KeyStore: ethKeyStore}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) diff --git a/core/services/fluxmonitorv2/flux_monitor_test.go b/core/services/fluxmonitorv2/flux_monitor_test.go index d8713fed997..2ac424bceab 100644 --- a/core/services/fluxmonitorv2/flux_monitor_test.go +++ b/core/services/fluxmonitorv2/flux_monitor_test.go @@ -275,7 +275,7 @@ func withORM(orm fluxmonitorv2.ORM) func(*setupOptions) { // setupStoreWithKey setups a new store and adds a key to the keystore func setupStoreWithKey(t *testing.T) (*sqlx.DB, common.Address) { db := pgtest.NewSqlxDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, pgtest.NewQConfig(true)).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, nodeAddr := cltest.MustInsertRandomKey(t, ethKeyStore) return db, nodeAddr @@ -283,8 +283,8 @@ func setupStoreWithKey(t *testing.T) (*sqlx.DB, common.Address) { // setupStoreWithKey setups a new store and adds a key to the keystore func setupFullDBWithKey(t *testing.T) (*sqlx.DB, common.Address) { - cfg, db := heavyweight.FullTestDBV2(t, nil) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + _, db := heavyweight.FullTestDBV2(t, nil) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, nodeAddr := cltest.MustInsertRandomKey(t, ethKeyStore) return db, nodeAddr diff --git a/core/services/fluxmonitorv2/key_store_test.go b/core/services/fluxmonitorv2/key_store_test.go index fdef2ade210..31e6c01e351 100644 --- a/core/services/fluxmonitorv2/key_store_test.go +++ b/core/services/fluxmonitorv2/key_store_test.go @@ -16,8 +16,7 @@ func TestKeyStore_EnabledKeysForChain(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := pgtest.NewQConfig(true) - ethKeyStore := cltest.NewKeyStore(t, db, cfg).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() ks := fluxmonitorv2.NewKeyStore(ethKeyStore) @@ -43,8 +42,7 @@ func TestKeyStore_GetRoundRobinAddress(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := pgtest.NewQConfig(true) - ethKeyStore := cltest.NewKeyStore(t, db, cfg).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, k0Address := cltest.MustInsertRandomKey(t, ethKeyStore) diff --git a/core/services/fluxmonitorv2/orm_test.go b/core/services/fluxmonitorv2/orm_test.go index f6904b9fe97..db00fabb4ff 100644 --- a/core/services/fluxmonitorv2/orm_test.go +++ b/core/services/fluxmonitorv2/orm_test.go @@ -89,7 +89,7 @@ func TestORM_UpdateFluxMonitorRoundStats(t *testing.T) { cfg := configtest.NewGeneralConfig(t, nil) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) lggr := logger.TestLogger(t) // Instantiate a real pipeline ORM because we need to create a pipeline run @@ -172,8 +172,7 @@ func TestORM_CreateEthTransaction(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := pgtest.NewQConfig(true) - ethKeyStore := cltest.NewKeyStore(t, db, cfg).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() strategy := commontxmmocks.NewTxStrategy(t) diff --git a/core/services/functions/listener_test.go b/core/services/functions/listener_test.go index d6cd9aa23d6..f3754bbbc29 100644 --- a/core/services/functions/listener_test.go +++ b/core/services/functions/listener_test.go @@ -85,7 +85,7 @@ func NewFunctionsListenerUniverse(t *testing.T, timeoutSec int, pruneFrequencySe mailMon := servicetest.Run(t, mailboxtest.NewMonitor(t)) db := pgtest.NewSqlxDB(t) - kst := cltest.NewKeyStore(t, db, cfg.Database()) + kst := cltest.NewKeyStore(t, db) relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, Client: ethClient, KeyStore: kst.Eth(), LogBroadcaster: broadcaster, MailMon: mailMon}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) diff --git a/core/services/job/helpers_test.go b/core/services/job/helpers_test.go index a7543753d63..b35389ad4ad 100644 --- a/core/services/job/helpers_test.go +++ b/core/services/job/helpers_test.go @@ -20,7 +20,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/job" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" @@ -214,7 +213,7 @@ func makeMinimalHTTPOracleSpec(t *testing.T, db *sqlx.DB, cfg chainlink.GeneralC ExternalJobID: uuid.New(), } s := fmt.Sprintf(minimalNonBootstrapTemplate, contractAddress, transmitterAddress, keyBundle, fetchUrl, timeout) - keyStore := cltest.NewKeyStore(t, db, pgtest.NewQConfig(true)) + keyStore := cltest.NewKeyStore(t, db) relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, Client: evmtest.NewEthClientMockWithDefaultChain(t), GeneralConfig: cfg, KeyStore: keyStore.Eth()}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) _, err := ocr.ValidatedOracleSpecToml(legacyChains, s) @@ -272,6 +271,7 @@ func makeOCRJobSpecFromToml(t *testing.T, jobSpecToml string) *job.Job { func makeOCR2VRFJobSpec(t testing.TB, ks keystore.Master, cfg chainlink.GeneralConfig, transmitter common.Address, chainID *big.Int, fromBlock uint64) *job.Job { t.Helper() + ctx := testutils.Context(t) useForwarders := false _, beacon := cltest.MustInsertRandomKey(t, ks.Eth()) @@ -279,7 +279,7 @@ func makeOCR2VRFJobSpec(t testing.TB, ks keystore.Master, cfg chainlink.GeneralC _, feed := cltest.MustInsertRandomKey(t, ks.Eth()) _, dkg := cltest.MustInsertRandomKey(t, ks.Eth()) sendingKeys := fmt.Sprintf(`"%s"`, transmitter) - kb, _ := ks.OCR2().Create(chaintype.EVM) + kb, _ := ks.OCR2().Create(ctx, chaintype.EVM) vrfKey := make([]byte, 32) _, err := rand.Read(vrfKey) diff --git a/core/services/job/job_orm_test.go b/core/services/job/job_orm_test.go index c60f096c358..3cd94735ca8 100644 --- a/core/services/job/job_orm_test.go +++ b/core/services/job/job_orm_test.go @@ -74,13 +74,14 @@ serverPubKey = '8fa807463ad73f9ee855cfd60ba406dcf98a2855b3dd8af613107b0f6890a707 func TestORM(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) ethKeyStore := keyStore.Eth() - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -338,12 +339,13 @@ func TestORM(t *testing.T) { func TestORM_DeleteJob_DeletesAssociatedRecords(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewGeneralConfig(t, nil) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -395,7 +397,7 @@ func TestORM_DeleteJob_DeletesAssociatedRecords(t *testing.T) { }) t.Run("it creates and deletes records for vrf jobs", func(t *testing.T) { - key, err := keyStore.VRF().Create() + key, err := keyStore.VRF().Create(testutils.Context(t)) require.NoError(t, err) pk := key.PublicKey jb, err := vrfcommon.ValidatedVRFSpec(testspecs.GenerateVRFSpec(testspecs.VRFSpecParams{PublicKey: pk.String()}).Toml()) @@ -438,10 +440,11 @@ func TestORM_DeleteJob_DeletesAssociatedRecords(t *testing.T) { } func TestORM_CreateJob_VRFV2(t *testing.T) { + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -522,10 +525,11 @@ func TestORM_CreateJob_VRFV2(t *testing.T) { } func TestORM_CreateJob_VRFV2Plus(t *testing.T) { + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -609,10 +613,11 @@ func TestORM_CreateJob_VRFV2Plus(t *testing.T) { } func TestORM_CreateJob_OCRBootstrap(t *testing.T) { + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -638,7 +643,7 @@ func TestORM_CreateJob_OCRBootstrap(t *testing.T) { func TestORM_CreateJob_EVMChainID_Validation(t *testing.T) { config := configtest.NewGeneralConfig(t, nil) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -720,6 +725,7 @@ func TestORM_CreateJob_EVMChainID_Validation(t *testing.T) { } func TestORM_CreateJob_OCR_DuplicatedContractAddress(t *testing.T) { + ctx := testutils.Context(t) customChainID := big.New(testutils.NewRandomEVMChainID()) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -732,8 +738,8 @@ func TestORM_CreateJob_OCR_DuplicatedContractAddress(t *testing.T) { }) }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -789,6 +795,7 @@ func TestORM_CreateJob_OCR_DuplicatedContractAddress(t *testing.T) { } func TestORM_CreateJob_OCR2_DuplicatedContractAddress(t *testing.T) { + ctx := testutils.Context(t) customChainID := big.New(testutils.NewRandomEVMChainID()) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -801,8 +808,8 @@ func TestORM_CreateJob_OCR2_DuplicatedContractAddress(t *testing.T) { }) }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR2().Add(cltest.DefaultOCR2Key)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -850,6 +857,7 @@ func TestORM_CreateJob_OCR2_DuplicatedContractAddress(t *testing.T) { } func TestORM_CreateJob_OCR2_Sending_Keys_Transmitter_Keys_Validations(t *testing.T) { + ctx := testutils.Context(t) customChainID := big.New(testutils.NewRandomEVMChainID()) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -862,8 +870,8 @@ func TestORM_CreateJob_OCR2_Sending_Keys_Transmitter_Keys_Validations(t *testing }) }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR2().Add(cltest.DefaultOCR2Key)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key)) lggr := logger.TestLogger(t) pipelineORM := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) @@ -904,10 +912,11 @@ func TestORM_CreateJob_OCR2_Sending_Keys_Transmitter_Keys_Validations(t *testing } func TestORM_ValidateKeyStoreMatch(t *testing.T) { + ctx := testutils.Context(t) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) {}) - keyStore := cltest.NewKeyStore(t, pgtest.NewSqlxDB(t), config.Database()) - require.NoError(t, keyStore.OCR2().Add(cltest.DefaultOCR2Key)) + keyStore := cltest.NewKeyStore(t, pgtest.NewSqlxDB(t)) + require.NoError(t, keyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key)) var jb job.Job { @@ -933,7 +942,7 @@ func TestORM_ValidateKeyStoreMatch(t *testing.T) { err := job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, "bad key") require.EqualError(t, err, "no Cosmos key matching: \"bad key\"") - cosmosKey, err := keyStore.Cosmos().Create() + cosmosKey, err := keyStore.Cosmos().Create(ctx) require.NoError(t, err) err = job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, cosmosKey.ID()) require.NoError(t, err) @@ -946,7 +955,7 @@ func TestORM_ValidateKeyStoreMatch(t *testing.T) { err := job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, "bad key") require.EqualError(t, err, "no Solana key matching: \"bad key\"") - solanaKey, err := keyStore.Solana().Create() + solanaKey, err := keyStore.Solana().Create(ctx) require.NoError(t, err) err = job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, solanaKey.ID()) require.NoError(t, err) @@ -958,7 +967,7 @@ func TestORM_ValidateKeyStoreMatch(t *testing.T) { err := job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, "bad key") require.EqualError(t, err, "no Starknet key matching: \"bad key\"") - starkNetKey, err := keyStore.StarkNet().Create() + starkNetKey, err := keyStore.StarkNet().Create(ctx) require.NoError(t, err) err = job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, starkNetKey.ID()) require.NoError(t, err) @@ -970,7 +979,7 @@ func TestORM_ValidateKeyStoreMatch(t *testing.T) { err := job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, "bad key") require.EqualError(t, err, "no CSA key matching: \"bad key\"") - csaKey, err := keyStore.CSA().Create() + csaKey, err := keyStore.CSA().Create(ctx) require.NoError(t, err) err = job.ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keyStore, csaKey.ID()) require.NoError(t, err) @@ -979,12 +988,13 @@ func TestORM_ValidateKeyStoreMatch(t *testing.T) { func Test_FindJobs(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1047,6 +1057,7 @@ func Test_FindJobs(t *testing.T) { func Test_FindJob(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) // Create a config with multiple EVM chains. The test fixtures already load 1337 // Additional chains will need additional fixture statements to add a chain to evm_chains. @@ -1062,10 +1073,10 @@ func Test_FindJob(t *testing.T) { }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) - require.NoError(t, keyStore.CSA().Add(cltest.DefaultCSAKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) + require.NoError(t, keyStore.CSA().Add(ctx, cltest.DefaultCSAKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1244,11 +1255,12 @@ func Test_FindJob(t *testing.T) { func Test_FindJobsByPipelineSpecIDs(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1291,12 +1303,13 @@ func Test_FindJobsByPipelineSpecIDs(t *testing.T) { func Test_FindPipelineRuns(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1351,13 +1364,14 @@ func Test_FindPipelineRuns(t *testing.T) { func Test_PipelineRunsByJobID(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1410,14 +1424,15 @@ func Test_PipelineRunsByJobID(t *testing.T) { } func Test_FindPipelineRunIDsByJobID(t *testing.T) { + ctx := testutils.Context(t) var jb job.Job config := configtest.NewTestGeneralConfig(t) _, db := heavyweight.FullTestDBV2(t, nil) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1519,13 +1534,14 @@ func Test_FindPipelineRunIDsByJobID(t *testing.T) { func Test_FindPipelineRunsByIDs(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) @@ -1577,12 +1593,13 @@ func Test_FindPipelineRunsByIDs(t *testing.T) { func Test_FindPipelineRunByID(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - err := keyStore.OCR().Add(cltest.DefaultOCRKey) + keyStore := cltest.NewKeyStore(t, db) + err := keyStore.OCR().Add(ctx, cltest.DefaultOCRKey) require.NoError(t, err) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) @@ -1620,12 +1637,13 @@ func Test_FindPipelineRunByID(t *testing.T) { func Test_FindJobWithoutSpecErrors(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - err := keyStore.OCR().Add(cltest.DefaultOCRKey) + keyStore := cltest.NewKeyStore(t, db) + err := keyStore.OCR().Add(ctx, cltest.DefaultOCRKey) require.NoError(t, err) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) @@ -1657,12 +1675,13 @@ func Test_FindJobWithoutSpecErrors(t *testing.T) { func Test_FindSpecErrorsByJobIDs(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - err := keyStore.OCR().Add(cltest.DefaultOCRKey) + keyStore := cltest.NewKeyStore(t, db) + err := keyStore.OCR().Add(ctx, cltest.DefaultOCRKey) require.NoError(t, err) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) @@ -1691,13 +1710,14 @@ func Test_FindSpecErrorsByJobIDs(t *testing.T) { func Test_CountPipelineRunsByJobID(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) diff --git a/core/services/job/job_pipeline_orm_integration_test.go b/core/services/job/job_pipeline_orm_integration_test.go index 696005c270e..33ee6dc306c 100644 --- a/core/services/job/job_pipeline_orm_integration_test.go +++ b/core/services/job/job_pipeline_orm_integration_test.go @@ -29,6 +29,7 @@ func clearJobsDb(t *testing.T, db *sqlx.DB) { } func TestPipelineORM_Integration(t *testing.T) { + ctx := testutils.Context(t) const DotStr = ` // data source 1 ds1 [type=bridge name=voter_turnout]; @@ -51,11 +52,11 @@ func TestPipelineORM_Integration(t *testing.T) { c.JobPipeline.HTTPRequest.DefaultTimeout = commonconfig.MustNewDuration(30 * time.Millisecond) }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) ethKeyStore := keyStore.Eth() _, transmitterAddress := cltest.MustInsertRandomKey(t, ethKeyStore) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) var specID int32 diff --git a/core/services/job/kv_orm_test.go b/core/services/job/kv_orm_test.go index 3ba03b8bc3c..156779ffb4d 100644 --- a/core/services/job/kv_orm_test.go +++ b/core/services/job/kv_orm_test.go @@ -34,7 +34,7 @@ func TestJobKVStore(t *testing.T) { jobID := int32(1337) kvStore := job.NewKVStore(jobID, db, config.Database(), lggr) - jobORM := NewTestORM(t, db, pipelineORM, bridgesORM, cltest.NewKeyStore(t, db, config.Database()), config.Database()) + jobORM := NewTestORM(t, db, pipelineORM, bridgesORM, cltest.NewKeyStore(t, db), config.Database()) jb, err := directrequest.ValidatedDirectRequestSpec(testspecs.GetDirectRequestSpec()) require.NoError(t, err) diff --git a/core/services/job/runner_integration_test.go b/core/services/job/runner_integration_test.go index 6149bb71cf6..e13b1025b8b 100644 --- a/core/services/job/runner_integration_test.go +++ b/core/services/job/runner_integration_test.go @@ -54,17 +54,18 @@ import ( var monitoringEndpoint = telemetry.MonitoringEndpointGenerator(&telemetry.NoopAgent{}) func TestRunner(t *testing.T) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, pgtest.NewQConfig(true)) + keyStore := cltest.NewKeyStore(t, db) ethKeyStore := keyStore.Eth() _, transmitterAddress := cltest.MustInsertRandomKey(t, ethKeyStore) - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - kb, err := keyStore.OCR().Create() + kb, err := keyStore.OCR().Create(ctx) require.NoError(t, err) kbid := models.MustSha256HashFromHex(kb.ID()) c.OCR.KeyBundleID = &kbid @@ -79,7 +80,6 @@ func TestRunner(t *testing.T) { ethClient.On("HeadByNumber", mock.Anything, (*big.Int)(nil)).Return(cltest.Head(10), nil) ethClient.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Maybe().Return(nil, nil) - ctx := testutils.Context(t) pipelineORM := pipeline.NewORM(db, logger.TestLogger(t), config.JobPipeline().MaxSuccessfulRuns()) require.NoError(t, pipelineORM.Start(ctx)) t.Cleanup(func() { assert.NoError(t, pipelineORM.Close()) }) @@ -437,6 +437,7 @@ answer1 [type=median index=0]; }) t.Run("minimal bootstrap", func(t *testing.T) { + ctx := testutils.Context(t) s := ` type = "offchainreporting" schemaVersion = 1 @@ -454,7 +455,7 @@ answer1 [type=median index=0]; require.NoError(t, err) lggr := logger.TestLogger(t) - _, err = keyStore.P2P().Create() + _, err = keyStore.P2P().Create(ctx) assert.NoError(t, err) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, config.P2P(), config.OCR(), config.Database(), db, lggr) servicetest.Run(t, pw) @@ -475,7 +476,8 @@ answer1 [type=median index=0]; }) t.Run("test min non-bootstrap", func(t *testing.T) { - kb, err := keyStore.OCR().Create() + ctx := testutils.Context(t) + kb, err := keyStore.OCR().Create(ctx) require.NoError(t, err) s := fmt.Sprintf(minimalNonBootstrapTemplate, cltest.NewEIP55Address(), transmitterAddress.Hex(), kb.ID(), "http://blah.com", "") @@ -537,6 +539,7 @@ answer1 [type=median index=0]; }) t.Run("test enhanced telemetry service creation", func(t *testing.T) { + ctx := testutils.Context(t) testCases := []struct { jbCaptureEATelemetry bool specCaptureEATelemetry bool @@ -558,7 +561,7 @@ answer1 [type=median index=0]; relayExtenders = evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, Client: ethClient, GeneralConfig: config, KeyStore: ethKeyStore}) legacyChains = evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) - kb, err := keyStore.OCR().Create() + kb, err := keyStore.OCR().Create(ctx) require.NoError(t, err) s := fmt.Sprintf(minimalNonBootstrapTemplate, cltest.NewEIP55Address(), transmitterAddress.Hex(), kb.ID(), "http://blah.com", "") @@ -606,8 +609,9 @@ answer1 [type=median index=0]; }) t.Run("test job spec error is created", func(t *testing.T) { + ctx := testutils.Context(t) // Create a keystore with an ocr key bundle and p2p key. - kb, err := keyStore.OCR().Create() + kb, err := keyStore.OCR().Create(ctx) require.NoError(t, err) spec := fmt.Sprintf(ocrJobSpecTemplate, testutils.NewAddress().Hex(), kb.ID(), transmitterAddress.Hex(), fmt.Sprintf(simpleFetchDataSourceTemplate, "blah", true)) jb := makeOCRJobSpecFromToml(t, spec) @@ -636,7 +640,6 @@ answer1 [type=median index=0]; // Return an error getting the contract code. ethClient.On("CodeAt", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("no such code")) - ctx := testutils.Context(t) for _, s := range services { err = s.Start(ctx) require.NoError(t, err) diff --git a/core/services/job/spawner_test.go b/core/services/job/spawner_test.go index 802763cfaab..d3927da6590 100644 --- a/core/services/job/spawner_test.go +++ b/core/services/job/spawner_test.go @@ -75,14 +75,15 @@ func (g *relayGetter) Get(id relay.ID) (loop.Relayer, error) { func TestSpawner_CreateJobDeleteJob(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) config := configtest.NewTestGeneralConfig(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) ethKeyStore := keyStore.Eth() - require.NoError(t, keyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, keyStore.P2P().Add(cltest.DefaultP2PKey)) - require.NoError(t, keyStore.OCR2().Add(cltest.DefaultOCR2Key)) + require.NoError(t, keyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, keyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) + require.NoError(t, keyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key)) _, address := cltest.MustInsertRandomKey(t, ethKeyStore) _, bridge := cltest.MustCreateBridge(t, db, cltest.BridgeOpts{}) diff --git a/core/services/keeper/orm_test.go b/core/services/keeper/orm_test.go index 1e5d927fe2f..3d305f3e2b1 100644 --- a/core/services/keeper/orm_test.go +++ b/core/services/keeper/orm_test.go @@ -76,8 +76,8 @@ func assertLastRunHeight(t *testing.T, db *sqlx.DB, upkeep keeper.UpkeepRegistra func TestKeeperDB_Registries(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) @@ -90,8 +90,8 @@ func TestKeeperDB_Registries(t *testing.T) { func TestKeeperDB_RegistryByContractAddress(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) @@ -104,8 +104,8 @@ func TestKeeperDB_RegistryByContractAddress(t *testing.T) { func TestKeeperDB_UpsertUpkeep(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) upkeep := keeper.UpkeepRegistration{ @@ -140,8 +140,8 @@ func TestKeeperDB_UpsertUpkeep(t *testing.T) { func TestKeeperDB_BatchDeleteUpkeepsForJob(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, job := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) @@ -167,8 +167,8 @@ func TestKeeperDB_BatchDeleteUpkeepsForJob(t *testing.T) { func TestKeeperDB_EligibleUpkeeps_Shuffle(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() blockheight := int64(63) gracePeriod := int64(10) @@ -198,8 +198,8 @@ func TestKeeperDB_EligibleUpkeeps_Shuffle(t *testing.T) { func TestKeeperDB_NewEligibleUpkeeps_GracePeriod(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 2, 20) @@ -226,8 +226,8 @@ func TestKeeperDB_NewEligibleUpkeeps_GracePeriod(t *testing.T) { func TestKeeperDB_EligibleUpkeeps_TurnsRandom(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 3, 10) @@ -270,8 +270,8 @@ func TestKeeperDB_EligibleUpkeeps_TurnsRandom(t *testing.T) { func TestKeeperDB_NewEligibleUpkeeps_SkipIfLastPerformedByCurrentKeeper(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 2, 20) @@ -293,8 +293,8 @@ func TestKeeperDB_NewEligibleUpkeeps_SkipIfLastPerformedByCurrentKeeper(t *testi func TestKeeperDB_NewEligibleUpkeeps_CoverBuddy(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 1, 2, 20) @@ -318,8 +318,8 @@ func TestKeeperDB_NewEligibleUpkeeps_CoverBuddy(t *testing.T) { func TestKeeperDB_NewEligibleUpkeeps_FirstTurn(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 2, 20) @@ -340,8 +340,8 @@ func TestKeeperDB_NewEligibleUpkeeps_FirstTurn(t *testing.T) { func TestKeeperDB_NewEligibleUpkeeps_FiltersByRegistry(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry1, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) registry2, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) @@ -365,8 +365,8 @@ func TestKeeperDB_NewEligibleUpkeeps_FiltersByRegistry(t *testing.T) { func TestKeeperDB_AllUpkeepIDsForRegistry(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, _ := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) upkeepIDs, err := orm.AllUpkeepIDsForRegistry(ctx, registry.ID) @@ -394,8 +394,8 @@ func TestKeeperDB_AllUpkeepIDsForRegistry(t *testing.T) { func TestKeeperDB_UpdateUpkeepLastKeeperIndex(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, j := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) upkeep := cltest.MustInsertUpkeepForRegistry(t, db, registry) @@ -409,8 +409,8 @@ func TestKeeperDB_UpdateUpkeepLastKeeperIndex(t *testing.T) { func TestKeeperDB_NewSetLastRunInfoForUpkeepOnJob(t *testing.T) { t.Parallel() ctx := testutils.Context(t) - db, config, orm := setupKeeperDB(t) - ethKeyStore := cltest.NewKeyStore(t, db, config.Database()).Eth() + db, _, orm := setupKeeperDB(t) + ethKeyStore := cltest.NewKeyStore(t, db).Eth() registry, j := cltest.MustInsertKeeperRegistry(t, db, orm, ethKeyStore, 0, 1, 20) upkeep := cltest.MustInsertUpkeepForRegistry(t, db, registry) diff --git a/core/services/keeper/registry_synchronizer_helper_test.go b/core/services/keeper/registry_synchronizer_helper_test.go index c97d3c0c92c..2726c9a754d 100644 --- a/core/services/keeper/registry_synchronizer_helper_test.go +++ b/core/services/keeper/registry_synchronizer_helper_test.go @@ -40,7 +40,7 @@ func setupRegistrySync(t *testing.T, version keeper.RegistryVersion) ( cfg := configtest.NewGeneralConfig(t, nil) korm := keeper.NewORM(db, logger.TestLogger(t)) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) lbMock := logmocks.NewBroadcaster(t) lbMock.On("AddDependents", 1).Maybe() j := cltest.MustInsertKeeperJob(t, db, korm, cltest.NewEIP55Address(), cltest.NewEIP55Address()) diff --git a/core/services/keeper/upkeep_executer_test.go b/core/services/keeper/upkeep_executer_test.go index 10995ec3c0d..33850ea7134 100644 --- a/core/services/keeper/upkeep_executer_test.go +++ b/core/services/keeper/upkeep_executer_test.go @@ -75,7 +75,7 @@ func setup(t *testing.T, estimator gas.EvmFeeEstimator, overrideFn func(c *chain } }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ethClient := evmtest.NewEthClientMock(t) ethClient.On("ConfiguredChainID").Return(cfg.EVMConfigs()[0].ChainID.ToInt()).Maybe() ethClient.On("IsL2").Return(false).Maybe() diff --git a/core/services/keystore/cosmos.go b/core/services/keystore/cosmos.go index e3549fdb932..76fc5f39816 100644 --- a/core/services/keystore/cosmos.go +++ b/core/services/keystore/cosmos.go @@ -15,12 +15,12 @@ import ( type Cosmos interface { Get(id string) (cosmoskey.Key, error) GetAll() ([]cosmoskey.Key, error) - Create() (cosmoskey.Key, error) - Add(key cosmoskey.Key) error - Delete(id string) (cosmoskey.Key, error) - Import(keyJSON []byte, password string) (cosmoskey.Key, error) + Create(ctx context.Context) (cosmoskey.Key, error) + Add(ctx context.Context, key cosmoskey.Key) error + Delete(ctx context.Context, id string) (cosmoskey.Key, error) + Import(ctx context.Context, keyJSON []byte, password string) (cosmoskey.Key, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error } type cosmos struct { @@ -56,17 +56,17 @@ func (ks *cosmos) GetAll() (keys []cosmoskey.Key, _ error) { return keys, nil } -func (ks *cosmos) Create() (cosmoskey.Key, error) { +func (ks *cosmos) Create(ctx context.Context) (cosmoskey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { return cosmoskey.Key{}, ErrLocked } key := cosmoskey.New() - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *cosmos) Add(key cosmoskey.Key) error { +func (ks *cosmos) Add(ctx context.Context, key cosmoskey.Key) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -75,10 +75,10 @@ func (ks *cosmos) Add(key cosmoskey.Key) error { if _, found := ks.keyRing.Cosmos[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *cosmos) Delete(id string) (cosmoskey.Key, error) { +func (ks *cosmos) Delete(ctx context.Context, id string) (cosmoskey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -88,11 +88,11 @@ func (ks *cosmos) Delete(id string) (cosmoskey.Key, error) { if err != nil { return cosmoskey.Key{}, err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return key, err } -func (ks *cosmos) Import(keyJSON []byte, password string) (cosmoskey.Key, error) { +func (ks *cosmos) Import(ctx context.Context, keyJSON []byte, password string) (cosmoskey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -105,7 +105,7 @@ func (ks *cosmos) Import(keyJSON []byte, password string) (cosmoskey.Key, error) if _, found := ks.keyRing.Cosmos[key.ID()]; found { return cosmoskey.Key{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *cosmos) Export(id string, password string) ([]byte, error) { @@ -121,7 +121,7 @@ func (ks *cosmos) Export(id string, password string) ([]byte, error) { return key.ToEncryptedJSON(password, ks.scryptParams) } -func (ks *cosmos) EnsureKey() error { +func (ks *cosmos) EnsureKey(ctx context.Context) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -136,7 +136,7 @@ func (ks *cosmos) EnsureKey() error { ks.logger.Infof("Created Cosmos key with ID %s", key.ID()) - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } func (ks *cosmos) getByID(id string) (cosmoskey.Key, error) { diff --git a/core/services/keystore/cosmos_test.go b/core/services/keystore/cosmos_test.go index 30c669f7545..cad6dd67654 100644 --- a/core/services/keystore/cosmos_test.go +++ b/core/services/keystore/cosmos_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "testing" "github.com/stretchr/testify/assert" @@ -8,7 +9,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/cosmoskey" @@ -16,15 +17,15 @@ import ( func Test_CosmosKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.Cosmos() reset := func() { + ctx := context.Background() // Executed during cleanup require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -42,7 +43,8 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -51,21 +53,22 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) _, err = ks.Export("non-existent", cltest.Password) assert.Error(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) - _, err = ks.Import(exportJSON, cltest.Password) + _, err = ks.Import(ctx, exportJSON, cltest.Password) assert.Error(t, err) - _, err = ks.Import([]byte(""), cltest.Password) + _, err = ks.Import(ctx, []byte(""), cltest.Password) assert.Error(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -75,17 +78,18 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey := cosmoskey.New() - err := ks.Add(newKey) + err := ks.Add(ctx, newKey) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -96,10 +100,11 @@ func Test_CosmosKeyStore_E2E(t *testing.T) { t.Run("ensures key", func(t *testing.T) { defer reset() - err := ks.EnsureKey() + ctx := testutils.Context(t) + err := ks.EnsureKey(ctx) assert.NoError(t, err) - err = ks.EnsureKey() + err = ks.EnsureKey(ctx) assert.NoError(t, err) keys, err := ks.GetAll() diff --git a/core/services/keystore/csa.go b/core/services/keystore/csa.go index 01491b85b35..21b530c0650 100644 --- a/core/services/keystore/csa.go +++ b/core/services/keystore/csa.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "github.com/pkg/errors" @@ -17,12 +18,12 @@ var ErrCSAKeyExists = errors.New("can only have 1 CSA key") type CSA interface { Get(id string) (csakey.KeyV2, error) GetAll() ([]csakey.KeyV2, error) - Create() (csakey.KeyV2, error) - Add(key csakey.KeyV2) error - Delete(id string) (csakey.KeyV2, error) - Import(keyJSON []byte, password string) (csakey.KeyV2, error) + Create(ctx context.Context) (csakey.KeyV2, error) + Add(ctx context.Context, key csakey.KeyV2) error + Delete(ctx context.Context, id string) (csakey.KeyV2, error) + Import(ctx context.Context, keyJSON []byte, password string) (csakey.KeyV2, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error } type csa struct { @@ -58,7 +59,7 @@ func (ks *csa) GetAll() (keys []csakey.KeyV2, _ error) { return keys, nil } -func (ks *csa) Create() (csakey.KeyV2, error) { +func (ks *csa) Create(ctx context.Context) (csakey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -74,10 +75,10 @@ func (ks *csa) Create() (csakey.KeyV2, error) { if err != nil { return csakey.KeyV2{}, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *csa) Add(key csakey.KeyV2) error { +func (ks *csa) Add(ctx context.Context, key csakey.KeyV2) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -86,10 +87,10 @@ func (ks *csa) Add(key csakey.KeyV2) error { if len(ks.keyRing.CSA) > 0 { return ErrCSAKeyExists } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *csa) Delete(id string) (csakey.KeyV2, error) { +func (ks *csa) Delete(ctx context.Context, id string) (csakey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -100,12 +101,12 @@ func (ks *csa) Delete(id string) (csakey.KeyV2, error) { return csakey.KeyV2{}, err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return key, err } -func (ks *csa) Import(keyJSON []byte, password string) (csakey.KeyV2, error) { +func (ks *csa) Import(ctx context.Context, keyJSON []byte, password string) (csakey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -118,7 +119,7 @@ func (ks *csa) Import(keyJSON []byte, password string) (csakey.KeyV2, error) { if _, found := ks.keyRing.CSA[key.ID()]; found { return csakey.KeyV2{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *csa) Export(id string, password string) ([]byte, error) { @@ -135,7 +136,7 @@ func (ks *csa) Export(id string, password string) ([]byte, error) { } // EnsureKey verifies whether the CSA key has been seeded, if not, it creates it. -func (ks *csa) EnsureKey() error { +func (ks *csa) EnsureKey(ctx context.Context) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -153,7 +154,7 @@ func (ks *csa) EnsureKey() error { ks.logger.Infof("Created CSA key with ID %s", key.ID()) - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } func (ks *csa) getByID(id string) (csakey.KeyV2, error) { diff --git a/core/services/keystore/csa_test.go b/core/services/keystore/csa_test.go index b6dfb009593..84d79798011 100644 --- a/core/services/keystore/csa_test.go +++ b/core/services/keystore/csa_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "fmt" "testing" @@ -9,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" @@ -17,15 +18,15 @@ import ( func Test_CSAKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.CSA() reset := func() { + ctx := context.Background() // Executed on cleanup _, err := db.Exec("DELETE FROM encrypted_key_rings") require.NoError(t, err) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -43,14 +44,16 @@ func Test_CSAKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) require.Equal(t, key, retrievedKey) t.Run("prevents creating more than one key", func(t *testing.T) { - k, err2 := ks.Create() + ctx := testutils.Context(t) + k, err2 := ks.Create(ctx) assert.Zero(t, k) assert.Error(t, err2) @@ -60,15 +63,16 @@ func Test_CSAKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -76,7 +80,7 @@ func Test_CSAKeyStore_E2E(t *testing.T) { require.Equal(t, importedKey, retrievedKey) t.Run("prevents importing more than one key", func(t *testing.T) { - k, err2 := ks.Import(exportJSON, cltest.Password) + k, err2 := ks.Import(testutils.Context(t), exportJSON, cltest.Password) assert.Zero(t, k) assert.Error(t, err2) @@ -84,7 +88,7 @@ func Test_CSAKeyStore_E2E(t *testing.T) { }) t.Run("fails to import malformed key", func(t *testing.T) { - k, err2 := ks.Import([]byte(""), cltest.Password) + k, err2 := ks.Import(testutils.Context(t), []byte(""), cltest.Password) assert.Zero(t, k) assert.Error(t, err2) @@ -100,14 +104,15 @@ func Test_CSAKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := csakey.NewV2() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -116,17 +121,18 @@ func Test_CSAKeyStore_E2E(t *testing.T) { require.Error(t, err) t.Run("prevents adding more than one key", func(t *testing.T) { - err = ks.Add(newKey) + ctx := testutils.Context(t) + err = ks.Add(ctx, newKey) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.Error(t, err) assert.True(t, errors.Is(err, keystore.ErrCSAKeyExists)) }) t.Run("fails to delete non-existent key", func(t *testing.T) { - k, err2 := ks.Delete("non-existent") + k, err2 := ks.Delete(testutils.Context(t), "non-existent") assert.Zero(t, k) assert.Error(t, err2) @@ -135,13 +141,14 @@ func Test_CSAKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key/ensures it already exists", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := csakey.NewV2() assert.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.NoError(t, err) - err = keyStore.CSA().EnsureKey() + err = keyStore.CSA().EnsureKey(ctx) assert.NoError(t, err) keys, err2 := ks.GetAll() assert.NoError(t, err2) @@ -154,12 +161,13 @@ func Test_CSAKeyStore_E2E(t *testing.T) { t.Run("auto creates a key if it doesn't exists when trying to ensure it already exists", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) keys, err := ks.GetAll() assert.NoError(t, err) assert.Equal(t, 0, len(keys)) - err = keyStore.CSA().EnsureKey() + err = keyStore.CSA().EnsureKey(ctx) assert.NoError(t, err) keys, err = ks.GetAll() diff --git a/core/services/keystore/dkgencrypt.go b/core/services/keystore/dkgencrypt.go index c5d02034dad..15d0ae8b24d 100644 --- a/core/services/keystore/dkgencrypt.go +++ b/core/services/keystore/dkgencrypt.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "github.com/pkg/errors" @@ -14,12 +15,12 @@ import ( type DKGEncrypt interface { Get(id string) (dkgencryptkey.Key, error) GetAll() ([]dkgencryptkey.Key, error) - Create() (dkgencryptkey.Key, error) - Add(key dkgencryptkey.Key) error - Delete(id string) (dkgencryptkey.Key, error) - Import(keyJSON []byte, password string) (dkgencryptkey.Key, error) + Create(ctx context.Context) (dkgencryptkey.Key, error) + Add(ctx context.Context, key dkgencryptkey.Key) error + Delete(ctx context.Context, id string) (dkgencryptkey.Key, error) + Import(ctx context.Context, keyJSON []byte, password string) (dkgencryptkey.Key, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error } type dkgEncrypt struct { @@ -35,17 +36,17 @@ func newDKGEncryptKeyStore(km *keyManager) *dkgEncrypt { var _ DKGEncrypt = &dkgEncrypt{} // Add implements DKGEncrypt -func (d *dkgEncrypt) Add(key dkgencryptkey.Key) error { +func (d *dkgEncrypt) Add(ctx context.Context, key dkgencryptkey.Key) error { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { return ErrLocked } - return d.safeAddKey(key) + return d.safeAddKey(ctx, key) } // Create implements DKGEncrypt -func (d *dkgEncrypt) Create() (dkgencryptkey.Key, error) { +func (d *dkgEncrypt) Create(ctx context.Context) (dkgencryptkey.Key, error) { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -55,11 +56,11 @@ func (d *dkgEncrypt) Create() (dkgencryptkey.Key, error) { if err != nil { return dkgencryptkey.Key{}, errors.Wrap(err, "dkgencryptkey.New()") } - return key, d.safeAddKey(key) + return key, d.safeAddKey(ctx, key) } // Delete implements DKGEncrypt -func (d *dkgEncrypt) Delete(id string) (dkgencryptkey.Key, error) { +func (d *dkgEncrypt) Delete(ctx context.Context, id string) (dkgencryptkey.Key, error) { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -70,12 +71,12 @@ func (d *dkgEncrypt) Delete(id string) (dkgencryptkey.Key, error) { return dkgencryptkey.Key{}, err } - err = d.safeRemoveKey(key) + err = d.safeRemoveKey(ctx, key) return key, errors.Wrap(err, "safe remove key") } // EnsureKey implements DKGEncrypt -func (d *dkgEncrypt) EnsureKey() error { +func (d *dkgEncrypt) EnsureKey(ctx context.Context) error { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -92,7 +93,7 @@ func (d *dkgEncrypt) EnsureKey() error { d.logger.Infof("Created DKGEncrypt key with ID %s", key.ID()) - return d.safeAddKey(key) + return d.safeAddKey(ctx, key) } // Export implements DKGEncrypt @@ -133,7 +134,7 @@ func (d *dkgEncrypt) GetAll() (keys []dkgencryptkey.Key, err error) { } // Import implements DKGEncrypt -func (d *dkgEncrypt) Import(keyJSON []byte, password string) (dkgencryptkey.Key, error) { +func (d *dkgEncrypt) Import(ctx context.Context, keyJSON []byte, password string) (dkgencryptkey.Key, error) { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -147,7 +148,7 @@ func (d *dkgEncrypt) Import(keyJSON []byte, password string) (dkgencryptkey.Key, if err == nil { return dkgencryptkey.Key{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, d.keyManager.safeAddKey(key) + return key, d.keyManager.safeAddKey(ctx, key) } // caller must hold lock diff --git a/core/services/keystore/dkgencrypt_test.go b/core/services/keystore/dkgencrypt_test.go index 36f48f9c2b4..4856473a0df 100644 --- a/core/services/keystore/dkgencrypt_test.go +++ b/core/services/keystore/dkgencrypt_test.go @@ -1,13 +1,14 @@ package keystore_test import ( + "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/dkgencryptkey" @@ -15,18 +16,18 @@ import ( func Test_DKGEncryptKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.DKGEncrypt() assert.NotNil(t, ks) reset := func() { + ctx := context.Background() // Executed on cleanup _, err := db.Exec("DELETE FROM encrypted_key_rings") require.NoError(t, err) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -44,7 +45,8 @@ func Test_DKGEncryptKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -53,15 +55,16 @@ func Test_DKGEncryptKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -71,14 +74,15 @@ func Test_DKGEncryptKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := dkgencryptkey.New() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -89,13 +93,14 @@ func Test_DKGEncryptKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key/ensures it already exists", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := dkgencryptkey.New() assert.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.NoError(t, err) - err = keyStore.DKGEncrypt().EnsureKey() + err = keyStore.DKGEncrypt().EnsureKey(ctx) assert.NoError(t, err) keys, err2 := ks.GetAll() assert.NoError(t, err2) @@ -107,12 +112,13 @@ func Test_DKGEncryptKeyStore_E2E(t *testing.T) { t.Run("auto creates a key if it doesn't exists when trying to ensure it already exists", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) keys, err := ks.GetAll() assert.NoError(t, err) assert.Equal(t, 0, len(keys)) - err = keyStore.DKGEncrypt().EnsureKey() + err = keyStore.DKGEncrypt().EnsureKey(ctx) assert.NoError(t, err) keys, err = ks.GetAll() diff --git a/core/services/keystore/dkgsign.go b/core/services/keystore/dkgsign.go index e609b441831..385323fc0fa 100644 --- a/core/services/keystore/dkgsign.go +++ b/core/services/keystore/dkgsign.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "github.com/pkg/errors" @@ -14,12 +15,12 @@ import ( type DKGSign interface { Get(id string) (dkgsignkey.Key, error) GetAll() ([]dkgsignkey.Key, error) - Create() (dkgsignkey.Key, error) - Add(key dkgsignkey.Key) error - Delete(id string) (dkgsignkey.Key, error) - Import(keyJSON []byte, password string) (dkgsignkey.Key, error) + Create(ctx context.Context) (dkgsignkey.Key, error) + Add(ctx context.Context, key dkgsignkey.Key) error + Delete(ctx context.Context, id string) (dkgsignkey.Key, error) + Import(ctx context.Context, keyJSON []byte, password string) (dkgsignkey.Key, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error } type dkgSign struct { @@ -35,17 +36,17 @@ func newDKGSignKeyStore(km *keyManager) *dkgSign { var _ DKGSign = &dkgSign{} // Add implements DKGSign -func (d *dkgSign) Add(key dkgsignkey.Key) error { +func (d *dkgSign) Add(ctx context.Context, key dkgsignkey.Key) error { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { return ErrLocked } - return d.safeAddKey(key) + return d.safeAddKey(ctx, key) } // Create implements DKGSign -func (d *dkgSign) Create() (dkgsignkey.Key, error) { +func (d *dkgSign) Create(ctx context.Context) (dkgsignkey.Key, error) { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -55,11 +56,11 @@ func (d *dkgSign) Create() (dkgsignkey.Key, error) { if err != nil { return dkgsignkey.Key{}, errors.Wrap(err, "dkgsignkey New()") } - return key, d.safeAddKey(key) + return key, d.safeAddKey(ctx, key) } // Delete implements DKGSign -func (d *dkgSign) Delete(id string) (dkgsignkey.Key, error) { +func (d *dkgSign) Delete(ctx context.Context, id string) (dkgsignkey.Key, error) { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -70,12 +71,12 @@ func (d *dkgSign) Delete(id string) (dkgsignkey.Key, error) { return dkgsignkey.Key{}, err } - err = d.safeRemoveKey(key) + err = d.safeRemoveKey(ctx, key) return key, errors.Wrap(err, "safe remove key") } // EnsureKey implements DKGSign -func (d *dkgSign) EnsureKey() error { +func (d *dkgSign) EnsureKey(ctx context.Context) error { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -92,7 +93,7 @@ func (d *dkgSign) EnsureKey() error { d.logger.Infof("Created DKGSign key with ID %s", key.ID()) - return d.safeAddKey(key) + return d.safeAddKey(ctx, key) } // Export implements DKGSign @@ -133,7 +134,7 @@ func (d *dkgSign) GetAll() (keys []dkgsignkey.Key, err error) { } // Import implements DKGSign -func (d *dkgSign) Import(keyJSON []byte, password string) (dkgsignkey.Key, error) { +func (d *dkgSign) Import(ctx context.Context, keyJSON []byte, password string) (dkgsignkey.Key, error) { d.lock.Lock() defer d.lock.Unlock() if d.isLocked() { @@ -147,7 +148,7 @@ func (d *dkgSign) Import(keyJSON []byte, password string) (dkgsignkey.Key, error if err == nil { return dkgsignkey.Key{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, d.keyManager.safeAddKey(key) + return key, d.keyManager.safeAddKey(ctx, key) } // caller must hold lock diff --git a/core/services/keystore/dkgsign_test.go b/core/services/keystore/dkgsign_test.go index 5ea23a516be..8aa8cb1ad74 100644 --- a/core/services/keystore/dkgsign_test.go +++ b/core/services/keystore/dkgsign_test.go @@ -1,13 +1,14 @@ package keystore_test import ( + "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/dkgsignkey" @@ -15,18 +16,18 @@ import ( func Test_DKGSignKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.DKGSign() assert.NotNil(t, ks) reset := func() { + ctx := context.Background() // Executed on cleanup _, err := db.Exec("DELETE FROM encrypted_key_rings") require.NoError(t, err) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -44,7 +45,8 @@ func Test_DKGSignKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -53,15 +55,16 @@ func Test_DKGSignKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -71,14 +74,15 @@ func Test_DKGSignKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := dkgsignkey.New() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -89,13 +93,13 @@ func Test_DKGSignKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key/ensures it already exists", func(t *testing.T) { defer reset() - + ctx := testutils.Context(t) newKey, err := dkgsignkey.New() assert.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.NoError(t, err) - err = keyStore.DKGSign().EnsureKey() + err = keyStore.DKGSign().EnsureKey(ctx) assert.NoError(t, err) keys, err2 := ks.GetAll() assert.NoError(t, err2) @@ -107,12 +111,13 @@ func Test_DKGSignKeyStore_E2E(t *testing.T) { t.Run("auto creates a key if it doesn't exists when trying to ensure it already exists", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) keys, err := ks.GetAll() assert.NoError(t, err) assert.Equal(t, 0, len(keys)) - err = keyStore.DKGSign().EnsureKey() + err = keyStore.DKGSign().EnsureKey(ctx) assert.NoError(t, err) keys, err = ks.GetAll() diff --git a/core/services/keystore/eth.go b/core/services/keystore/eth.go index be59cb5e54c..a4365eb9092 100644 --- a/core/services/keystore/eth.go +++ b/core/services/keystore/eth.go @@ -13,8 +13,8 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -29,9 +29,9 @@ type Eth interface { Import(ctx context.Context, keyJSON []byte, password string, chainIDs ...*big.Int) (ethkey.KeyV2, error) Export(ctx context.Context, id string, password string) ([]byte, error) - Enable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error - Disable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error - Add(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error + Enable(ctx context.Context, address common.Address, chainID *big.Int) error + Disable(ctx context.Context, address common.Address, chainID *big.Int) error + Add(ctx context.Context, address common.Address, chainID *big.Int) error EnsureKeys(ctx context.Context, chainIDs ...*big.Int) error SubscribeToKeyChanges(ctx context.Context) (ch chan struct{}, unsub func()) @@ -55,18 +55,18 @@ type Eth interface { type eth struct { *keyManager keystateORM - q pg.Q + ds sqlutil.DataSource subscribers [](chan struct{}) subscribersMu *sync.RWMutex } var _ Eth = ð{} -func newEthKeyStore(km *keyManager, orm keystateORM, q pg.Q) *eth { +func newEthKeyStore(km *keyManager, orm keystateORM, ds sqlutil.DataSource) *eth { return ð{ keystateORM: orm, keyManager: km, - q: q, + ds: ds, subscribers: make([](chan struct{}), 0), subscribersMu: new(sync.RWMutex), } @@ -111,9 +111,10 @@ func (ks *eth) Create(ctx context.Context, chainIDs ...*big.Int) (ethkey.KeyV2, return ethkey.KeyV2{}, err } err = ks.add(ctx, key, chainIDs...) - if err == nil { - ks.notify() + if err != nil { + return ethkey.KeyV2{}, errors.Wrap(err, "unable to add eth key") } + ks.notify() ks.logger.Infow(fmt.Sprintf("Created EVM key with ID %s", key.Address.Hex()), "address", key.Address.Hex(), "evmChainIDs", chainIDs) return key, err } @@ -139,7 +140,7 @@ func (ks *eth) EnsureKeys(ctx context.Context, chainIDs ...*big.Int) (err error) } err = ks.add(ctx, newKey, chainID) if err != nil { - return err + return fmt.Errorf("failed to add key %s for chain %s: %w", newKey.Address, chainID, err) } ks.logger.Infow(fmt.Sprintf("Created EVM key with ID %s", newKey.Address.Hex()), "address", newKey.Address.Hex(), "evmChainID", chainID) } @@ -182,27 +183,29 @@ func (ks *eth) Export(ctx context.Context, id string, password string) ([]byte, return key.ToEncryptedJSON(password, ks.scryptParams) } -func (ks *eth) Add(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { +func (ks *eth) Add(ctx context.Context, address common.Address, chainID *big.Int) error { ks.lock.Lock() defer ks.lock.Unlock() _, found := ks.keyRing.Eth[address.Hex()] if !found { return ErrKeyNotFound } - return ks.addKey(ctx, address, chainID, qopts...) + return ks.addKey(ctx, nil, address, chainID) } // caller must hold lock! -func (ks *eth) addKey(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { +// ds is optional, for transactions +func (ks *eth) addKey(ctx context.Context, ds sqlutil.DataSource, address common.Address, chainID *big.Int) error { + if ds == nil { + ds = ks.ds + } state := new(ethkey.State) sql := `INSERT INTO evm.key_states (address, disabled, evm_chain_id, created_at, updated_at) VALUES ($1, false, $2, NOW(), NOW()) RETURNING *;` - q := ks.q.WithOpts(qopts...) - q = q.WithOpts(pg.WithParentCtx(ctx)) - if err := q.Get(state, sql, address, chainID.String()); err != nil { - return errors.Wrap(err, "failed to insert evm_key_state") + if err := ds.GetContext(ctx, state, sql, address, chainID.String()); err != nil { + return errors.Wrap(err, "failed to insert key_state") } // consider: do we really need a cache of the keystates? ks.keyStates.add(state) @@ -210,24 +213,23 @@ func (ks *eth) addKey(ctx context.Context, address common.Address, chainID *big. return nil } -func (ks *eth) Enable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { +func (ks *eth) Enable(ctx context.Context, address common.Address, chainID *big.Int) error { ks.lock.Lock() defer ks.lock.Unlock() _, found := ks.keyRing.Eth[address.Hex()] if !found { return ErrKeyNotFound } - return ks.enable(ctx, address, chainID, qopts...) + return ks.enable(ctx, address, chainID) } // caller must hold lock! -func (ks *eth) enable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { +func (ks *eth) enable(ctx context.Context, address common.Address, chainID *big.Int) error { state := new(ethkey.State) - q := ks.q.WithOpts(qopts...) sql := `INSERT INTO evm.key_states as key_states ("address", "evm_chain_id", "disabled", "created_at", "updated_at") VALUES ($1, $2, false, NOW(), NOW()) ON CONFLICT ("address", "evm_chain_id") DO UPDATE SET "disabled" = false, "updated_at" = NOW() WHERE key_states."address" = $1 AND key_states."evm_chain_id" = $2 RETURNING *;` - if err := q.Get(state, sql, address, chainID.String()); err != nil { + if err := ks.ds.GetContext(ctx, state, sql, address, chainID.String()); err != nil { return errors.Wrap(err, "failed to enable state") } @@ -240,23 +242,22 @@ func (ks *eth) enable(ctx context.Context, address common.Address, chainID *big. return nil } -func (ks *eth) Disable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { +func (ks *eth) Disable(ctx context.Context, address common.Address, chainID *big.Int) error { ks.lock.Lock() defer ks.lock.Unlock() _, found := ks.keyRing.Eth[address.Hex()] if !found { return errors.Errorf("no key exists with ID %s", address.Hex()) } - return ks.disable(ctx, address, chainID, qopts...) + return ks.disable(ctx, address, chainID) } -func (ks *eth) disable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { +func (ks *eth) disable(ctx context.Context, address common.Address, chainID *big.Int) error { state := new(ethkey.State) - q := ks.q.WithOpts(qopts...) sql := `INSERT INTO evm.key_states as key_states ("address", "evm_chain_id", "disabled", "created_at", "updated_at") VALUES ($1, $2, true, NOW(), NOW()) ON CONFLICT ("address", "evm_chain_id") DO UPDATE SET "disabled" = true, "updated_at" = NOW() WHERE key_states."address" = $1 AND key_states."evm_chain_id" = $2 RETURNING *;` - if err := q.Get(state, sql, address, chainID.String()); err != nil { + if err := ks.ds.GetContext(ctx, state, sql, address, chainID.String()); err != nil { return errors.Wrap(err, "failed to disable state") } @@ -279,8 +280,8 @@ func (ks *eth) Delete(ctx context.Context, id string) (ethkey.KeyV2, error) { if err != nil { return ethkey.KeyV2{}, err } - err = ks.safeRemoveKey(key, func(tx pg.Queryer) error { - _, err2 := tx.Exec(`DELETE FROM evm.key_states WHERE address = $1`, key.Address) + err = ks.safeRemoveKey(ctx, key, func(ds sqlutil.DataSource) error { + _, err2 := ds.ExecContext(ctx, `DELETE FROM evm.key_states WHERE address = $1`, key.Address) return err2 }) if err != nil { @@ -511,7 +512,7 @@ func (ks *eth) XXXTestingOnlySetState(ctx context.Context, state ethkey.State) { *existingState = state sql := `UPDATE evm.key_states SET address = :address, is_disabled = :is_disabled, evm_chain_id = :evm_chain_id, updated_at = NOW() WHERE address = :address;` - _, err := ks.q.NamedExec(sql, state) + _, err := ks.ds.NamedExecContext(ctx, sql, state) if err != nil { panic(err.Error()) } @@ -565,9 +566,9 @@ func (ks *eth) keysForChain(chainID *big.Int, includeDisabled bool) (keys []ethk // caller must hold lock! func (ks *eth) add(ctx context.Context, key ethkey.KeyV2, chainIDs ...*big.Int) (err error) { - err = ks.safeAddKey(key, func(tx pg.Queryer) (serr error) { + err = ks.safeAddKey(ctx, key, func(tx sqlutil.DataSource) (serr error) { for _, chainID := range chainIDs { - if serr = ks.addKey(ctx, key.Address, chainID, pg.WithQueryer(tx)); serr != nil { + if serr = ks.addKey(ctx, tx, key.Address, chainID); serr != nil { return serr } } diff --git a/core/services/keystore/eth_test.go b/core/services/keystore/eth_test.go index 6bc346bf4f8..07a41599f7d 100644 --- a/core/services/keystore/eth_test.go +++ b/core/services/keystore/eth_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "fmt" "math/big" "sort" @@ -12,13 +13,14 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" commonutils "github.com/smartcontractkit/chainlink-common/pkg/utils" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" ubig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" @@ -27,18 +29,20 @@ import ( func Test_EthKeyStore(t *testing.T) { t.Parallel() - db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) + db := sqlutil.WrapDataSource(pgtest.NewSqlxDB(t), logger.Test(t), sqlutil.TimeoutHook(func() time.Duration { + return 5 * time.Minute + }), sqlutil.MonitorHook(func() bool { return true })) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - err := keyStore.Unlock(cltest.Password) + keyStore := keystore.ExposedNewMaster(t, db) + err := keyStore.Unlock(testutils.Context(t), cltest.Password) require.NoError(t, err) ethKeyStore := keyStore.Eth() reset := func() { + ctx := context.Background() // Executed on cleanup keyStore.ResetXXXTestOnly() - require.NoError(t, commonutils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) - require.NoError(t, commonutils.JustError(db.Exec("DELETE FROM evm.key_states"))) - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, commonutils.JustError(db.ExecContext(ctx, "DELETE FROM encrypted_key_rings"))) + require.NoError(t, commonutils.JustError(db.ExecContext(ctx, "DELETE FROM evm.key_states"))) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } const statesTableName = "evm.key_states" @@ -58,11 +62,11 @@ func Test_EthKeyStore(t *testing.T) { cltest.AssertCount(t, db, statesTableName, 1) var state ethkey.State sql := fmt.Sprintf(`SELECT address, disabled, evm_chain_id, created_at, updated_at from %s LIMIT 1`, statesTableName) - require.NoError(t, db.Get(&state, sql)) + require.NoError(t, db.GetContext(ctx, &state, sql)) require.Equal(t, state.Address.Address(), retrievedKeys[0].Address) // adds key to db keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) retrievedKeys, err = ethKeyStore.GetAll(ctx) require.NoError(t, err) require.Equal(t, 1, len(retrievedKeys)) @@ -217,9 +221,8 @@ func Test_EthKeyStore_GetRoundRobinAddress(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ethKeyStore := keyStore.Eth() t.Run("should error when no addresses", func(t *testing.T) { @@ -341,8 +344,7 @@ func Test_EthKeyStore_SignTx(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - config := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) ethKeyStore := keyStore.Eth() k, _ := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -364,17 +366,17 @@ func Test_EthKeyStore_E2E(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - err := keyStore.Unlock(cltest.Password) + keyStore := keystore.ExposedNewMaster(t, db) + err := keyStore.Unlock(testutils.Context(t), cltest.Password) require.NoError(t, err) ks := keyStore.Eth() reset := func() { + ctx := testutils.Context(t) keyStore.ResetXXXTestOnly() require.NoError(t, commonutils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) require.NoError(t, commonutils.JustError(db.Exec("DELETE FROM evm.key_states"))) - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -499,8 +501,7 @@ func Test_EthKeyStore_SubscribeToKeyChanges(t *testing.T) { chDone := make(chan struct{}) defer func() { close(chDone) }() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() chSub, unsubscribe := ks.SubscribeToKeyChanges(ctx) defer unsubscribe() @@ -567,8 +568,7 @@ func Test_EthKeyStore_Enable(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() t.Run("already existing disabled key gets enabled", func(t *testing.T) { @@ -618,8 +618,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { t.Run("creates one unique key per chain if none exist", func(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() testutils.AssertCount(t, db, "evm.key_states", 0) @@ -634,8 +633,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { t.Run("does nothing if a key exists for a chain", func(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() // Add one enabled key @@ -658,8 +656,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { t.Run("does nothing if a key exists but is disabled for a chain", func(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() // Add one enabled key @@ -693,8 +690,7 @@ func Test_EthKeyStore_Delete(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() randKeyID := utils.RandomAddress().Hex() @@ -741,8 +737,7 @@ func Test_EthKeyStore_CheckEnabled(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() // create keys @@ -827,8 +822,7 @@ func Test_EthKeyStore_Disable(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) ks := keyStore.Eth() t.Run("creates key, deletes it unsafely and then enable creates it again", func(t *testing.T) { diff --git a/core/services/keystore/helpers_test.go b/core/services/keystore/helpers_test.go index d0b2a21ab38..e53e0af0c20 100644 --- a/core/services/keystore/helpers_test.go +++ b/core/services/keystore/helpers_test.go @@ -1,15 +1,14 @@ package keystore import ( + "context" "testing" "github.com/stretchr/testify/require" - "github.com/jmoiron/sqlx" - + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -19,14 +18,14 @@ func mustNewEthKey(t *testing.T) *ethkey.KeyV2 { return &key } -func ExposedNewMaster(t *testing.T, db *sqlx.DB, cfg pg.QConfig) *master { - return newMaster(db, utils.FastScryptParams, logger.TestLogger(t), cfg) +func ExposedNewMaster(t *testing.T, ds sqlutil.DataSource) *master { + return newMaster(ds, utils.FastScryptParams, logger.TestLogger(t)) } -func (m *master) ExportedSave() error { +func (m *master) ExportedSave(ctx context.Context) error { m.lock.Lock() defer m.lock.Unlock() - return m.save() + return m.save(ctx) } func (m *master) ResetXXXTestOnly() { diff --git a/core/services/keystore/keystoretest.go b/core/services/keystore/keystoretest.go index 6efc8e76bcf..91dc87ffe95 100644 --- a/core/services/keystore/keystoretest.go +++ b/core/services/keystore/keystoretest.go @@ -1,13 +1,12 @@ package keystore import ( + "context" "errors" "sync" - "github.com/jmoiron/sqlx" - + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/logger" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -19,25 +18,25 @@ import ( // to support DB callbacks. type memoryORM struct { keyRing *encryptedKeyRing - q pg.Queryer + ds sqlutil.DataSource mu sync.RWMutex } -func (o *memoryORM) isEmpty() (bool, error) { +func (o *memoryORM) isEmpty(ctx context.Context) (bool, error) { return false, nil } -func (o *memoryORM) saveEncryptedKeyRing(kr *encryptedKeyRing, callbacks ...func(pg.Queryer) error) (err error) { +func (o *memoryORM) saveEncryptedKeyRing(ctx context.Context, kr *encryptedKeyRing, callbacks ...func(sqlutil.DataSource) error) (err error) { o.mu.Lock() defer o.mu.Unlock() o.keyRing = kr for _, c := range callbacks { - err = errors.Join(err, c(o.q)) + err = errors.Join(err, c(o.ds)) } return } -func (o *memoryORM) getEncryptedKeyRing() (encryptedKeyRing, error) { +func (o *memoryORM) getEncryptedKeyRing(ctx context.Context) (encryptedKeyRing, error) { o.mu.RLock() defer o.mu.RUnlock() if o.keyRing == nil { @@ -46,15 +45,15 @@ func (o *memoryORM) getEncryptedKeyRing() (encryptedKeyRing, error) { return *o.keyRing, nil } -func newInMemoryORM(q pg.Queryer) *memoryORM { - return &memoryORM{q: q} +func newInMemoryORM(ds sqlutil.DataSource) *memoryORM { + return &memoryORM{ds: ds} } // NewInMemory sets up a keystore which NOOPs attempts to access the `encrypted_key_rings` table. Accessing `evm.key_states` // will still hit the DB. -func NewInMemory(db *sqlx.DB, scryptParams utils.ScryptParams, lggr logger.Logger, cfg pg.QConfig) *master { - dbORM := NewORM(db, lggr, cfg) - memoryORM := newInMemoryORM(dbORM.q) +func NewInMemory(ds sqlutil.DataSource, scryptParams utils.ScryptParams, lggr logger.Logger) *master { + dbORM := NewORM(ds, lggr) + memoryORM := newInMemoryORM(ds) km := &keyManager{ orm: memoryORM, @@ -68,7 +67,7 @@ func NewInMemory(db *sqlx.DB, scryptParams utils.ScryptParams, lggr logger.Logge keyManager: km, cosmos: newCosmosKeyStore(km), csa: newCSAKeyStore(km), - eth: newEthKeyStore(km, dbORM, dbORM.q), + eth: newEthKeyStore(km, dbORM, ds), ocr: newOCRKeyStore(km), ocr2: newOCR2KeyStore(km), p2p: newP2PKeyStore(km), diff --git a/core/services/keystore/master.go b/core/services/keystore/master.go index 05f19495f9d..bb5b21a96f0 100644 --- a/core/services/keystore/master.go +++ b/core/services/keystore/master.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "math/big" "reflect" @@ -8,8 +9,7 @@ import ( "github.com/pkg/errors" - "github.com/jmoiron/sqlx" - + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/cosmoskey" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" @@ -22,7 +22,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/solkey" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/starkkey" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/vrfkey" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -50,8 +49,8 @@ type Master interface { Cosmos() Cosmos StarkNet() StarkNet VRF() VRF - Unlock(password string) error - IsEmpty() (bool, error) + Unlock(ctx context.Context, password string) error + IsEmpty(ctx context.Context) (bool, error) } type master struct { @@ -69,12 +68,12 @@ type master struct { dkgEncrypt *dkgEncrypt } -func New(db *sqlx.DB, scryptParams utils.ScryptParams, lggr logger.Logger, cfg pg.QConfig) Master { - return newMaster(db, scryptParams, lggr, cfg) +func New(ds sqlutil.DataSource, scryptParams utils.ScryptParams, lggr logger.Logger) Master { + return newMaster(ds, scryptParams, lggr) } -func newMaster(db *sqlx.DB, scryptParams utils.ScryptParams, lggr logger.Logger, cfg pg.QConfig) *master { - orm := NewORM(db, lggr, cfg) +func newMaster(ds sqlutil.DataSource, scryptParams utils.ScryptParams, lggr logger.Logger) *master { + orm := NewORM(ds, lggr) km := &keyManager{ orm: orm, keystateORM: orm, @@ -87,7 +86,7 @@ func newMaster(db *sqlx.DB, scryptParams utils.ScryptParams, lggr logger.Logger, keyManager: km, cosmos: newCosmosKeyStore(km), csa: newCSAKeyStore(km), - eth: newEthKeyStore(km, orm, orm.q), + eth: newEthKeyStore(km, orm, orm.ds), ocr: newOCRKeyStore(km), ocr2: newOCR2KeyStore(km), p2p: newP2PKeyStore(km), @@ -144,13 +143,13 @@ func (ks *master) VRF() VRF { } type ORM interface { - isEmpty() (bool, error) - saveEncryptedKeyRing(*encryptedKeyRing, ...func(pg.Queryer) error) error - getEncryptedKeyRing() (encryptedKeyRing, error) + isEmpty(context.Context) (bool, error) + saveEncryptedKeyRing(context.Context, *encryptedKeyRing, ...func(sqlutil.DataSource) error) error + getEncryptedKeyRing(context.Context) (encryptedKeyRing, error) } type keystateORM interface { - loadKeyStates() (*keyStates, error) + loadKeyStates(context.Context) (*keyStates, error) } type keyManager struct { @@ -164,11 +163,11 @@ type keyManager struct { logger logger.Logger } -func (km *keyManager) IsEmpty() (bool, error) { - return km.orm.isEmpty() +func (km *keyManager) IsEmpty(ctx context.Context) (bool, error) { + return km.orm.isEmpty(ctx) } -func (km *keyManager) Unlock(password string) error { +func (km *keyManager) Unlock(ctx context.Context, password string) error { km.lock.Lock() defer km.lock.Unlock() // DEV: allow Unlock() to be idempotent - this is especially useful in tests, @@ -178,7 +177,7 @@ func (km *keyManager) Unlock(password string) error { } return nil } - ekr, err := km.orm.getEncryptedKeyRing() + ekr, err := km.orm.getEncryptedKeyRing(ctx) if err != nil { return errors.Wrap(err, "unable to get encrypted key ring") } @@ -189,7 +188,7 @@ func (km *keyManager) Unlock(password string) error { kr.logPubKeys(km.logger) km.keyRing = kr - ks, err := km.keystateORM.loadKeyStates() + ks, err := km.keystateORM.loadKeyStates(ctx) if err != nil { return errors.Wrap(err, "unable to load key states") } @@ -200,16 +199,16 @@ func (km *keyManager) Unlock(password string) error { } // caller must hold lock! -func (km *keyManager) save(callbacks ...func(pg.Queryer) error) error { +func (km *keyManager) save(ctx context.Context, callbacks ...func(sqlutil.DataSource) error) error { ekb, err := km.keyRing.Encrypt(km.password, km.scryptParams) if err != nil { return errors.Wrap(err, "unable to encrypt keyRing") } - return km.orm.saveEncryptedKeyRing(&ekb, callbacks...) + return km.orm.saveEncryptedKeyRing(ctx, &ekb, callbacks...) } // caller must hold lock! -func (km *keyManager) safeAddKey(unknownKey Key, callbacks ...func(pg.Queryer) error) error { +func (km *keyManager) safeAddKey(ctx context.Context, unknownKey Key, callbacks ...func(sqlutil.DataSource) error) error { fieldName, err := GetFieldNameForKey(unknownKey) if err != nil { return err @@ -221,7 +220,7 @@ func (km *keyManager) safeAddKey(unknownKey Key, callbacks ...func(pg.Queryer) e keyMap := keyRing.FieldByName(fieldName) keyMap.SetMapIndex(id, key) // save keyring to DB - err = km.save(callbacks...) + err = km.save(ctx, callbacks...) // if save fails, remove key from keyring if err != nil { keyMap.SetMapIndex(id, reflect.Value{}) @@ -231,7 +230,7 @@ func (km *keyManager) safeAddKey(unknownKey Key, callbacks ...func(pg.Queryer) e } // caller must hold lock! -func (km *keyManager) safeRemoveKey(unknownKey Key, callbacks ...func(pg.Queryer) error) (err error) { +func (km *keyManager) safeRemoveKey(ctx context.Context, unknownKey Key, callbacks ...func(sqlutil.DataSource) error) (err error) { fieldName, err := GetFieldNameForKey(unknownKey) if err != nil { return err @@ -242,7 +241,7 @@ func (km *keyManager) safeRemoveKey(unknownKey Key, callbacks ...func(pg.Queryer keyMap := keyRing.FieldByName(fieldName) keyMap.SetMapIndex(id, reflect.Value{}) // save keyring to DB - err = km.save(callbacks...) + err = km.save(ctx, callbacks...) // if save fails, add key back to keyRing if err != nil { keyMap.SetMapIndex(id, key) diff --git a/core/services/keystore/master_test.go b/core/services/keystore/master_test.go index 73f636c6625..e41a7a771ae 100644 --- a/core/services/keystore/master_test.go +++ b/core/services/keystore/master_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" ) @@ -16,9 +16,8 @@ func TestMasterKeystore_Unlock_Save(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) + keyStore := keystore.ExposedNewMaster(t, db) const tableName = "encrypted_key_rings" reset := func() { keyStore.ResetXXXTestOnly() @@ -28,36 +27,40 @@ func TestMasterKeystore_Unlock_Save(t *testing.T) { t.Run("can be unlocked more than once, as long as the passwords match", func(t *testing.T) { defer reset() - require.NoError(t, keyStore.Unlock(cltest.Password)) - require.NoError(t, keyStore.Unlock(cltest.Password)) - require.NoError(t, keyStore.Unlock(cltest.Password)) - require.Error(t, keyStore.Unlock("wrong password")) + ctx := testutils.Context(t) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) + require.Error(t, keyStore.Unlock(ctx, "wrong password")) }) t.Run("saves an empty keyRing", func(t *testing.T) { defer reset() - require.NoError(t, keyStore.Unlock(cltest.Password)) + ctx := testutils.Context(t) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) cltest.AssertCount(t, db, tableName, 1) - require.NoError(t, keyStore.ExportedSave()) + require.NoError(t, keyStore.ExportedSave(ctx)) cltest.AssertCount(t, db, tableName, 1) }) t.Run("won't load a saved keyRing if the password is incorrect", func(t *testing.T) { defer reset() - require.NoError(t, keyStore.Unlock(cltest.Password)) + ctx := testutils.Context(t) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) cltest.MustInsertRandomKey(t, keyStore.Eth()) // need at least 1 key to encrypt cltest.AssertCount(t, db, tableName, 1) keyStore.ResetXXXTestOnly() cltest.AssertCount(t, db, tableName, 1) - require.Error(t, keyStore.Unlock("password2")) + require.Error(t, keyStore.Unlock(ctx, "password2")) cltest.AssertCount(t, db, tableName, 1) }) t.Run("loads a saved keyRing if the password is correct", func(t *testing.T) { defer reset() - require.NoError(t, keyStore.Unlock(cltest.Password)) - require.NoError(t, keyStore.ExportedSave()) + ctx := testutils.Context(t) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) + require.NoError(t, keyStore.ExportedSave(ctx)) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) }) } diff --git a/core/services/keystore/mocks/cosmos.go b/core/services/keystore/mocks/cosmos.go index 40ba12d15d7..36d1daec524 100644 --- a/core/services/keystore/mocks/cosmos.go +++ b/core/services/keystore/mocks/cosmos.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + cosmoskey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/cosmoskey" mock "github.com/stretchr/testify/mock" @@ -13,17 +15,17 @@ type Cosmos struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *Cosmos) Add(key cosmoskey.Key) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *Cosmos) Add(ctx context.Context, key cosmoskey.Key) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(cosmoskey.Key) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, cosmoskey.Key) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -31,9 +33,9 @@ func (_m *Cosmos) Add(key cosmoskey.Key) error { return r0 } -// Create provides a mock function with given fields: -func (_m *Cosmos) Create() (cosmoskey.Key, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *Cosmos) Create(ctx context.Context) (cosmoskey.Key, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -41,17 +43,17 @@ func (_m *Cosmos) Create() (cosmoskey.Key, error) { var r0 cosmoskey.Key var r1 error - if rf, ok := ret.Get(0).(func() (cosmoskey.Key, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (cosmoskey.Key, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() cosmoskey.Key); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) cosmoskey.Key); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(cosmoskey.Key) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -59,9 +61,9 @@ func (_m *Cosmos) Create() (cosmoskey.Key, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *Cosmos) Delete(id string) (cosmoskey.Key, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *Cosmos) Delete(ctx context.Context, id string) (cosmoskey.Key, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -69,17 +71,17 @@ func (_m *Cosmos) Delete(id string) (cosmoskey.Key, error) { var r0 cosmoskey.Key var r1 error - if rf, ok := ret.Get(0).(func(string) (cosmoskey.Key, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (cosmoskey.Key, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) cosmoskey.Key); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) cosmoskey.Key); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(cosmoskey.Key) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -87,17 +89,17 @@ func (_m *Cosmos) Delete(id string) (cosmoskey.Key, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *Cosmos) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *Cosmos) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -193,9 +195,9 @@ func (_m *Cosmos) GetAll() ([]cosmoskey.Key, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *Cosmos) Import(keyJSON []byte, password string) (cosmoskey.Key, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *Cosmos) Import(ctx context.Context, keyJSON []byte, password string) (cosmoskey.Key, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -203,17 +205,17 @@ func (_m *Cosmos) Import(keyJSON []byte, password string) (cosmoskey.Key, error) var r0 cosmoskey.Key var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (cosmoskey.Key, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (cosmoskey.Key, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) cosmoskey.Key); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) cosmoskey.Key); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(cosmoskey.Key) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/csa.go b/core/services/keystore/mocks/csa.go index ad5b25a27bd..ba0ce76e39a 100644 --- a/core/services/keystore/mocks/csa.go +++ b/core/services/keystore/mocks/csa.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + csakey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" mock "github.com/stretchr/testify/mock" @@ -13,17 +15,17 @@ type CSA struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *CSA) Add(key csakey.KeyV2) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *CSA) Add(ctx context.Context, key csakey.KeyV2) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(csakey.KeyV2) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, csakey.KeyV2) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -31,9 +33,9 @@ func (_m *CSA) Add(key csakey.KeyV2) error { return r0 } -// Create provides a mock function with given fields: -func (_m *CSA) Create() (csakey.KeyV2, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *CSA) Create(ctx context.Context) (csakey.KeyV2, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -41,17 +43,17 @@ func (_m *CSA) Create() (csakey.KeyV2, error) { var r0 csakey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func() (csakey.KeyV2, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (csakey.KeyV2, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() csakey.KeyV2); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) csakey.KeyV2); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(csakey.KeyV2) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -59,9 +61,9 @@ func (_m *CSA) Create() (csakey.KeyV2, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *CSA) Delete(id string) (csakey.KeyV2, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *CSA) Delete(ctx context.Context, id string) (csakey.KeyV2, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -69,17 +71,17 @@ func (_m *CSA) Delete(id string) (csakey.KeyV2, error) { var r0 csakey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func(string) (csakey.KeyV2, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (csakey.KeyV2, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) csakey.KeyV2); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) csakey.KeyV2); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(csakey.KeyV2) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -87,17 +89,17 @@ func (_m *CSA) Delete(id string) (csakey.KeyV2, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *CSA) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *CSA) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -193,9 +195,9 @@ func (_m *CSA) GetAll() ([]csakey.KeyV2, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *CSA) Import(keyJSON []byte, password string) (csakey.KeyV2, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *CSA) Import(ctx context.Context, keyJSON []byte, password string) (csakey.KeyV2, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -203,17 +205,17 @@ func (_m *CSA) Import(keyJSON []byte, password string) (csakey.KeyV2, error) { var r0 csakey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (csakey.KeyV2, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (csakey.KeyV2, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) csakey.KeyV2); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) csakey.KeyV2); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(csakey.KeyV2) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/dkg_encrypt.go b/core/services/keystore/mocks/dkg_encrypt.go index e7e52bada25..1dc17b61183 100644 --- a/core/services/keystore/mocks/dkg_encrypt.go +++ b/core/services/keystore/mocks/dkg_encrypt.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + dkgencryptkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/dkgencryptkey" mock "github.com/stretchr/testify/mock" @@ -13,17 +15,17 @@ type DKGEncrypt struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *DKGEncrypt) Add(key dkgencryptkey.Key) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *DKGEncrypt) Add(ctx context.Context, key dkgencryptkey.Key) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(dkgencryptkey.Key) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, dkgencryptkey.Key) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -31,9 +33,9 @@ func (_m *DKGEncrypt) Add(key dkgencryptkey.Key) error { return r0 } -// Create provides a mock function with given fields: -func (_m *DKGEncrypt) Create() (dkgencryptkey.Key, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *DKGEncrypt) Create(ctx context.Context) (dkgencryptkey.Key, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -41,17 +43,17 @@ func (_m *DKGEncrypt) Create() (dkgencryptkey.Key, error) { var r0 dkgencryptkey.Key var r1 error - if rf, ok := ret.Get(0).(func() (dkgencryptkey.Key, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (dkgencryptkey.Key, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() dkgencryptkey.Key); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) dkgencryptkey.Key); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(dkgencryptkey.Key) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -59,9 +61,9 @@ func (_m *DKGEncrypt) Create() (dkgencryptkey.Key, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *DKGEncrypt) Delete(id string) (dkgencryptkey.Key, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *DKGEncrypt) Delete(ctx context.Context, id string) (dkgencryptkey.Key, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -69,17 +71,17 @@ func (_m *DKGEncrypt) Delete(id string) (dkgencryptkey.Key, error) { var r0 dkgencryptkey.Key var r1 error - if rf, ok := ret.Get(0).(func(string) (dkgencryptkey.Key, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (dkgencryptkey.Key, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) dkgencryptkey.Key); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) dkgencryptkey.Key); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(dkgencryptkey.Key) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -87,17 +89,17 @@ func (_m *DKGEncrypt) Delete(id string) (dkgencryptkey.Key, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *DKGEncrypt) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *DKGEncrypt) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -193,9 +195,9 @@ func (_m *DKGEncrypt) GetAll() ([]dkgencryptkey.Key, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *DKGEncrypt) Import(keyJSON []byte, password string) (dkgencryptkey.Key, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *DKGEncrypt) Import(ctx context.Context, keyJSON []byte, password string) (dkgencryptkey.Key, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -203,17 +205,17 @@ func (_m *DKGEncrypt) Import(keyJSON []byte, password string) (dkgencryptkey.Key var r0 dkgencryptkey.Key var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (dkgencryptkey.Key, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (dkgencryptkey.Key, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) dkgencryptkey.Key); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) dkgencryptkey.Key); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(dkgencryptkey.Key) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/dkg_sign.go b/core/services/keystore/mocks/dkg_sign.go index e5c6434d90d..1ff71e2fc8d 100644 --- a/core/services/keystore/mocks/dkg_sign.go +++ b/core/services/keystore/mocks/dkg_sign.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + dkgsignkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/dkgsignkey" mock "github.com/stretchr/testify/mock" @@ -13,17 +15,17 @@ type DKGSign struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *DKGSign) Add(key dkgsignkey.Key) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *DKGSign) Add(ctx context.Context, key dkgsignkey.Key) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(dkgsignkey.Key) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, dkgsignkey.Key) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -31,9 +33,9 @@ func (_m *DKGSign) Add(key dkgsignkey.Key) error { return r0 } -// Create provides a mock function with given fields: -func (_m *DKGSign) Create() (dkgsignkey.Key, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *DKGSign) Create(ctx context.Context) (dkgsignkey.Key, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -41,17 +43,17 @@ func (_m *DKGSign) Create() (dkgsignkey.Key, error) { var r0 dkgsignkey.Key var r1 error - if rf, ok := ret.Get(0).(func() (dkgsignkey.Key, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (dkgsignkey.Key, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() dkgsignkey.Key); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) dkgsignkey.Key); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(dkgsignkey.Key) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -59,9 +61,9 @@ func (_m *DKGSign) Create() (dkgsignkey.Key, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *DKGSign) Delete(id string) (dkgsignkey.Key, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *DKGSign) Delete(ctx context.Context, id string) (dkgsignkey.Key, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -69,17 +71,17 @@ func (_m *DKGSign) Delete(id string) (dkgsignkey.Key, error) { var r0 dkgsignkey.Key var r1 error - if rf, ok := ret.Get(0).(func(string) (dkgsignkey.Key, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (dkgsignkey.Key, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) dkgsignkey.Key); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) dkgsignkey.Key); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(dkgsignkey.Key) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -87,17 +89,17 @@ func (_m *DKGSign) Delete(id string) (dkgsignkey.Key, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *DKGSign) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *DKGSign) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -193,9 +195,9 @@ func (_m *DKGSign) GetAll() ([]dkgsignkey.Key, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *DKGSign) Import(keyJSON []byte, password string) (dkgsignkey.Key, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *DKGSign) Import(ctx context.Context, keyJSON []byte, password string) (dkgsignkey.Key, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -203,17 +205,17 @@ func (_m *DKGSign) Import(keyJSON []byte, password string) (dkgsignkey.Key, erro var r0 dkgsignkey.Key var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (dkgsignkey.Key, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (dkgsignkey.Key, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) dkgsignkey.Key); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) dkgsignkey.Key); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(dkgsignkey.Key) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/eth.go b/core/services/keystore/mocks/eth.go index a5dd612d9e5..591477ce6d3 100644 --- a/core/services/keystore/mocks/eth.go +++ b/core/services/keystore/mocks/eth.go @@ -12,8 +12,6 @@ import ( mock "github.com/stretchr/testify/mock" - pg "github.com/smartcontractkit/chainlink/v2/core/services/pg" - types "github.com/ethereum/go-ethereum/core/types" ) @@ -22,24 +20,17 @@ type Eth struct { mock.Mock } -// Add provides a mock function with given fields: ctx, address, chainID, qopts -func (_m *Eth) Add(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { - _va := make([]interface{}, len(qopts)) - for _i := range qopts { - _va[_i] = qopts[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, address, chainID) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) +// Add provides a mock function with given fields: ctx, address, chainID +func (_m *Eth) Add(ctx context.Context, address common.Address, chainID *big.Int) error { + ret := _m.Called(ctx, address, chainID) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int, ...pg.QOpt) error); ok { - r0 = rf(ctx, address, chainID, qopts...) + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) error); ok { + r0 = rf(ctx, address, chainID) } else { r0 = ret.Error(0) } @@ -128,24 +119,17 @@ func (_m *Eth) Delete(ctx context.Context, id string) (ethkey.KeyV2, error) { return r0, r1 } -// Disable provides a mock function with given fields: ctx, address, chainID, qopts -func (_m *Eth) Disable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { - _va := make([]interface{}, len(qopts)) - for _i := range qopts { - _va[_i] = qopts[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, address, chainID) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) +// Disable provides a mock function with given fields: ctx, address, chainID +func (_m *Eth) Disable(ctx context.Context, address common.Address, chainID *big.Int) error { + ret := _m.Called(ctx, address, chainID) if len(ret) == 0 { panic("no return value specified for Disable") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int, ...pg.QOpt) error); ok { - r0 = rf(ctx, address, chainID, qopts...) + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) error); ok { + r0 = rf(ctx, address, chainID) } else { r0 = ret.Error(0) } @@ -153,24 +137,17 @@ func (_m *Eth) Disable(ctx context.Context, address common.Address, chainID *big return r0 } -// Enable provides a mock function with given fields: ctx, address, chainID, qopts -func (_m *Eth) Enable(ctx context.Context, address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { - _va := make([]interface{}, len(qopts)) - for _i := range qopts { - _va[_i] = qopts[_i] - } - var _ca []interface{} - _ca = append(_ca, ctx, address, chainID) - _ca = append(_ca, _va...) - ret := _m.Called(_ca...) +// Enable provides a mock function with given fields: ctx, address, chainID +func (_m *Eth) Enable(ctx context.Context, address common.Address, chainID *big.Int) error { + ret := _m.Called(ctx, address, chainID) if len(ret) == 0 { panic("no return value specified for Enable") } var r0 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int, ...pg.QOpt) error); ok { - r0 = rf(ctx, address, chainID, qopts...) + if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) error); ok { + r0 = rf(ctx, address, chainID) } else { r0 = ret.Error(0) } diff --git a/core/services/keystore/mocks/master.go b/core/services/keystore/mocks/master.go index 3025f5b103a..4662635cb00 100644 --- a/core/services/keystore/mocks/master.go +++ b/core/services/keystore/mocks/master.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + keystore "github.com/smartcontractkit/chainlink/v2/core/services/keystore" mock "github.com/stretchr/testify/mock" ) @@ -112,9 +114,9 @@ func (_m *Master) Eth() keystore.Eth { return r0 } -// IsEmpty provides a mock function with given fields: -func (_m *Master) IsEmpty() (bool, error) { - ret := _m.Called() +// IsEmpty provides a mock function with given fields: ctx +func (_m *Master) IsEmpty(ctx context.Context) (bool, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for IsEmpty") @@ -122,17 +124,17 @@ func (_m *Master) IsEmpty() (bool, error) { var r0 bool var r1 error - if rf, ok := ret.Get(0).(func() (bool, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (bool, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() bool); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) bool); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(bool) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -240,17 +242,17 @@ func (_m *Master) StarkNet() keystore.StarkNet { return r0 } -// Unlock provides a mock function with given fields: password -func (_m *Master) Unlock(password string) error { - ret := _m.Called(password) +// Unlock provides a mock function with given fields: ctx, password +func (_m *Master) Unlock(ctx context.Context, password string) error { + ret := _m.Called(ctx, password) if len(ret) == 0 { panic("no return value specified for Unlock") } var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(password) + if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { + r0 = rf(ctx, password) } else { r0 = ret.Error(0) } diff --git a/core/services/keystore/mocks/ocr.go b/core/services/keystore/mocks/ocr.go index e1c4d588330..b29f07f03f4 100644 --- a/core/services/keystore/mocks/ocr.go +++ b/core/services/keystore/mocks/ocr.go @@ -3,8 +3,11 @@ package mocks import ( - ocrkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocrkey" + context "context" + mock "github.com/stretchr/testify/mock" + + ocrkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocrkey" ) // OCR is an autogenerated mock type for the OCR type @@ -12,17 +15,17 @@ type OCR struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *OCR) Add(key ocrkey.KeyV2) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *OCR) Add(ctx context.Context, key ocrkey.KeyV2) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(ocrkey.KeyV2) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, ocrkey.KeyV2) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -30,9 +33,9 @@ func (_m *OCR) Add(key ocrkey.KeyV2) error { return r0 } -// Create provides a mock function with given fields: -func (_m *OCR) Create() (ocrkey.KeyV2, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *OCR) Create(ctx context.Context) (ocrkey.KeyV2, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -40,17 +43,17 @@ func (_m *OCR) Create() (ocrkey.KeyV2, error) { var r0 ocrkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func() (ocrkey.KeyV2, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (ocrkey.KeyV2, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() ocrkey.KeyV2); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) ocrkey.KeyV2); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(ocrkey.KeyV2) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -58,9 +61,9 @@ func (_m *OCR) Create() (ocrkey.KeyV2, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *OCR) Delete(id string) (ocrkey.KeyV2, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *OCR) Delete(ctx context.Context, id string) (ocrkey.KeyV2, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -68,17 +71,17 @@ func (_m *OCR) Delete(id string) (ocrkey.KeyV2, error) { var r0 ocrkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func(string) (ocrkey.KeyV2, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (ocrkey.KeyV2, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) ocrkey.KeyV2); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) ocrkey.KeyV2); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(ocrkey.KeyV2) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -86,17 +89,17 @@ func (_m *OCR) Delete(id string) (ocrkey.KeyV2, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *OCR) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *OCR) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -192,9 +195,9 @@ func (_m *OCR) GetAll() ([]ocrkey.KeyV2, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *OCR) Import(keyJSON []byte, password string) (ocrkey.KeyV2, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *OCR) Import(ctx context.Context, keyJSON []byte, password string) (ocrkey.KeyV2, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -202,17 +205,17 @@ func (_m *OCR) Import(keyJSON []byte, password string) (ocrkey.KeyV2, error) { var r0 ocrkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (ocrkey.KeyV2, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (ocrkey.KeyV2, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) ocrkey.KeyV2); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) ocrkey.KeyV2); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(ocrkey.KeyV2) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/ocr2.go b/core/services/keystore/mocks/ocr2.go index d44e739deed..13f0c65b9d1 100644 --- a/core/services/keystore/mocks/ocr2.go +++ b/core/services/keystore/mocks/ocr2.go @@ -3,6 +3,8 @@ package mocks import ( + context "context" + chaintype "github.com/smartcontractkit/chainlink/v2/core/services/keystore/chaintype" mock "github.com/stretchr/testify/mock" @@ -15,17 +17,17 @@ type OCR2 struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *OCR2) Add(key ocr2key.KeyBundle) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *OCR2) Add(ctx context.Context, key ocr2key.KeyBundle) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(ocr2key.KeyBundle) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, ocr2key.KeyBundle) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -33,9 +35,9 @@ func (_m *OCR2) Add(key ocr2key.KeyBundle) error { return r0 } -// Create provides a mock function with given fields: _a0 -func (_m *OCR2) Create(_a0 chaintype.ChainType) (ocr2key.KeyBundle, error) { - ret := _m.Called(_a0) +// Create provides a mock function with given fields: _a0, _a1 +func (_m *OCR2) Create(_a0 context.Context, _a1 chaintype.ChainType) (ocr2key.KeyBundle, error) { + ret := _m.Called(_a0, _a1) if len(ret) == 0 { panic("no return value specified for Create") @@ -43,19 +45,19 @@ func (_m *OCR2) Create(_a0 chaintype.ChainType) (ocr2key.KeyBundle, error) { var r0 ocr2key.KeyBundle var r1 error - if rf, ok := ret.Get(0).(func(chaintype.ChainType) (ocr2key.KeyBundle, error)); ok { - return rf(_a0) + if rf, ok := ret.Get(0).(func(context.Context, chaintype.ChainType) (ocr2key.KeyBundle, error)); ok { + return rf(_a0, _a1) } - if rf, ok := ret.Get(0).(func(chaintype.ChainType) ocr2key.KeyBundle); ok { - r0 = rf(_a0) + if rf, ok := ret.Get(0).(func(context.Context, chaintype.ChainType) ocr2key.KeyBundle); ok { + r0 = rf(_a0, _a1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(ocr2key.KeyBundle) } } - if rf, ok := ret.Get(1).(func(chaintype.ChainType) error); ok { - r1 = rf(_a0) + if rf, ok := ret.Get(1).(func(context.Context, chaintype.ChainType) error); ok { + r1 = rf(_a0, _a1) } else { r1 = ret.Error(1) } @@ -63,17 +65,17 @@ func (_m *OCR2) Create(_a0 chaintype.ChainType) (ocr2key.KeyBundle, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *OCR2) Delete(id string) error { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *OCR2) Delete(ctx context.Context, id string) error { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") } var r0 error - if rf, ok := ret.Get(0).(func(string) error); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { + r0 = rf(ctx, id) } else { r0 = ret.Error(0) } @@ -81,13 +83,14 @@ func (_m *OCR2) Delete(id string) error { return r0 } -// EnsureKeys provides a mock function with given fields: enabledChains -func (_m *OCR2) EnsureKeys(enabledChains ...chaintype.ChainType) error { +// EnsureKeys provides a mock function with given fields: ctx, enabledChains +func (_m *OCR2) EnsureKeys(ctx context.Context, enabledChains ...chaintype.ChainType) error { _va := make([]interface{}, len(enabledChains)) for _i := range enabledChains { _va[_i] = enabledChains[_i] } var _ca []interface{} + _ca = append(_ca, ctx) _ca = append(_ca, _va...) ret := _m.Called(_ca...) @@ -96,8 +99,8 @@ func (_m *OCR2) EnsureKeys(enabledChains ...chaintype.ChainType) error { } var r0 error - if rf, ok := ret.Get(0).(func(...chaintype.ChainType) error); ok { - r0 = rf(enabledChains...) + if rf, ok := ret.Get(0).(func(context.Context, ...chaintype.ChainType) error); ok { + r0 = rf(ctx, enabledChains...) } else { r0 = ret.Error(0) } @@ -225,9 +228,9 @@ func (_m *OCR2) GetAllOfType(_a0 chaintype.ChainType) ([]ocr2key.KeyBundle, erro return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *OCR2) Import(keyJSON []byte, password string) (ocr2key.KeyBundle, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *OCR2) Import(ctx context.Context, keyJSON []byte, password string) (ocr2key.KeyBundle, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -235,19 +238,19 @@ func (_m *OCR2) Import(keyJSON []byte, password string) (ocr2key.KeyBundle, erro var r0 ocr2key.KeyBundle var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (ocr2key.KeyBundle, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (ocr2key.KeyBundle, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) ocr2key.KeyBundle); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) ocr2key.KeyBundle); ok { + r0 = rf(ctx, keyJSON, password) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(ocr2key.KeyBundle) } } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/p2p.go b/core/services/keystore/mocks/p2p.go index fa2a1b6ceeb..7e480c5d96f 100644 --- a/core/services/keystore/mocks/p2p.go +++ b/core/services/keystore/mocks/p2p.go @@ -3,8 +3,11 @@ package mocks import ( - p2pkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/p2pkey" + context "context" + mock "github.com/stretchr/testify/mock" + + p2pkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/p2pkey" ) // P2P is an autogenerated mock type for the P2P type @@ -12,17 +15,17 @@ type P2P struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *P2P) Add(key p2pkey.KeyV2) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *P2P) Add(ctx context.Context, key p2pkey.KeyV2) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(p2pkey.KeyV2) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, p2pkey.KeyV2) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -30,9 +33,9 @@ func (_m *P2P) Add(key p2pkey.KeyV2) error { return r0 } -// Create provides a mock function with given fields: -func (_m *P2P) Create() (p2pkey.KeyV2, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *P2P) Create(ctx context.Context) (p2pkey.KeyV2, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -40,17 +43,17 @@ func (_m *P2P) Create() (p2pkey.KeyV2, error) { var r0 p2pkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func() (p2pkey.KeyV2, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (p2pkey.KeyV2, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() p2pkey.KeyV2); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) p2pkey.KeyV2); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(p2pkey.KeyV2) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -58,9 +61,9 @@ func (_m *P2P) Create() (p2pkey.KeyV2, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *P2P) Delete(id p2pkey.PeerID) (p2pkey.KeyV2, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *P2P) Delete(ctx context.Context, id p2pkey.PeerID) (p2pkey.KeyV2, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -68,17 +71,17 @@ func (_m *P2P) Delete(id p2pkey.PeerID) (p2pkey.KeyV2, error) { var r0 p2pkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func(p2pkey.PeerID) (p2pkey.KeyV2, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, p2pkey.PeerID) (p2pkey.KeyV2, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(p2pkey.PeerID) p2pkey.KeyV2); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, p2pkey.PeerID) p2pkey.KeyV2); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(p2pkey.KeyV2) } - if rf, ok := ret.Get(1).(func(p2pkey.PeerID) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, p2pkey.PeerID) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -86,17 +89,17 @@ func (_m *P2P) Delete(id p2pkey.PeerID) (p2pkey.KeyV2, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *P2P) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *P2P) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -220,9 +223,9 @@ func (_m *P2P) GetOrFirst(id p2pkey.PeerID) (p2pkey.KeyV2, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *P2P) Import(keyJSON []byte, password string) (p2pkey.KeyV2, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *P2P) Import(ctx context.Context, keyJSON []byte, password string) (p2pkey.KeyV2, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -230,17 +233,17 @@ func (_m *P2P) Import(keyJSON []byte, password string) (p2pkey.KeyV2, error) { var r0 p2pkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (p2pkey.KeyV2, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (p2pkey.KeyV2, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) p2pkey.KeyV2); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) p2pkey.KeyV2); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(p2pkey.KeyV2) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/solana.go b/core/services/keystore/mocks/solana.go index c2cc4139bab..7c4593ac5a3 100644 --- a/core/services/keystore/mocks/solana.go +++ b/core/services/keystore/mocks/solana.go @@ -15,17 +15,17 @@ type Solana struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *Solana) Add(key solkey.Key) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *Solana) Add(ctx context.Context, key solkey.Key) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(solkey.Key) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, solkey.Key) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -33,9 +33,9 @@ func (_m *Solana) Add(key solkey.Key) error { return r0 } -// Create provides a mock function with given fields: -func (_m *Solana) Create() (solkey.Key, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *Solana) Create(ctx context.Context) (solkey.Key, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -43,17 +43,17 @@ func (_m *Solana) Create() (solkey.Key, error) { var r0 solkey.Key var r1 error - if rf, ok := ret.Get(0).(func() (solkey.Key, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (solkey.Key, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() solkey.Key); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) solkey.Key); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(solkey.Key) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -61,9 +61,9 @@ func (_m *Solana) Create() (solkey.Key, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *Solana) Delete(id string) (solkey.Key, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *Solana) Delete(ctx context.Context, id string) (solkey.Key, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -71,17 +71,17 @@ func (_m *Solana) Delete(id string) (solkey.Key, error) { var r0 solkey.Key var r1 error - if rf, ok := ret.Get(0).(func(string) (solkey.Key, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (solkey.Key, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) solkey.Key); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) solkey.Key); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(solkey.Key) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -89,17 +89,17 @@ func (_m *Solana) Delete(id string) (solkey.Key, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *Solana) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *Solana) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -195,9 +195,9 @@ func (_m *Solana) GetAll() ([]solkey.Key, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *Solana) Import(keyJSON []byte, password string) (solkey.Key, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *Solana) Import(ctx context.Context, keyJSON []byte, password string) (solkey.Key, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -205,17 +205,17 @@ func (_m *Solana) Import(keyJSON []byte, password string) (solkey.Key, error) { var r0 solkey.Key var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (solkey.Key, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (solkey.Key, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) solkey.Key); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) solkey.Key); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(solkey.Key) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/starknet.go b/core/services/keystore/mocks/starknet.go index c3d74a8389f..61fb89418b4 100644 --- a/core/services/keystore/mocks/starknet.go +++ b/core/services/keystore/mocks/starknet.go @@ -3,8 +3,11 @@ package mocks import ( - starkkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/starkkey" + context "context" + mock "github.com/stretchr/testify/mock" + + starkkey "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/starkkey" ) // StarkNet is an autogenerated mock type for the StarkNet type @@ -12,17 +15,17 @@ type StarkNet struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *StarkNet) Add(key starkkey.Key) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *StarkNet) Add(ctx context.Context, key starkkey.Key) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(starkkey.Key) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, starkkey.Key) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -30,9 +33,9 @@ func (_m *StarkNet) Add(key starkkey.Key) error { return r0 } -// Create provides a mock function with given fields: -func (_m *StarkNet) Create() (starkkey.Key, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *StarkNet) Create(ctx context.Context) (starkkey.Key, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -40,17 +43,17 @@ func (_m *StarkNet) Create() (starkkey.Key, error) { var r0 starkkey.Key var r1 error - if rf, ok := ret.Get(0).(func() (starkkey.Key, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (starkkey.Key, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() starkkey.Key); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) starkkey.Key); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(starkkey.Key) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -58,9 +61,9 @@ func (_m *StarkNet) Create() (starkkey.Key, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *StarkNet) Delete(id string) (starkkey.Key, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *StarkNet) Delete(ctx context.Context, id string) (starkkey.Key, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -68,17 +71,17 @@ func (_m *StarkNet) Delete(id string) (starkkey.Key, error) { var r0 starkkey.Key var r1 error - if rf, ok := ret.Get(0).(func(string) (starkkey.Key, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (starkkey.Key, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) starkkey.Key); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) starkkey.Key); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(starkkey.Key) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -86,17 +89,17 @@ func (_m *StarkNet) Delete(id string) (starkkey.Key, error) { return r0, r1 } -// EnsureKey provides a mock function with given fields: -func (_m *StarkNet) EnsureKey() error { - ret := _m.Called() +// EnsureKey provides a mock function with given fields: ctx +func (_m *StarkNet) EnsureKey(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for EnsureKey") } var r0 error - if rf, ok := ret.Get(0).(func() error); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) error); ok { + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -192,9 +195,9 @@ func (_m *StarkNet) GetAll() ([]starkkey.Key, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *StarkNet) Import(keyJSON []byte, password string) (starkkey.Key, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *StarkNet) Import(ctx context.Context, keyJSON []byte, password string) (starkkey.Key, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -202,17 +205,17 @@ func (_m *StarkNet) Import(keyJSON []byte, password string) (starkkey.Key, error var r0 starkkey.Key var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (starkkey.Key, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (starkkey.Key, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) starkkey.Key); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) starkkey.Key); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(starkkey.Key) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/mocks/vrf.go b/core/services/keystore/mocks/vrf.go index ab730ebec67..acd6e02d434 100644 --- a/core/services/keystore/mocks/vrf.go +++ b/core/services/keystore/mocks/vrf.go @@ -3,6 +3,7 @@ package mocks import ( + context "context" big "math/big" mock "github.com/stretchr/testify/mock" @@ -15,17 +16,17 @@ type VRF struct { mock.Mock } -// Add provides a mock function with given fields: key -func (_m *VRF) Add(key vrfkey.KeyV2) error { - ret := _m.Called(key) +// Add provides a mock function with given fields: ctx, key +func (_m *VRF) Add(ctx context.Context, key vrfkey.KeyV2) error { + ret := _m.Called(ctx, key) if len(ret) == 0 { panic("no return value specified for Add") } var r0 error - if rf, ok := ret.Get(0).(func(vrfkey.KeyV2) error); ok { - r0 = rf(key) + if rf, ok := ret.Get(0).(func(context.Context, vrfkey.KeyV2) error); ok { + r0 = rf(ctx, key) } else { r0 = ret.Error(0) } @@ -33,9 +34,9 @@ func (_m *VRF) Add(key vrfkey.KeyV2) error { return r0 } -// Create provides a mock function with given fields: -func (_m *VRF) Create() (vrfkey.KeyV2, error) { - ret := _m.Called() +// Create provides a mock function with given fields: ctx +func (_m *VRF) Create(ctx context.Context) (vrfkey.KeyV2, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Create") @@ -43,17 +44,17 @@ func (_m *VRF) Create() (vrfkey.KeyV2, error) { var r0 vrfkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func() (vrfkey.KeyV2, error)); ok { - return rf() + if rf, ok := ret.Get(0).(func(context.Context) (vrfkey.KeyV2, error)); ok { + return rf(ctx) } - if rf, ok := ret.Get(0).(func() vrfkey.KeyV2); ok { - r0 = rf() + if rf, ok := ret.Get(0).(func(context.Context) vrfkey.KeyV2); ok { + r0 = rf(ctx) } else { r0 = ret.Get(0).(vrfkey.KeyV2) } - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -61,9 +62,9 @@ func (_m *VRF) Create() (vrfkey.KeyV2, error) { return r0, r1 } -// Delete provides a mock function with given fields: id -func (_m *VRF) Delete(id string) (vrfkey.KeyV2, error) { - ret := _m.Called(id) +// Delete provides a mock function with given fields: ctx, id +func (_m *VRF) Delete(ctx context.Context, id string) (vrfkey.KeyV2, error) { + ret := _m.Called(ctx, id) if len(ret) == 0 { panic("no return value specified for Delete") @@ -71,17 +72,17 @@ func (_m *VRF) Delete(id string) (vrfkey.KeyV2, error) { var r0 vrfkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func(string) (vrfkey.KeyV2, error)); ok { - return rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) (vrfkey.KeyV2, error)); ok { + return rf(ctx, id) } - if rf, ok := ret.Get(0).(func(string) vrfkey.KeyV2); ok { - r0 = rf(id) + if rf, ok := ret.Get(0).(func(context.Context, string) vrfkey.KeyV2); ok { + r0 = rf(ctx, id) } else { r0 = ret.Get(0).(vrfkey.KeyV2) } - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) } else { r1 = ret.Error(1) } @@ -205,9 +206,9 @@ func (_m *VRF) GetAll() ([]vrfkey.KeyV2, error) { return r0, r1 } -// Import provides a mock function with given fields: keyJSON, password -func (_m *VRF) Import(keyJSON []byte, password string) (vrfkey.KeyV2, error) { - ret := _m.Called(keyJSON, password) +// Import provides a mock function with given fields: ctx, keyJSON, password +func (_m *VRF) Import(ctx context.Context, keyJSON []byte, password string) (vrfkey.KeyV2, error) { + ret := _m.Called(ctx, keyJSON, password) if len(ret) == 0 { panic("no return value specified for Import") @@ -215,17 +216,17 @@ func (_m *VRF) Import(keyJSON []byte, password string) (vrfkey.KeyV2, error) { var r0 vrfkey.KeyV2 var r1 error - if rf, ok := ret.Get(0).(func([]byte, string) (vrfkey.KeyV2, error)); ok { - return rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) (vrfkey.KeyV2, error)); ok { + return rf(ctx, keyJSON, password) } - if rf, ok := ret.Get(0).(func([]byte, string) vrfkey.KeyV2); ok { - r0 = rf(keyJSON, password) + if rf, ok := ret.Get(0).(func(context.Context, []byte, string) vrfkey.KeyV2); ok { + r0 = rf(ctx, keyJSON, password) } else { r0 = ret.Get(0).(vrfkey.KeyV2) } - if rf, ok := ret.Get(1).(func([]byte, string) error); ok { - r1 = rf(keyJSON, password) + if rf, ok := ret.Get(1).(func(context.Context, []byte, string) error); ok { + r1 = rf(ctx, keyJSON, password) } else { r1 = ret.Error(1) } diff --git a/core/services/keystore/ocr.go b/core/services/keystore/ocr.go index dda5bfa13c3..7cacbbfff97 100644 --- a/core/services/keystore/ocr.go +++ b/core/services/keystore/ocr.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "github.com/pkg/errors" @@ -13,12 +14,12 @@ import ( type OCR interface { Get(id string) (ocrkey.KeyV2, error) GetAll() ([]ocrkey.KeyV2, error) - Create() (ocrkey.KeyV2, error) - Add(key ocrkey.KeyV2) error - Delete(id string) (ocrkey.KeyV2, error) - Import(keyJSON []byte, password string) (ocrkey.KeyV2, error) + Create(ctx context.Context) (ocrkey.KeyV2, error) + Add(ctx context.Context, key ocrkey.KeyV2) error + Delete(ctx context.Context, id string) (ocrkey.KeyV2, error) + Import(ctx context.Context, keyJSON []byte, password string) (ocrkey.KeyV2, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error } // KeyNotFoundError is returned when we don't find a requested key @@ -64,7 +65,7 @@ func (ks *ocr) GetAll() (keys []ocrkey.KeyV2, _ error) { return keys, nil } -func (ks *ocr) Create() (ocrkey.KeyV2, error) { +func (ks *ocr) Create(ctx context.Context) (ocrkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -74,10 +75,10 @@ func (ks *ocr) Create() (ocrkey.KeyV2, error) { if err != nil { return ocrkey.KeyV2{}, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *ocr) Add(key ocrkey.KeyV2) error { +func (ks *ocr) Add(ctx context.Context, key ocrkey.KeyV2) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -86,10 +87,10 @@ func (ks *ocr) Add(key ocrkey.KeyV2) error { if _, found := ks.keyRing.OCR[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *ocr) Delete(id string) (ocrkey.KeyV2, error) { +func (ks *ocr) Delete(ctx context.Context, id string) (ocrkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -99,11 +100,11 @@ func (ks *ocr) Delete(id string) (ocrkey.KeyV2, error) { if err != nil { return ocrkey.KeyV2{}, err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return key, err } -func (ks *ocr) Import(keyJSON []byte, password string) (ocrkey.KeyV2, error) { +func (ks *ocr) Import(ctx context.Context, keyJSON []byte, password string) (ocrkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -116,7 +117,7 @@ func (ks *ocr) Import(keyJSON []byte, password string) (ocrkey.KeyV2, error) { if _, found := ks.keyRing.OCR[key.ID()]; found { return ocrkey.KeyV2{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *ocr) Export(id string, password string) ([]byte, error) { @@ -133,7 +134,7 @@ func (ks *ocr) Export(id string, password string) ([]byte, error) { } // EnsureKey verifies whether the OCR key has been seeded, if not, it creates it. -func (ks *ocr) EnsureKey() error { +func (ks *ocr) EnsureKey(ctx context.Context) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -151,7 +152,7 @@ func (ks *ocr) EnsureKey() error { ks.logger.Infof("Created OCR key with ID %s", key.ID()) - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } func (ks *ocr) getByID(id string) (ocrkey.KeyV2, error) { diff --git a/core/services/keystore/ocr2.go b/core/services/keystore/ocr2.go index a6460bf1ae5..4edbe2ba741 100644 --- a/core/services/keystore/ocr2.go +++ b/core/services/keystore/ocr2.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "github.com/pkg/errors" @@ -15,12 +16,12 @@ type OCR2 interface { Get(id string) (ocr2key.KeyBundle, error) GetAll() ([]ocr2key.KeyBundle, error) GetAllOfType(chaintype.ChainType) ([]ocr2key.KeyBundle, error) - Create(chaintype.ChainType) (ocr2key.KeyBundle, error) - Add(key ocr2key.KeyBundle) error - Delete(id string) error - Import(keyJSON []byte, password string) (ocr2key.KeyBundle, error) + Create(context.Context, chaintype.ChainType) (ocr2key.KeyBundle, error) + Add(ctx context.Context, key ocr2key.KeyBundle) error + Delete(ctx context.Context, id string) error + Import(ctx context.Context, keyJSON []byte, password string) (ocr2key.KeyBundle, error) Export(id string, password string) ([]byte, error) - EnsureKeys(enabledChains ...chaintype.ChainType) error + EnsureKeys(ctx context.Context, enabledChains ...chaintype.ChainType) error } type ocr2 struct { @@ -67,16 +68,16 @@ func (ks ocr2) GetAllOfType(chainType chaintype.ChainType) ([]ocr2key.KeyBundle, return ks.getAllOfType(chainType) } -func (ks ocr2) Create(chainType chaintype.ChainType) (ocr2key.KeyBundle, error) { +func (ks ocr2) Create(ctx context.Context, chainType chaintype.ChainType) (ocr2key.KeyBundle, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { return nil, ErrLocked } - return ks.create(chainType) + return ks.create(ctx, chainType) } -func (ks ocr2) Add(key ocr2key.KeyBundle) error { +func (ks ocr2) Add(ctx context.Context, key ocr2key.KeyBundle) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -85,10 +86,10 @@ func (ks ocr2) Add(key ocr2key.KeyBundle) error { if _, found := ks.keyRing.OCR2[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks ocr2) Delete(id string) error { +func (ks ocr2) Delete(ctx context.Context, id string) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -98,11 +99,11 @@ func (ks ocr2) Delete(id string) error { if err != nil { return err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return err } -func (ks ocr2) Import(keyJSON []byte, password string) (ocr2key.KeyBundle, error) { +func (ks ocr2) Import(ctx context.Context, keyJSON []byte, password string) (ocr2key.KeyBundle, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -115,7 +116,7 @@ func (ks ocr2) Import(keyJSON []byte, password string) (ocr2key.KeyBundle, error if _, found := ks.keyRing.OCR[key.ID()]; found { return nil, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks ocr2) Export(id string, password string) ([]byte, error) { @@ -131,7 +132,7 @@ func (ks ocr2) Export(id string, password string) ([]byte, error) { return ocr2key.ToEncryptedJSON(key, password, ks.scryptParams) } -func (ks ocr2) EnsureKeys(enabledChains ...chaintype.ChainType) error { +func (ks ocr2) EnsureKeys(ctx context.Context, enabledChains ...chaintype.ChainType) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -148,7 +149,7 @@ func (ks ocr2) EnsureKeys(enabledChains ...chaintype.ChainType) error { continue } - created, err := ks.create(chainType) + created, err := ks.create(ctx, chainType) if err != nil { return err } @@ -177,7 +178,7 @@ func (ks ocr2) getAllOfType(chainType chaintype.ChainType) ([]ocr2key.KeyBundle, return keys, nil } -func (ks ocr2) create(chainType chaintype.ChainType) (ocr2key.KeyBundle, error) { +func (ks ocr2) create(ctx context.Context, chainType chaintype.ChainType) (ocr2key.KeyBundle, error) { if !chaintype.IsSupportedChainType(chainType) { return nil, chaintype.NewErrInvalidChainType(chainType) } @@ -185,5 +186,5 @@ func (ks ocr2) create(chainType chaintype.ChainType) (ocr2key.KeyBundle, error) if err != nil { return nil, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } diff --git a/core/services/keystore/ocr2_test.go b/core/services/keystore/ocr2_test.go index 9223538a766..f2c8715ab4f 100644 --- a/core/services/keystore/ocr2_test.go +++ b/core/services/keystore/ocr2_test.go @@ -1,13 +1,14 @@ package keystore_test import ( + "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/chaintype" @@ -16,15 +17,15 @@ import ( func Test_OCR2KeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.OCR2() reset := func() { + ctx := context.Background() // Executed on cleanup _, err := db.Exec("DELETE FROM encrypted_key_rings") require.NoError(t, err) keyStore.ResetXXXTestOnly() - err = keyStore.Unlock(cltest.Password) + err = keyStore.Unlock(ctx, cltest.Password) require.NoError(t, err) } @@ -43,9 +44,10 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { t.Run("creates a key with valid type", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) // lopp through different chain types for _, chain := range chaintype.SupportedChainTypes { - key, err := ks.Create(chain) + key, err := ks.Create(ctx, chain) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -55,6 +57,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { t.Run("gets keys by type", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) created := map[chaintype.ChainType]bool{} for _, chain := range chaintype.SupportedChainTypes { @@ -64,7 +67,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { require.NoError(t, err) require.Len(t, keys, 0) - _, err = ks.Create(chain) + _, err = ks.Create(ctx, chain) require.NoError(t, err) created[chain] = true @@ -83,26 +86,28 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { t.Run("errors when creating a key with an invalid type", func(t *testing.T) { defer reset() - _, err := ks.Create("foobar") + ctx := testutils.Context(t) + _, err := ks.Create(ctx, "foobar") require.Error(t, err) }) t.Run("imports and exports a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) for _, chain := range chaintype.SupportedChainTypes { - key, err := ks.Create(chain) + key, err := ks.Create(ctx, chain) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) _, err = ks.Export("non-existent", cltest.Password) assert.Error(t, err) - err = ks.Delete(key.ID()) + err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) - _, err = ks.Import([]byte(""), cltest.Password) + _, err = ks.Import(ctx, []byte(""), cltest.Password) assert.Error(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -114,19 +119,20 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) for _, chain := range chaintype.SupportedChainTypes { newKey, err := ocr2key.New(chain) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - err = ks.Delete(newKey.ID()) + err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) - err = ks.Delete(newKey.ID()) + err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -138,14 +144,15 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { t.Run("ensures key", func(t *testing.T) { defer reset() - err := ks.EnsureKeys(chaintype.SupportedChainTypes...) + ctx := testutils.Context(t) + err := ks.EnsureKeys(ctx, chaintype.SupportedChainTypes...) assert.NoError(t, err) keys, err := ks.GetAll() assert.NoError(t, err) require.Equal(t, len(chaintype.SupportedChainTypes), len(keys)) - err = ks.EnsureKeys(chaintype.SupportedChainTypes...) + err = ks.EnsureKeys(ctx, chaintype.SupportedChainTypes...) assert.NoError(t, err) // loop through different supported chain types @@ -158,7 +165,8 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { t.Run("ensures key only for enabled chains", func(t *testing.T) { defer reset() - err := ks.EnsureKeys(chaintype.EVM) + ctx := testutils.Context(t) + err := ks.EnsureKeys(ctx, chaintype.EVM) assert.NoError(t, err) keys, err := ks.GetAll() @@ -166,7 +174,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { require.Equal(t, 1, len(keys)) require.Equal(t, keys[0].ChainType(), chaintype.EVM) - err = ks.EnsureKeys(chaintype.Cosmos) + err = ks.EnsureKeys(ctx, chaintype.Cosmos) assert.NoError(t, err) keys, err = ks.GetAll() @@ -178,7 +186,7 @@ func Test_OCR2KeyStore_E2E(t *testing.T) { require.Equal(t, 1, len(cosmosKeys)) require.Equal(t, cosmosKeys[0].ChainType(), chaintype.Cosmos) - err = ks.EnsureKeys(chaintype.StarkNet) + err = ks.EnsureKeys(ctx, chaintype.StarkNet) assert.NoError(t, err) keys, err = ks.GetAll() diff --git a/core/services/keystore/ocr_test.go b/core/services/keystore/ocr_test.go index c65d576c452..b7a7b127f21 100644 --- a/core/services/keystore/ocr_test.go +++ b/core/services/keystore/ocr_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "testing" "github.com/stretchr/testify/assert" @@ -8,7 +9,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocrkey" @@ -16,14 +17,14 @@ import ( func Test_OCRKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.OCR() reset := func() { + ctx := context.Background() // Executed on cleaup require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -41,7 +42,8 @@ func Test_OCRKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -50,21 +52,22 @@ func Test_OCRKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) _, err = ks.Export("non-existent", cltest.Password) assert.Error(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) - _, err = ks.Import([]byte(""), cltest.Password) + _, err = ks.Import(ctx, []byte(""), cltest.Password) assert.Error(t, err) - _, err = ks.Import(exportJSON, cltest.Password) + _, err = ks.Import(ctx, exportJSON, cltest.Password) assert.Error(t, err) assert.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -74,18 +77,19 @@ func Test_OCRKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := ocrkey.NewV2() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) assert.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -96,9 +100,10 @@ func Test_OCRKeyStore_E2E(t *testing.T) { t.Run("ensures key", func(t *testing.T) { defer reset() - err := ks.EnsureKey() + ctx := testutils.Context(t) + err := ks.EnsureKey(ctx) require.NoError(t, err) - err = ks.EnsureKey() + err = ks.EnsureKey(ctx) require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) @@ -106,8 +111,9 @@ func Test_OCRKeyStore_E2E(t *testing.T) { }) t.Run("imports a key exported from a v1 keystore", func(t *testing.T) { + ctx := testutils.Context(t) exportedKey := `{"id":"7cfd89bbb018e4778a44fd61172e8834dd24b4a2baf61ead795143b117221c61","onChainSigningAddress":"ocrsad_0x2ed5b18b62dacd7a85b6ed19247ea718bdae6114","offChainPublicKey":"ocroff_62a76d04e13dae5870071badea6b113a5123f4ac1a2cbae6b2fb7070dd9dbf2d","configPublicKey":"ocrcfg_75581baab36744671c2b1d75071b07b08b9cb631b3a7155d2f590744983d9c41","crypto":{"cipher":"aes-128-ctr","ciphertext":"60d2e679f08e0b1538cf609e25f2d32c0b7d408f24cab22dd05bffd3b5580c65552097e203f6546e2d792a4f6adb69449fee0fe4dd7f1060970907518e7c33331abd076388af842f03d05c193b03f22f6bf0423d4ae99dbb563c7158b4eac2a31b03c90fb9fd7be217804243151c36c33504469632bc2c89be33e7b9157edf172a52af4d49fa125b8d0358ea63ace90bc181a7164b548e0f12288ec08b919b46afad1b36dbaeda32d8d657a43908f802b6f2354473f538437ba3bd0b0d374d8e836e623484b655c95f4ef11e30baaa47b9075c6dbb53147c4b489f45a4bdcfa6b56ef2e6eaa9e9b88b570517c991de359d7f07226c00259810a8a4196b7d5331e4126529eac9bd80b47b5540940f89ad0e728b3dd50e6da316d9f3cf9b3be9b87ca6b7868daa7e4142fc4a65fc77deea6f4f2b4bce1e38337aa827160d8c50cad92d157309aa251180b894ab1ca9923d709d","cipherparams":{"iv":"a9507e6f2b073c1da1082d40a24864d1"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"267f9450f52af42a918ab5747043c88bd2035fa3d3e0f0cfd2b621981bc9320f"},"mac":"15aeb3fc1903f514bfe70cb2eb5a23820ba904f5edf8aeb1913d447797f74442"}}` - importedKey, err := ks.Import([]byte(exportedKey), "p4SsW0rD1!@#_") + importedKey, err := ks.Import(ctx, []byte(exportedKey), "p4SsW0rD1!@#_") require.NoError(t, err) require.Equal(t, "7cfd89bbb018e4778a44fd61172e8834dd24b4a2baf61ead795143b117221c61", importedKey.ID()) }) diff --git a/core/services/keystore/orm.go b/core/services/keystore/orm.go index 3d75d6f2369..d1c06f0b6a8 100644 --- a/core/services/keystore/orm.go +++ b/core/services/keystore/orm.go @@ -1,41 +1,41 @@ package keystore import ( + "context" "database/sql" + "github.com/pkg/errors" + + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" - - "github.com/jmoiron/sqlx" - "github.com/pkg/errors" ) -func NewORM(db *sqlx.DB, lggr logger.Logger, cfg pg.QConfig) ksORM { +func NewORM(ds sqlutil.DataSource, lggr logger.Logger) ksORM { namedLogger := lggr.Named("KeystoreORM") return ksORM{ - q: pg.NewQ(db, namedLogger, cfg), + ds: ds, lggr: namedLogger, } } type ksORM struct { - q pg.Q + ds sqlutil.DataSource lggr logger.Logger } -func (orm ksORM) isEmpty() (bool, error) { +func (orm ksORM) isEmpty(ctx context.Context) (bool, error) { var count int64 - err := orm.q.QueryRow("SELECT count(*) FROM encrypted_key_rings").Scan(&count) + err := orm.ds.QueryRowxContext(ctx, "SELECT count(*) FROM encrypted_key_rings").Scan(&count) if err != nil { return false, err } return count == 0, nil } -func (orm ksORM) saveEncryptedKeyRing(kr *encryptedKeyRing, callbacks ...func(pg.Queryer) error) error { - return orm.q.Transaction(func(tx pg.Queryer) error { - _, err := tx.Exec(` +func (orm ksORM) saveEncryptedKeyRing(ctx context.Context, kr *encryptedKeyRing, callbacks ...func(sqlutil.DataSource) error) error { + return sqlutil.TransactDataSource(ctx, orm.ds, nil, func(tx sqlutil.DataSource) error { + _, err := tx.ExecContext(ctx, ` UPDATE encrypted_key_rings SET encrypted_keys = $1 `, kr.EncryptedKeys) @@ -52,11 +52,11 @@ func (orm ksORM) saveEncryptedKeyRing(kr *encryptedKeyRing, callbacks ...func(pg }) } -func (orm ksORM) getEncryptedKeyRing() (kr encryptedKeyRing, err error) { - err = orm.q.Get(&kr, `SELECT * FROM encrypted_key_rings LIMIT 1`) +func (orm ksORM) getEncryptedKeyRing(ctx context.Context) (kr encryptedKeyRing, err error) { + err = orm.ds.GetContext(ctx, &kr, `SELECT * FROM encrypted_key_rings LIMIT 1`) if errors.Is(err, sql.ErrNoRows) { sql := `INSERT INTO encrypted_key_rings (encrypted_keys, updated_at) VALUES (NULL, NOW()) RETURNING *;` - err2 := orm.q.Get(&kr, sql) + err2 := orm.ds.GetContext(ctx, &kr, sql) if err2 != nil { return kr, err2 @@ -67,10 +67,10 @@ func (orm ksORM) getEncryptedKeyRing() (kr encryptedKeyRing, err error) { return kr, nil } -func (orm ksORM) loadKeyStates() (*keyStates, error) { +func (orm ksORM) loadKeyStates(ctx context.Context) (*keyStates, error) { ks := newKeyStates() var ethkeystates []*ethkey.State - if err := orm.q.Select(ðkeystates, `SELECT id, address, evm_chain_id, disabled, created_at, updated_at FROM evm.key_states`); err != nil { + if err := orm.ds.SelectContext(ctx, ðkeystates, `SELECT id, address, evm_chain_id, disabled, created_at, updated_at FROM evm.key_states`); err != nil { return ks, errors.Wrap(err, "error loading evm.key_states from DB") } for _, state := range ethkeystates { diff --git a/core/services/keystore/p2p.go b/core/services/keystore/p2p.go index ee2c64c021d..ee5bc647b5d 100644 --- a/core/services/keystore/p2p.go +++ b/core/services/keystore/p2p.go @@ -1,13 +1,14 @@ package keystore import ( + "context" "fmt" "strings" "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/p2pkey" - "github.com/smartcontractkit/chainlink/v2/core/services/pg" ) //go:generate mockery --quiet --name P2P --output ./mocks/ --case=underscore --filename p2p.go @@ -15,12 +16,12 @@ import ( type P2P interface { Get(id p2pkey.PeerID) (p2pkey.KeyV2, error) GetAll() ([]p2pkey.KeyV2, error) - Create() (p2pkey.KeyV2, error) - Add(key p2pkey.KeyV2) error - Delete(id p2pkey.PeerID) (p2pkey.KeyV2, error) - Import(keyJSON []byte, password string) (p2pkey.KeyV2, error) + Create(ctx context.Context) (p2pkey.KeyV2, error) + Add(ctx context.Context, key p2pkey.KeyV2) error + Delete(ctx context.Context, id p2pkey.PeerID) (p2pkey.KeyV2, error) + Import(ctx context.Context, keyJSON []byte, password string) (p2pkey.KeyV2, error) Export(id p2pkey.PeerID, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error GetOrFirst(id p2pkey.PeerID) (p2pkey.KeyV2, error) } @@ -58,7 +59,7 @@ func (ks *p2p) GetAll() (keys []p2pkey.KeyV2, _ error) { return keys, nil } -func (ks *p2p) Create() (p2pkey.KeyV2, error) { +func (ks *p2p) Create(ctx context.Context) (p2pkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -68,10 +69,10 @@ func (ks *p2p) Create() (p2pkey.KeyV2, error) { if err != nil { return p2pkey.KeyV2{}, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *p2p) Add(key p2pkey.KeyV2) error { +func (ks *p2p) Add(ctx context.Context, key p2pkey.KeyV2) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -80,10 +81,10 @@ func (ks *p2p) Add(key p2pkey.KeyV2) error { if _, found := ks.keyRing.P2P[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *p2p) Delete(id p2pkey.PeerID) (p2pkey.KeyV2, error) { +func (ks *p2p) Delete(ctx context.Context, id p2pkey.PeerID) (p2pkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -93,14 +94,14 @@ func (ks *p2p) Delete(id p2pkey.PeerID) (p2pkey.KeyV2, error) { if err != nil { return p2pkey.KeyV2{}, err } - err = ks.safeRemoveKey(key, func(tx pg.Queryer) error { - _, err2 := tx.Exec(`DELETE FROM p2p_peers WHERE peer_id = $1`, key.ID()) + err = ks.safeRemoveKey(ctx, key, func(ds sqlutil.DataSource) error { + _, err2 := ds.ExecContext(ctx, `DELETE FROM p2p_peers WHERE peer_id = $1`, key.ID()) return err2 }) return key, err } -func (ks *p2p) Import(keyJSON []byte, password string) (p2pkey.KeyV2, error) { +func (ks *p2p) Import(ctx context.Context, keyJSON []byte, password string) (p2pkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -113,7 +114,7 @@ func (ks *p2p) Import(keyJSON []byte, password string) (p2pkey.KeyV2, error) { if _, found := ks.keyRing.P2P[key.ID()]; found { return p2pkey.KeyV2{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *p2p) Export(id p2pkey.PeerID, password string) ([]byte, error) { @@ -129,7 +130,7 @@ func (ks *p2p) Export(id p2pkey.PeerID, password string) ([]byte, error) { return key.ToEncryptedJSON(password, ks.scryptParams) } -func (ks *p2p) EnsureKey() error { +func (ks *p2p) EnsureKey(ctx context.Context) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -147,7 +148,7 @@ func (ks *p2p) EnsureKey() error { ks.logger.Infof("Created P2P key with ID %s", key.ID()) - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } var ( diff --git a/core/services/keystore/p2p_test.go b/core/services/keystore/p2p_test.go index 4dc44651473..f6c86a12814 100644 --- a/core/services/keystore/p2p_test.go +++ b/core/services/keystore/p2p_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "crypto/rand" "fmt" "testing" @@ -12,7 +13,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/p2pkey" @@ -20,15 +20,15 @@ import ( func Test_P2PKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.P2P() reset := func() { + ctx := context.Background() // Executed on cleanup require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -49,7 +49,8 @@ func Test_P2PKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.PeerID()) require.NoError(t, err) @@ -58,7 +59,8 @@ func Test_P2PKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.PeerID(), cltest.Password) require.NoError(t, err) @@ -67,15 +69,15 @@ func Test_P2PKeyStore_E2E(t *testing.T) { require.NoError(t, err) _, err = ks.Export(nonExistent, cltest.Password) assert.Error(t, err) - _, err = ks.Delete(key.PeerID()) + _, err = ks.Delete(ctx, key.PeerID()) require.NoError(t, err) _, err = ks.Get(key.PeerID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) - _, err = ks.Import(exportJSON, cltest.Password) + _, err = ks.Import(ctx, exportJSON, cltest.Password) assert.Error(t, err) - _, err = ks.Import([]byte(""), cltest.Password) + _, err = ks.Import(ctx, []byte(""), cltest.Password) assert.Error(t, err) require.Equal(t, key.PeerID(), importedKey.PeerID()) retrievedKey, err := ks.Get(key.PeerID()) @@ -85,18 +87,19 @@ func Test_P2PKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := p2pkey.NewV2() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.PeerID()) + _, err = ks.Delete(ctx, newKey.PeerID()) require.NoError(t, err) - _, err = ks.Delete(newKey.PeerID()) + _, err = ks.Delete(ctx, newKey.PeerID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -107,14 +110,15 @@ func Test_P2PKeyStore_E2E(t *testing.T) { t.Run("ensures key", func(t *testing.T) { defer reset() - err := ks.EnsureKey() + ctx := testutils.Context(t) + err := ks.EnsureKey(ctx) assert.NoError(t, err) keys, err := ks.GetAll() assert.NoError(t, err) require.Equal(t, 1, len(keys)) - err = ks.EnsureKey() + err = ks.EnsureKey(ctx) assert.NoError(t, err) keys, err = ks.GetAll() @@ -124,12 +128,13 @@ func Test_P2PKeyStore_E2E(t *testing.T) { t.Run("GetOrFirst", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) _, err := ks.GetOrFirst(p2pkey.PeerID{}) require.Contains(t, err.Error(), "no p2p keys exist") id := p2pkey.PeerID{0xa0} _, err = ks.GetOrFirst(id) require.Contains(t, err.Error(), fmt.Sprintf("unable to find P2P key with id %s", id)) - k1, err := ks.Create() + k1, err := ks.Create(ctx) require.NoError(t, err) k2, err := ks.GetOrFirst(p2pkey.PeerID{}) require.NoError(t, err) @@ -137,7 +142,7 @@ func Test_P2PKeyStore_E2E(t *testing.T) { k3, err := ks.GetOrFirst(k1.PeerID()) require.NoError(t, err) require.Equal(t, k1, k3) - _, err = ks.Create() + _, err = ks.Create(ctx) require.NoError(t, err) _, err = ks.GetOrFirst(p2pkey.PeerID{}) require.Contains(t, err.Error(), "multiple p2p keys found") @@ -152,7 +157,8 @@ func Test_P2PKeyStore_E2E(t *testing.T) { }) t.Run("clears p2p_peers on delete", func(t *testing.T) { - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) type P2PPeer struct { ID string @@ -181,14 +187,15 @@ func Test_P2PKeyStore_E2E(t *testing.T) { require.NoError(t, stmt.Get(&p2pPeer1, &p2pPeer1)) require.NoError(t, stmt.Get(&p2pPeer2, &p2pPeer2)) cltest.AssertCount(t, db, p2pTableName, 2) - _, err = ks.Delete(key.PeerID()) + _, err = ks.Delete(ctx, key.PeerID()) require.NoError(t, err) cltest.AssertCount(t, db, p2pTableName, 1) }) t.Run("imports a key exported from a v1 keystore", func(t *testing.T) { + ctx := testutils.Context(t) exportedKey := `{"publicKey":"fcc1fdebde28322dde17233fe7bd6dcde447d60d5cc1de518962deed102eea35","peerID":"p2p_12D3KooWSq2UZgSXvhGLG5uuAAmz1JNjxHMJViJB39aorvbbYo8p","crypto":{"cipher":"aes-128-ctr","ciphertext":"adb2dff72148a8cd467f6f06a03869e7cedf180cf2a4decdb86875b2e1cf3e58c4bd2b721ecdaa88a0825fa9abfc309bf32dbb35a5c0b6cb01ac89a956d78e0550eff351","cipherparams":{"iv":"6cc4381766a4efc39f762b2b8d09dfba"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"ff5055ae4cdcdc2d0404307d578262e2caeb0210f82db3a0ecbdba727c6f5259"},"mac":"d37e4f1dea98d85960ef3205099fc71741715ae56a3b1a8f9215a78de9b95595"}}` - importedKey, err := ks.Import([]byte(exportedKey), "p4SsW0rD1!@#_") + importedKey, err := ks.Import(ctx, []byte(exportedKey), "p4SsW0rD1!@#_") require.NoError(t, err) require.Equal(t, "12D3KooWSq2UZgSXvhGLG5uuAAmz1JNjxHMJViJB39aorvbbYo8p", importedKey.ID()) }) diff --git a/core/services/keystore/solana.go b/core/services/keystore/solana.go index 47b2cde7120..e95af37a7fa 100644 --- a/core/services/keystore/solana.go +++ b/core/services/keystore/solana.go @@ -14,12 +14,12 @@ import ( type Solana interface { Get(id string) (solkey.Key, error) GetAll() ([]solkey.Key, error) - Create() (solkey.Key, error) - Add(key solkey.Key) error - Delete(id string) (solkey.Key, error) - Import(keyJSON []byte, password string) (solkey.Key, error) + Create(ctx context.Context) (solkey.Key, error) + Add(ctx context.Context, key solkey.Key) error + Delete(ctx context.Context, id string) (solkey.Key, error) + Import(ctx context.Context, keyJSON []byte, password string) (solkey.Key, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error Sign(ctx context.Context, id string, msg []byte) (signature []byte, err error) } @@ -72,7 +72,7 @@ func (ks *solana) GetAll() (keys []solkey.Key, _ error) { return keys, nil } -func (ks *solana) Create() (solkey.Key, error) { +func (ks *solana) Create(ctx context.Context) (solkey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -82,10 +82,10 @@ func (ks *solana) Create() (solkey.Key, error) { if err != nil { return solkey.Key{}, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *solana) Add(key solkey.Key) error { +func (ks *solana) Add(ctx context.Context, key solkey.Key) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -94,10 +94,10 @@ func (ks *solana) Add(key solkey.Key) error { if _, found := ks.keyRing.Solana[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *solana) Delete(id string) (solkey.Key, error) { +func (ks *solana) Delete(ctx context.Context, id string) (solkey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -107,11 +107,11 @@ func (ks *solana) Delete(id string) (solkey.Key, error) { if err != nil { return solkey.Key{}, err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return key, err } -func (ks *solana) Import(keyJSON []byte, password string) (solkey.Key, error) { +func (ks *solana) Import(ctx context.Context, keyJSON []byte, password string) (solkey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -124,7 +124,7 @@ func (ks *solana) Import(keyJSON []byte, password string) (solkey.Key, error) { if _, found := ks.keyRing.Solana[key.ID()]; found { return solkey.Key{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *solana) Export(id string, password string) ([]byte, error) { @@ -140,7 +140,7 @@ func (ks *solana) Export(id string, password string) ([]byte, error) { return key.ToEncryptedJSON(password, ks.scryptParams) } -func (ks *solana) EnsureKey() error { +func (ks *solana) EnsureKey(ctx context.Context) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -157,7 +157,7 @@ func (ks *solana) EnsureKey() error { ks.logger.Infof("Created Solana key with ID %s", key.ID()) - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } func (ks *solana) Sign(_ context.Context, id string, msg []byte) (signature []byte, err error) { diff --git a/core/services/keystore/solana_test.go b/core/services/keystore/solana_test.go index cf2515f5f70..7355404d093 100644 --- a/core/services/keystore/solana_test.go +++ b/core/services/keystore/solana_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "testing" "github.com/stretchr/testify/assert" @@ -9,7 +10,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/solkey" @@ -17,15 +17,15 @@ import ( func Test_SolanaKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.Solana() reset := func() { + ctx := context.Background() // Executed on cleanup require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -43,7 +43,8 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -52,21 +53,22 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) _, err = ks.Export("non-existent", cltest.Password) assert.Error(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) - _, err = ks.Import(exportJSON, cltest.Password) + _, err = ks.Import(ctx, exportJSON, cltest.Password) assert.Error(t, err) - _, err = ks.Import([]byte(""), cltest.Password) + _, err = ks.Import(ctx, []byte(""), cltest.Password) assert.Error(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -76,18 +78,19 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := solkey.New() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) assert.Error(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) assert.Error(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -98,10 +101,11 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { t.Run("ensures key", func(t *testing.T) { defer reset() - err := ks.EnsureKey() + ctx := testutils.Context(t) + err := ks.EnsureKey(ctx) assert.NoError(t, err) - err = ks.EnsureKey() + err = ks.EnsureKey(ctx) assert.NoError(t, err) keys, err := ks.GetAll() @@ -111,9 +115,10 @@ func Test_SolanaKeyStore_E2E(t *testing.T) { t.Run("sign tx", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := solkey.New() require.NoError(t, err) - require.NoError(t, ks.Add(newKey)) + require.NoError(t, ks.Add(ctx, newKey)) // sign unknown ID _, err = ks.Sign(testutils.Context(t), "not-real", nil) diff --git a/core/services/keystore/starknet.go b/core/services/keystore/starknet.go index 6b6afa987c6..e6655a4d3f2 100644 --- a/core/services/keystore/starknet.go +++ b/core/services/keystore/starknet.go @@ -18,12 +18,12 @@ import ( type StarkNet interface { Get(id string) (starkkey.Key, error) GetAll() ([]starkkey.Key, error) - Create() (starkkey.Key, error) - Add(key starkkey.Key) error - Delete(id string) (starkkey.Key, error) - Import(keyJSON []byte, password string) (starkkey.Key, error) + Create(ctx context.Context) (starkkey.Key, error) + Add(ctx context.Context, key starkkey.Key) error + Delete(ctx context.Context, id string) (starkkey.Key, error) + Import(ctx context.Context, keyJSON []byte, password string) (starkkey.Key, error) Export(id string, password string) ([]byte, error) - EnsureKey() error + EnsureKey(ctx context.Context) error } type starknet struct { @@ -59,7 +59,7 @@ func (ks *starknet) GetAll() (keys []starkkey.Key, _ error) { return keys, nil } -func (ks *starknet) Create() (starkkey.Key, error) { +func (ks *starknet) Create(ctx context.Context) (starkkey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -69,10 +69,10 @@ func (ks *starknet) Create() (starkkey.Key, error) { if err != nil { return starkkey.Key{}, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *starknet) Add(key starkkey.Key) error { +func (ks *starknet) Add(ctx context.Context, key starkkey.Key) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -81,10 +81,10 @@ func (ks *starknet) Add(key starkkey.Key) error { if _, found := ks.keyRing.StarkNet[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *starknet) Delete(id string) (starkkey.Key, error) { +func (ks *starknet) Delete(ctx context.Context, id string) (starkkey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -94,11 +94,11 @@ func (ks *starknet) Delete(id string) (starkkey.Key, error) { if err != nil { return starkkey.Key{}, err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return key, err } -func (ks *starknet) Import(keyJSON []byte, password string) (starkkey.Key, error) { +func (ks *starknet) Import(ctx context.Context, keyJSON []byte, password string) (starkkey.Key, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -111,7 +111,7 @@ func (ks *starknet) Import(keyJSON []byte, password string) (starkkey.Key, error if _, found := ks.keyRing.StarkNet[key.ID()]; found { return starkkey.Key{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *starknet) Export(id string, password string) ([]byte, error) { @@ -127,7 +127,7 @@ func (ks *starknet) Export(id string, password string) ([]byte, error) { return starkkey.ToEncryptedJSON(key, password, ks.scryptParams) } -func (ks *starknet) EnsureKey() error { +func (ks *starknet) EnsureKey(ctx context.Context) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -144,7 +144,7 @@ func (ks *starknet) EnsureKey() error { ks.logger.Infof("Created StarkNet key with ID %s", key.ID()) - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } func (ks *starknet) getByID(id string) (starkkey.Key, error) { diff --git a/core/services/keystore/starknet_test.go b/core/services/keystore/starknet_test.go index 43624a4159e..97d4219272b 100644 --- a/core/services/keystore/starknet_test.go +++ b/core/services/keystore/starknet_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "fmt" "math/big" "testing" @@ -14,7 +15,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/starkkey" @@ -25,15 +25,15 @@ import ( func Test_StarkNetKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.StarkNet() reset := func() { + ctx := context.Background() // Executed on cleanup require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -51,7 +51,8 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -60,15 +61,16 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -78,14 +80,15 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := starkkey.New() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -96,10 +99,11 @@ func Test_StarkNetKeyStore_E2E(t *testing.T) { t.Run("ensures key", func(t *testing.T) { defer reset() - err := ks.EnsureKey() + ctx := testutils.Context(t) + err := ks.EnsureKey(ctx) assert.NoError(t, err) - err = ks.EnsureKey() + err = ks.EnsureKey(ctx) assert.NoError(t, err) keys, err := ks.GetAll() diff --git a/core/services/keystore/vrf.go b/core/services/keystore/vrf.go index 91e77557674..7b222e193d1 100644 --- a/core/services/keystore/vrf.go +++ b/core/services/keystore/vrf.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "math/big" @@ -14,10 +15,10 @@ import ( type VRF interface { Get(id string) (vrfkey.KeyV2, error) GetAll() ([]vrfkey.KeyV2, error) - Create() (vrfkey.KeyV2, error) - Add(key vrfkey.KeyV2) error - Delete(id string) (vrfkey.KeyV2, error) - Import(keyJSON []byte, password string) (vrfkey.KeyV2, error) + Create(ctx context.Context) (vrfkey.KeyV2, error) + Add(ctx context.Context, key vrfkey.KeyV2) error + Delete(ctx context.Context, id string) (vrfkey.KeyV2, error) + Import(ctx context.Context, keyJSON []byte, password string) (vrfkey.KeyV2, error) Export(id string, password string) ([]byte, error) GenerateProof(id string, seed *big.Int) (vrfkey.Proof, error) @@ -60,7 +61,7 @@ func (ks *vrf) GetAll() (keys []vrfkey.KeyV2, _ error) { return keys, nil } -func (ks *vrf) Create() (vrfkey.KeyV2, error) { +func (ks *vrf) Create(ctx context.Context) (vrfkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -70,10 +71,10 @@ func (ks *vrf) Create() (vrfkey.KeyV2, error) { if err != nil { return vrfkey.KeyV2{}, err } - return key, ks.safeAddKey(key) + return key, ks.safeAddKey(ctx, key) } -func (ks *vrf) Add(key vrfkey.KeyV2) error { +func (ks *vrf) Add(ctx context.Context, key vrfkey.KeyV2) error { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -82,10 +83,10 @@ func (ks *vrf) Add(key vrfkey.KeyV2) error { if _, found := ks.keyRing.VRF[key.ID()]; found { return fmt.Errorf("key with ID %s already exists", key.ID()) } - return ks.safeAddKey(key) + return ks.safeAddKey(ctx, key) } -func (ks *vrf) Delete(id string) (vrfkey.KeyV2, error) { +func (ks *vrf) Delete(ctx context.Context, id string) (vrfkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -95,11 +96,11 @@ func (ks *vrf) Delete(id string) (vrfkey.KeyV2, error) { if err != nil { return vrfkey.KeyV2{}, err } - err = ks.safeRemoveKey(key) + err = ks.safeRemoveKey(ctx, key) return key, err } -func (ks *vrf) Import(keyJSON []byte, password string) (vrfkey.KeyV2, error) { +func (ks *vrf) Import(ctx context.Context, keyJSON []byte, password string) (vrfkey.KeyV2, error) { ks.lock.Lock() defer ks.lock.Unlock() if ks.isLocked() { @@ -112,7 +113,7 @@ func (ks *vrf) Import(keyJSON []byte, password string) (vrfkey.KeyV2, error) { if _, found := ks.keyRing.VRF[key.ID()]; found { return vrfkey.KeyV2{}, fmt.Errorf("key with ID %s already exists", key.ID()) } - return key, ks.keyManager.safeAddKey(key) + return key, ks.keyManager.safeAddKey(ctx, key) } func (ks *vrf) Export(id string, password string) ([]byte, error) { diff --git a/core/services/keystore/vrf_test.go b/core/services/keystore/vrf_test.go index 77fccd865ff..4b77377d5e8 100644 --- a/core/services/keystore/vrf_test.go +++ b/core/services/keystore/vrf_test.go @@ -1,6 +1,7 @@ package keystore_test import ( + "context" "fmt" "math/big" "testing" @@ -9,7 +10,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/vrfkey" @@ -19,14 +20,14 @@ import ( func Test_VRFKeyStore_E2E(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - keyStore := keystore.ExposedNewMaster(t, db, cfg.Database()) - require.NoError(t, keyStore.Unlock(cltest.Password)) + keyStore := keystore.ExposedNewMaster(t, db) + require.NoError(t, keyStore.Unlock(testutils.Context(t), cltest.Password)) ks := keyStore.VRF() reset := func() { + ctx := context.Background() // Executed during cleanup require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) keyStore.ResetXXXTestOnly() - require.NoError(t, keyStore.Unlock(cltest.Password)) + require.NoError(t, keyStore.Unlock(ctx, cltest.Password)) } t.Run("initializes with an empty state", func(t *testing.T) { @@ -44,7 +45,8 @@ func Test_VRFKeyStore_E2E(t *testing.T) { t.Run("creates a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) retrievedKey, err := ks.Get(key.ID()) require.NoError(t, err) @@ -53,15 +55,16 @@ func Test_VRFKeyStore_E2E(t *testing.T) { t.Run("imports and exports a key", func(t *testing.T) { defer reset() - key, err := ks.Create() + ctx := testutils.Context(t) + key, err := ks.Create(ctx) require.NoError(t, err) exportJSON, err := ks.Export(key.ID(), cltest.Password) require.NoError(t, err) - _, err = ks.Delete(key.ID()) + _, err = ks.Delete(ctx, key.ID()) require.NoError(t, err) _, err = ks.Get(key.ID()) require.Error(t, err) - importedKey, err := ks.Import(exportJSON, cltest.Password) + importedKey, err := ks.Import(ctx, exportJSON, cltest.Password) require.NoError(t, err) require.Equal(t, key.ID(), importedKey.ID()) retrievedKey, err := ks.Get(key.ID()) @@ -71,14 +74,15 @@ func Test_VRFKeyStore_E2E(t *testing.T) { t.Run("adds an externally created key / deletes a key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) newKey, err := vrfkey.NewV2() require.NoError(t, err) - err = ks.Add(newKey) + err = ks.Add(ctx, newKey) require.NoError(t, err) keys, err := ks.GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) - _, err = ks.Delete(newKey.ID()) + _, err = ks.Delete(ctx, newKey.ID()) require.NoError(t, err) keys, err = ks.GetAll() require.NoError(t, err) @@ -89,13 +93,14 @@ func Test_VRFKeyStore_E2E(t *testing.T) { t.Run("fails to add an already added key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) k, err := vrfkey.NewV2() require.NoError(t, err) - err = ks.Add(k) + err = ks.Add(ctx, k) require.NoError(t, err) - err = ks.Add(k) + err = ks.Add(ctx, k) assert.Error(t, err) assert.Equal(t, fmt.Sprintf("key with ID %s already exists", k.ID()), err.Error()) @@ -103,14 +108,15 @@ func Test_VRFKeyStore_E2E(t *testing.T) { t.Run("fails to delete a key that doesn't exists", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) k, err := vrfkey.NewV2() require.NoError(t, err) - err = ks.Add(k) + err = ks.Add(ctx, k) require.NoError(t, err) - fk, err := ks.Delete("non-existent") + fk, err := ks.Delete(ctx, "non-existent") assert.Zero(t, fk) assert.Error(t, err) @@ -118,22 +124,24 @@ func Test_VRFKeyStore_E2E(t *testing.T) { t.Run("imports a key exported from a v1 keystore", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) exportedKey := `{"PublicKey":"0xd2377bc6be8a2c5ce163e1867ee42ef111e320686f940a98e52e9c019ca0606800","vrf_key":{"address":"b94276ad4e5452732ec0cccf30ef7919b67844b6","crypto":{"cipher":"aes-128-ctr","ciphertext":"ff66d61d02dba54a61bab1ceb8414643f9e76b7351785d2959e2c8b50ee69a92","cipherparams":{"iv":"75705da271b11e330a27b8d593a3930c"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"efe5b372e4fe79d0af576a79d65a1ee35d0792d9c92b70107b5ada1817ea7c7b"},"mac":"e4d0bb08ffd004ab03aeaa42367acbd9bb814c6cfd981f5157503f54c30816e7"},"version":3}}` - importedKey, err := ks.Import([]byte(exportedKey), "p4SsW0rD1!@#_") + importedKey, err := ks.Import(ctx, []byte(exportedKey), "p4SsW0rD1!@#_") require.NoError(t, err) require.Equal(t, "0xd2377bc6be8a2c5ce163e1867ee42ef111e320686f940a98e52e9c019ca0606800", importedKey.ID()) }) t.Run("fails to import an already imported key", func(t *testing.T) { defer reset() + ctx := testutils.Context(t) exportedKey := `{"PublicKey":"0xd2377bc6be8a2c5ce163e1867ee42ef111e320686f940a98e52e9c019ca0606800","vrf_key":{"address":"b94276ad4e5452732ec0cccf30ef7919b67844b6","crypto":{"cipher":"aes-128-ctr","ciphertext":"ff66d61d02dba54a61bab1ceb8414643f9e76b7351785d2959e2c8b50ee69a92","cipherparams":{"iv":"75705da271b11e330a27b8d593a3930c"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"efe5b372e4fe79d0af576a79d65a1ee35d0792d9c92b70107b5ada1817ea7c7b"},"mac":"e4d0bb08ffd004ab03aeaa42367acbd9bb814c6cfd981f5157503f54c30816e7"},"version":3}}` - importedKey, err := ks.Import([]byte(exportedKey), "p4SsW0rD1!@#_") + importedKey, err := ks.Import(ctx, []byte(exportedKey), "p4SsW0rD1!@#_") require.NoError(t, err) keyStore.SetPassword("p4SsW0rD1!@#_") - k, err := ks.Import([]byte(exportedKey), "p4SsW0rD1!@#_") + k, err := ks.Import(ctx, []byte(exportedKey), "p4SsW0rD1!@#_") assert.Zero(t, k) assert.Error(t, err) @@ -158,9 +166,10 @@ func Test_VRFKeyStore_E2E(t *testing.T) { }) t.Run("generates a proof for a key", func(t *testing.T) { + ctx := testutils.Context(t) k, err := vrfkey.NewV2() require.NoError(t, err) - err = ks.Add(k) + err = ks.Add(ctx, k) require.NoError(t, err) pf, err := ks.GenerateProof(k.ID(), big.NewInt(int64(1))) diff --git a/core/services/ocr/database_test.go b/core/services/ocr/database_test.go index 8b8d64c49c9..a2559ca2a87 100644 --- a/core/services/ocr/database_test.go +++ b/core/services/ocr/database_test.go @@ -16,7 +16,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/ocr" ) @@ -25,8 +24,7 @@ func Test_DB_ReadWriteState(t *testing.T) { db := pgtest.NewSqlxDB(t) configDigest := cltest.MakeConfigDigest(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() key, _ := cltest.MustInsertRandomKey(t, ethKeyStore) spec := cltest.MustInsertOffchainreportingOracleSpec(t, db, key.EIP55Address) @@ -106,7 +104,6 @@ func Test_DB_ReadWriteState(t *testing.T) { func Test_DB_ReadWriteConfig(t *testing.T) { db := pgtest.NewSqlxDB(t) sqlDB := db - cfg := configtest.NewTestGeneralConfig(t) config := ocrtypes.ContractConfig{ ConfigDigest: cltest.MakeConfigDigest(t), @@ -116,7 +113,7 @@ func Test_DB_ReadWriteConfig(t *testing.T) { EncodedConfigVersion: uint64(987654), Encoded: []byte{1, 2, 3, 4, 5}, } - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() key, _ := cltest.MustInsertRandomKey(t, ethKeyStore) spec := cltest.MustInsertOffchainreportingOracleSpec(t, db, key.EIP55Address) transmitterAddress := key.Address @@ -188,8 +185,7 @@ func assertPendingTransmissionEqual(t *testing.T, pt1, pt2 ocrtypes.PendingTrans func Test_DB_PendingTransmissions(t *testing.T) { db := pgtest.NewSqlxDB(t) sqlDB := db - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() key, _ := cltest.MustInsertRandomKey(t, ethKeyStore) spec := cltest.MustInsertOffchainreportingOracleSpec(t, db, key.EIP55Address) diff --git a/core/services/ocr2/database_test.go b/core/services/ocr2/database_test.go index 486bf1fd708..6e4f8f5dd66 100644 --- a/core/services/ocr2/database_test.go +++ b/core/services/ocr2/database_test.go @@ -61,7 +61,7 @@ func Test_DB_ReadWriteState(t *testing.T) { configDigest := testhelpers.MakeConfigDigest(t) cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, sqlDB, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, sqlDB).Eth() key, _ := cltest.MustInsertRandomKey(t, ethKeyStore) spec := MustInsertOCROracleSpec(t, sqlDB, key.EIP55Address) lggr := logger.TestLogger(t) @@ -152,7 +152,7 @@ func Test_DB_ReadWriteConfig(t *testing.T) { OffchainConfig: []byte{0x03, 0x04}, } cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, sqlDB, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, sqlDB).Eth() key, _ := cltest.MustInsertRandomKey(t, ethKeyStore) spec := MustInsertOCROracleSpec(t, sqlDB, key.EIP55Address) lggr := logger.TestLogger(t) @@ -239,7 +239,7 @@ func Test_DB_PendingTransmissions(t *testing.T) { sqlDB := setupDB(t) cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, sqlDB, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, sqlDB).Eth() key, _ := cltest.MustInsertRandomKey(t, ethKeyStore) lggr := logger.TestLogger(t) diff --git a/core/services/ocr2/delegate_test.go b/core/services/ocr2/delegate_test.go index ea8693d48ce..bae1f5f3e78 100644 --- a/core/services/ocr2/delegate_test.go +++ b/core/services/ocr2/delegate_test.go @@ -27,6 +27,7 @@ import ( ) func TestGetEVMEffectiveTransmitterID(t *testing.T) { + ctx := testutils.Context(t) customChainID := big.New(testutils.NewRandomEVMChainID()) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -39,8 +40,8 @@ func TestGetEVMEffectiveTransmitterID(t *testing.T) { }) }) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) - require.NoError(t, keyStore.OCR2().Add(cltest.DefaultOCR2Key)) + keyStore := cltest.NewKeyStore(t, db) + require.NoError(t, keyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key)) lggr := logger.TestLogger(t) txManager := txmmocks.NewMockEvmTxManager(t) diff --git a/core/services/ocr2/plugins/dkg/config/config_test.go b/core/services/ocr2/plugins/dkg/config/config_test.go index fe796a9ad6c..f8cc1265ee1 100644 --- a/core/services/ocr2/plugins/dkg/config/config_test.go +++ b/core/services/ocr2/plugins/dkg/config/config_test.go @@ -7,21 +7,21 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/dkg/config" ) func TestValidatePluginConfig(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) - cfg := configtest.NewGeneralConfig(t, nil) db := pgtest.NewSqlxDB(t) - kst := cltest.NewKeyStore(t, db, cfg.Database()) + kst := cltest.NewKeyStore(t, db) - dkgEncryptKey, err := kst.DKGEncrypt().Create() + dkgEncryptKey, err := kst.DKGEncrypt().Create(ctx) require.NoError(t, err) - dkgSignKey, err := kst.DKGSign().Create() + dkgSignKey, err := kst.DKGSign().Create(ctx) require.NoError(t, err) encryptKeyBytes, err := dkgEncryptKey.PublicKey.MarshalBinary() diff --git a/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go b/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go index ae9bf5f01cd..3f96b49cfe0 100644 --- a/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go +++ b/core/services/ocr2/plugins/functions/integration_tests/v1/internal/testutils.go @@ -317,6 +317,7 @@ func StartNewNode( ocr2Keystore []byte, thresholdKeyShare string, ) *Node { + ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) config, _ := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Insecure.OCRDevelopmentMode = ptr(true) @@ -371,9 +372,9 @@ func StartNewNode( var kb ocr2key.KeyBundle if ocr2Keystore != nil { - kb, err = app.GetKeyStore().OCR2().Import(ocr2Keystore, "testPassword") + kb, err = app.GetKeyStore().OCR2().Import(ctx, ocr2Keystore, "testPassword") } else { - kb, err = app.GetKeyStore().OCR2().Create("evm") + kb, err = app.GetKeyStore().OCR2().Create(ctx, "evm") } require.NoError(t, err) diff --git a/core/services/ocr2/plugins/generic/pipeline_runner_adapter_test.go b/core/services/ocr2/plugins/generic/pipeline_runner_adapter_test.go index 02136583e49..ae74cb218ee 100644 --- a/core/services/ocr2/plugins/generic/pipeline_runner_adapter_test.go +++ b/core/services/ocr2/plugins/generic/pipeline_runner_adapter_test.go @@ -37,13 +37,14 @@ answer; func TestAdapter_Integration(t *testing.T) { testutils.SkipShortDB(t) + ctx := testutils.Context(t) logger := logger.TestLogger(t) cfg := configtest.NewTestGeneralConfig(t) url := cfg.Database().URL() db, err := pg.NewConnection(url.String(), cfg.Database().Dialect(), cfg.Database()) require.NoError(t, err) - keystore := keystore.NewInMemory(db, utils.FastScryptParams, logger, cfg.Database()) + keystore := keystore.NewInMemory(db, utils.FastScryptParams, logger) pipelineORM := pipeline.NewORM(db, logger, cfg.JobPipeline().MaxSuccessfulRuns()) bridgesORM := bridges.NewORM(db) jobORM := job.NewORM(db, pipelineORM, bridgesORM, keystore, logger, cfg.Database()) @@ -59,7 +60,7 @@ func TestAdapter_Integration(t *testing.T) { http.DefaultClient, http.DefaultClient, ) - err = keystore.Unlock(cfg.Password().Keystore()) + err = keystore.Unlock(ctx, cfg.Password().Keystore()) require.NoError(t, err) jb, err := ocr2validate.ValidatedOracleSpecToml(testutils.Context(t), cfg.OCR2(), cfg.Insecure(), testspecs.GetOCR2EVMSpecMinimal(), nil) require.NoError(t, err) diff --git a/core/services/ocr2/plugins/ocr2keeper/integration_test.go b/core/services/ocr2/plugins/ocr2keeper/integration_test.go index ea752256232..1054c59dd1c 100644 --- a/core/services/ocr2/plugins/ocr2keeper/integration_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/integration_test.go @@ -112,6 +112,7 @@ func setupNode( p2pV2Bootstrappers []commontypes.BootstrapperLocator, mercury mercury.MercuryEndpointMock, ) (chainlink.Application, string, common.Address, ocr2key.KeyBundle) { + ctx := testutils.Context(t) p2pKey := keystest.NewP2PKeyV2(t) p2paddresses := []string{fmt.Sprintf("127.0.0.1:%d", port)} cfg, _ := heavyweight.FullTestDBV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -143,10 +144,10 @@ func setupNode( }) app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, cfg, backend, nodeKey, p2pKey) - kb, err := app.GetKeyStore().OCR2().Create(chaintype.EVM) + kb, err := app.GetKeyStore().OCR2().Create(ctx, chaintype.EVM) require.NoError(t, err) - err = app.Start(testutils.Context(t)) + err = app.Start(ctx) require.NoError(t, err) t.Cleanup(func() { diff --git a/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go b/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go index 94c4c0bb8fc..ac2695dc632 100644 --- a/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go +++ b/core/services/ocr2/plugins/ocr2vrf/internal/ocr2vrf_integration_test.go @@ -312,7 +312,7 @@ func setupNodeOCR2( b.Commit() } - kb, err := app.GetKeyStore().OCR2().Create("evm") + kb, err := app.GetKeyStore().OCR2().Create(ctx, "evm") require.NoError(t, err) return &ocr2Node{ @@ -371,10 +371,10 @@ func runOCR2VRFTest(t *testing.T, useForwarders bool) { node := setupNodeOCR2(t, uni.owner, ports[i], fmt.Sprintf("ocr2vrforacle%d", i), uni.backend, useForwarders, bootstrappers) sendingKeys = append(sendingKeys, node.sendingKeys) - dkgSignKey, err := node.app.GetKeyStore().DKGSign().Create() + dkgSignKey, err := node.app.GetKeyStore().DKGSign().Create(ctx) require.NoError(t, err) - dkgEncryptKey, err := node.app.GetKeyStore().DKGEncrypt().Create() + dkgEncryptKey, err := node.app.GetKeyStore().DKGEncrypt().Create(ctx) require.NoError(t, err) kbs = append(kbs, node.keybundle) diff --git a/core/services/ocrcommon/peer_wrapper_test.go b/core/services/ocrcommon/peer_wrapper_test.go index f46b2af27c5..e87f211fd21 100644 --- a/core/services/ocrcommon/peer_wrapper_test.go +++ b/core/services/ocrcommon/peer_wrapper_test.go @@ -33,20 +33,18 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) }) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), cfg.Database(), db, logger.TestLogger(t)) require.Contains(t, pw.Start(testutils.Context(t)).Error(), "No P2P keys found in keystore. Peer wrapper will not be fully initialized") }) t.Run("with one p2p key and matching P2P.PeerID returns nil", func(t *testing.T) { - cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) - }) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) - k, err := keyStore.P2P().Create() + ctx := testutils.Context(t) + keyStore := cltest.NewKeyStore(t, db) + k, err := keyStore.P2P().Create(ctx) require.NoError(t, err) - cfg = configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { + cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = ptr(k.PeerID()) @@ -58,13 +56,14 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { }) t.Run("with one p2p key and mismatching P2P.PeerID returns error", func(t *testing.T) { + ctx := testutils.Context(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) c.P2P.PeerID = ptr(p2pkey.PeerID(peerID)) }) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) - _, err := keyStore.P2P().Create() + _, err := keyStore.P2P().Create(ctx) require.NoError(t, err) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), cfg.Database(), db, logger.TestLogger(t)) @@ -73,15 +72,12 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { }) t.Run("with multiple p2p keys and valid P2P.PeerID returns nil", func(t *testing.T) { - cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) - c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - }) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) - k2, err := keyStore.P2P().Create() + ctx := testutils.Context(t) + keyStore := cltest.NewKeyStore(t, db) + k2, err := keyStore.P2P().Create(ctx) require.NoError(t, err) - cfg = configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { + cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = ptr(k2.PeerID()) @@ -94,14 +90,15 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { }) t.Run("with multiple p2p keys and mismatching P2P.PeerID returns error", func(t *testing.T) { + ctx := testutils.Context(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = ptr(p2pkey.PeerID(peerID)) }) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) - _, err := keyStore.P2P().Create() + _, err := keyStore.P2P().Create(ctx) require.NoError(t, err) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), cfg.Database(), db, logger.TestLogger(t)) @@ -112,15 +109,15 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { func Test_SingletonPeerWrapper_Close(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) - k, err := keyStore.P2P().Create() + keyStore := cltest.NewKeyStore(t, db) + k, err := keyStore.P2P().Create(ctx) require.NoError(t, err) - cfg = configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { + cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.P2P.V2.Enabled = ptr(true) c.P2P.PeerID = ptr(k.PeerID()) c.P2P.V2.DeltaDial = commonconfig.MustNewDuration(100 * time.Millisecond) diff --git a/core/services/ocrcommon/transmitter_test.go b/core/services/ocrcommon/transmitter_test.go index c56896ab2b9..d6a07190800 100644 --- a/core/services/ocrcommon/transmitter_test.go +++ b/core/services/ocrcommon/transmitter_test.go @@ -13,7 +13,6 @@ import ( txmmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr/mocks" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/services/ocrcommon" ) @@ -26,8 +25,7 @@ func Test_DefaultTransmitter_CreateEthTransaction(t *testing.T) { t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -67,8 +65,7 @@ func Test_DefaultTransmitter_Forwarding_Enabled_CreateEthTransaction(t *testing. t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) _, fromAddress2 := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -119,8 +116,7 @@ func Test_DefaultTransmitter_Forwarding_Enabled_CreateEthTransaction_Round_Robin t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() fromAddress := common.Address{} @@ -150,8 +146,7 @@ func Test_DefaultTransmitter_Forwarding_Enabled_CreateEthTransaction_No_Keystore t.Parallel() db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) _, fromAddress2 := cltest.MustInsertRandomKey(t, ethKeyStore) diff --git a/core/services/pipeline/orm_test.go b/core/services/pipeline/orm_test.go index 88155bc04ba..bba928534ba 100644 --- a/core/services/pipeline/orm_test.go +++ b/core/services/pipeline/orm_test.go @@ -74,7 +74,7 @@ func setupORM(t *testing.T, heavy bool) (db *sqlx.DB, orm pipeline.ORM, jorm job orm = pipeline.NewORM(db, logger.TestLogger(t), cfg.JobPipelineMaxSuccessfulRuns()) config := configtest.NewTestGeneralConfig(t) lggr := logger.TestLogger(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) bridgeORM := bridges.NewORM(db) jorm = job.NewORM(db, orm, bridgeORM, keyStore, lggr, config.Database()) @@ -661,7 +661,7 @@ func Test_GetUnfinishedRuns_Keepers(t *testing.T) { config := configtest.NewTestGeneralConfig(t) lggr := logger.TestLogger(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) porm := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) bridgeORM := bridges.NewORM(db) @@ -764,7 +764,7 @@ func Test_GetUnfinishedRuns_DirectRequest(t *testing.T) { config := configtest.NewTestGeneralConfig(t) lggr := logger.TestLogger(t) db := pgtest.NewSqlxDB(t) - keyStore := cltest.NewKeyStore(t, db, config.Database()) + keyStore := cltest.NewKeyStore(t, db) porm := pipeline.NewORM(db, lggr, config.JobPipeline().MaxSuccessfulRuns()) bridgeORM := bridges.NewORM(db) diff --git a/core/services/pipeline/runner_test.go b/core/services/pipeline/runner_test.go index f27a6b35348..e086d5297ef 100644 --- a/core/services/pipeline/runner_test.go +++ b/core/services/pipeline/runner_test.go @@ -43,7 +43,7 @@ import ( func newRunner(t testing.TB, db *sqlx.DB, bridgeORM bridges.ORM, cfg chainlink.GeneralConfig) (pipeline.Runner, *mocks.ORM) { lggr := logger.TestLogger(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, KeyStore: ethKeyStore}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) orm := mocks.NewORM(t) @@ -480,7 +480,7 @@ func Test_PipelineRunner_HandleFaultsPersistRun(t *testing.T) { }). Return(nil) cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, KeyStore: ethKeyStore}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) lggr := logger.TestLogger(t) @@ -521,7 +521,7 @@ func Test_PipelineRunner_ExecuteAndInsertFinishedRun_SavingTheSpec(t *testing.T) }). Return(nil) cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, KeyStore: ethKeyStore}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) lggr := logger.TestLogger(t) @@ -1002,7 +1002,7 @@ func Test_PipelineRunner_ExecuteRun(t *testing.T) { t.Run("uses cached *Pipeline if available", func(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, KeyStore: ethKeyStore}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) lggr := logger.TestLogger(t) diff --git a/core/services/promreporter/prom_reporter_test.go b/core/services/promreporter/prom_reporter_test.go index 9627b52f871..635b5b83c47 100644 --- a/core/services/promreporter/prom_reporter_test.go +++ b/core/services/promreporter/prom_reporter_test.go @@ -34,7 +34,7 @@ func newHead() evmtypes.Head { func newLegacyChainContainer(t *testing.T, db *sqlx.DB) legacyevm.LegacyChainContainer { config, dbConfig, evmConfig := txmgr.MakeTestConfigs(t) - keyStore := cltest.NewKeyStore(t, db, dbConfig).Eth() + keyStore := cltest.NewKeyStore(t, db).Eth() ethClient := evmtest.NewEthClientMockWithDefaultChain(t) estimator := gas.NewEstimator(logger.TestLogger(t), ethClient, config, evmConfig.GasEstimator()) lggr := logger.TestLogger(t) @@ -95,9 +95,8 @@ func Test_PromReporter_OnNewLongestChain(t *testing.T) { t.Run("with unconfirmed evm.txes", func(t *testing.T) { db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() _, fromAddress := cltest.MustInsertRandomKey(t, ethKeyStore) var subscribeCalls atomic.Int32 diff --git a/core/services/relay/evm/functions/contract_transmitter_test.go b/core/services/relay/evm/functions/contract_transmitter_test.go index fb50f6941b2..c0ca43e23ca 100644 --- a/core/services/relay/evm/functions/contract_transmitter_test.go +++ b/core/services/relay/evm/functions/contract_transmitter_test.go @@ -22,7 +22,6 @@ import ( txmmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr/mocks" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/functions/encoding" @@ -38,8 +37,7 @@ func TestContractTransmitter_LatestConfigDigestAndEpoch(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() digestStr := "000130da6b9315bd59af6b0a3f5463c0d0a39e92eaa34cbcbdbace7b3bfcc776" lggr := logger.TestLogger(t) @@ -90,8 +88,7 @@ func TestContractTransmitter_Transmit_V1(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() contractVersion := uint32(1) configuredDestAddress, coordinatorAddress := testutils.NewAddress(), testutils.NewAddress() @@ -169,8 +166,7 @@ func TestContractTransmitter_Transmit_V1_CoordinatorMismatch(t *testing.T) { ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) - ethKeyStore := cltest.NewKeyStore(t, db, cfg.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() contractVersion := uint32(1) configuredDestAddress, coordinatorAddress1, coordinatorAddress2 := testutils.NewAddress(), testutils.NewAddress(), testutils.NewAddress() diff --git a/core/services/relay/evm/relayer_extender_test.go b/core/services/relay/evm/relayer_extender_test.go index af15461aee9..b9a6433c3a7 100644 --- a/core/services/relay/evm/relayer_extender_test.go +++ b/core/services/relay/evm/relayer_extender_test.go @@ -22,6 +22,7 @@ import ( func TestChainRelayExtenders(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) newId := testutils.NewRandomEVMChainID() cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -31,8 +32,8 @@ func TestChainRelayExtenders(t *testing.T) { c.EVM = append(c.EVM, &toml.EVMConfig{ChainID: ubig.New(newId), Enabled: &t, Chain: toml.Defaults(nil)}) }) db := pgtest.NewSqlxDB(t) - kst := cltest.NewKeyStore(t, db, cfg.Database()) - require.NoError(t, kst.Unlock(cltest.Password)) + kst := cltest.NewKeyStore(t, db) + require.NoError(t, kst.Unlock(ctx, cltest.Password)) opts := evmtest.NewChainRelayExtOpts(t, evmtest.TestChainOpts{DB: db, KeyStore: kst.Eth(), GeneralConfig: cfg}) opts.GenEthClient = func(*big.Int) evmclient.Client { diff --git a/core/services/vrf/delegate_test.go b/core/services/vrf/delegate_test.go index db9724179e7..6df91cef717 100644 --- a/core/services/vrf/delegate_test.go +++ b/core/services/vrf/delegate_test.go @@ -67,6 +67,7 @@ type vrfUniverse struct { } func buildVrfUni(t *testing.T, db *sqlx.DB, cfg chainlink.GeneralConfig) vrfUniverse { + ctx := testutils.Context(t) // Mock all chain interactions lb := log_mocks.NewBroadcaster(t) lb.On("AddDependents", 1).Maybe() @@ -80,7 +81,7 @@ func buildVrfUni(t *testing.T, db *sqlx.DB, cfg chainlink.GeneralConfig) vrfUniv // Don't mock db interactions prm := pipeline.NewORM(db, lggr, cfg.JobPipeline().MaxSuccessfulRuns()) btORM := bridges.NewORM(db) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg.Database()) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) _, dbConfig, evmConfig := txmgr.MakeTestConfigs(t) txm, err := txmgr.NewTxm(db, db, evmConfig, evmConfig.GasEstimator(), evmConfig.Transactions(), dbConfig, dbConfig.Listener(), ec, logger.TestLogger(t), nil, ks.Eth(), nil) orm := headtracker.NewORM(*testutils.FixtureChainID, db) @@ -90,12 +91,12 @@ func buildVrfUni(t *testing.T, db *sqlx.DB, cfg chainlink.GeneralConfig) vrfUniv relayExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{LogBroadcaster: lb, KeyStore: ks.Eth(), Client: ec, DB: db, GeneralConfig: cfg, TxManager: txm}) legacyChains := evmrelay.NewLegacyChainsFromRelayerExtenders(relayExtenders) pr := pipeline.NewRunner(prm, btORM, cfg.JobPipeline(), cfg.WebServer(), legacyChains, ks.Eth(), ks.VRF(), lggr, nil, nil) - require.NoError(t, ks.Unlock(testutils.Password)) + require.NoError(t, ks.Unlock(ctx, testutils.Password)) k, err2 := ks.Eth().Create(testutils.Context(t), testutils.FixtureChainID) require.NoError(t, err2) submitter := k.Address require.NoError(t, err) - vrfkey, err3 := ks.VRF().Create() + vrfkey, err3 := ks.VRF().Create(ctx) require.NoError(t, err3) return vrfUniverse{ @@ -559,11 +560,11 @@ decode_log->vrf->encode_tx->submit_tx func Test_CheckFromAddressesExist(t *testing.T) { t.Run("from addresses exist", func(t *testing.T) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) lggr := logger.TestLogger(t) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg.Database()) - require.NoError(t, ks.Unlock(testutils.Password)) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, testutils.Password)) var fromAddresses []string for i := 0; i < 3; i++ { @@ -587,11 +588,11 @@ func Test_CheckFromAddressesExist(t *testing.T) { }) t.Run("one of from addresses doesn't exist", func(t *testing.T) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewTestGeneralConfig(t) lggr := logger.TestLogger(t) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg.Database()) - require.NoError(t, ks.Unlock(testutils.Password)) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, testutils.Password)) var fromAddresses []string for i := 0; i < 3; i++ { diff --git a/core/services/vrf/proof/proof_response_test.go b/core/services/vrf/proof/proof_response_test.go index c547be2be2c..994ac80b5e2 100644 --- a/core/services/vrf/proof/proof_response_test.go +++ b/core/services/vrf/proof/proof_response_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/solidity_vrf_verifier_wrapper" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" proof2 "github.com/smartcontractkit/chainlink/v2/core/services/vrf/proof" "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -22,11 +22,11 @@ import ( ) func TestMarshaledProof(t *testing.T) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) - cfg := configtest.NewGeneralConfig(t, nil) - keyStore := cltest.NewKeyStore(t, db, cfg.Database()) + keyStore := cltest.NewKeyStore(t, db) key := cltest.DefaultVRFKey - require.NoError(t, keyStore.VRF().Add(key)) + require.NoError(t, keyStore.VRF().Add(ctx, key)) blockHash := common.Hash{} blockNum := 0 preSeed := big.NewInt(1) diff --git a/core/services/vrf/v1/integration_test.go b/core/services/vrf/v1/integration_test.go index 1d11615950b..c28ad9ce3d0 100644 --- a/core/services/vrf/v1/integration_test.go +++ b/core/services/vrf/v1/integration_test.go @@ -233,7 +233,8 @@ func TestIntegration_VRF_WithBHS(t *testing.T) { } func createVRFJobRegisterKey(t *testing.T, u vrftesthelpers.CoordinatorUniverse, app *cltest.TestApplication, incomingConfs int) (job.Job, vrfkey.KeyV2) { - vrfKey, err := app.KeyStore.VRF().Create() + ctx := testutils.Context(t) + vrfKey, err := app.KeyStore.VRF().Create(ctx) require.NoError(t, err) jid := uuid.MustParse("96a8a26f-d426-4784-8d8f-fb387d4d8345") diff --git a/core/services/vrf/v2/integration_helpers_test.go b/core/services/vrf/v2/integration_helpers_test.go index 3d7a94ae833..2e0554fca96 100644 --- a/core/services/vrf/v2/integration_helpers_test.go +++ b/core/services/vrf/v2/integration_helpers_test.go @@ -1672,9 +1672,9 @@ func testMaliciousConsumer( app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, config, uni.backend, ownerKey) require.NoError(t, app.Start(ctx)) - err := app.GetKeyStore().Unlock(cltest.Password) + err := app.GetKeyStore().Unlock(ctx, cltest.Password) require.NoError(t, err) - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) jid := uuid.New() @@ -1796,7 +1796,7 @@ func testReplayOldRequestsOnStartUp( require.NoError(t, app.Start(ctx)) // Create VRF Key, register it to coordinator and export - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) registerProvingKeyHelper(t, uni, coordinator, vrfkey, &defaultMaxGasPrice) keyHash := vrfkey.PublicKey.MustHash() @@ -1833,7 +1833,7 @@ func testReplayOldRequestsOnStartUp( require.NoError(t, app.Start(ctx)) - vrfKey, err := app.GetKeyStore().VRF().Import(encodedVrfKey, testutils.Password) + vrfKey, err := app.GetKeyStore().VRF().Import(ctx, encodedVrfKey, testutils.Password) require.NoError(t, err) incomingConfs := 2 diff --git a/core/services/vrf/v2/integration_v2_plus_test.go b/core/services/vrf/v2/integration_v2_plus_test.go index 742ff99071c..b885473e488 100644 --- a/core/services/vrf/v2/integration_v2_plus_test.go +++ b/core/services/vrf/v2/integration_v2_plus_test.go @@ -847,6 +847,7 @@ func TestVRFV2PlusIntegration_TestMaliciousConsumer(t *testing.T) { } func TestVRFV2PlusIntegration_RequestCost(t *testing.T) { + ctx := testutils.Context(t) key := cltest.MustGenerateRandomKey(t) uni := newVRFCoordinatorV2PlusUniverse(t, key, 1, false) @@ -854,7 +855,7 @@ func TestVRFV2PlusIntegration_RequestCost(t *testing.T) { app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, cfg, uni.backend, key) require.NoError(t, app.Start(testutils.Context(t))) - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) registerProvingKeyHelper(t, uni.coordinatorV2UniverseCommon, uni.rootContract, vrfkey, &defaultMaxGasPrice) t.Run("non-proxied consumer", func(tt *testing.T) { @@ -1002,6 +1003,7 @@ func requestAndEstimateFulfillmentCost( } func TestVRFV2PlusIntegration_FulfillmentCost(t *testing.T) { + ctx := testutils.Context(t) key := cltest.MustGenerateRandomKey(t) uni := newVRFCoordinatorV2PlusUniverse(t, key, 1, false) @@ -1009,7 +1011,7 @@ func TestVRFV2PlusIntegration_FulfillmentCost(t *testing.T) { app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, cfg, uni.backend, key) require.NoError(t, app.Start(testutils.Context(t))) - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) registerProvingKeyHelper(t, uni.coordinatorV2UniverseCommon, uni.rootContract, vrfkey, &defaultMaxGasPrice) diff --git a/core/services/vrf/v2/integration_v2_reverted_txns_test.go b/core/services/vrf/v2/integration_v2_reverted_txns_test.go index b8e6f5f9b05..dfee450b6a2 100644 --- a/core/services/vrf/v2/integration_v2_reverted_txns_test.go +++ b/core/services/vrf/v2/integration_v2_reverted_txns_test.go @@ -411,6 +411,7 @@ func createVRFJobsNew( chainID *big.Int, gasLanePrices ...*assets.Wei, ) (jobs []job.Job, vrfKeyIDs []string) { + ctx := testutils.Context(t) if len(gasLanePrices) != len(fromKeys) { t.Fatalf("must provide one gas lane price for each set of from addresses. len(gasLanePrices) != len(fromKeys) [%d != %d]", len(gasLanePrices), len(fromKeys)) @@ -422,7 +423,7 @@ func createVRFJobsNew( keyStrs = append(keyStrs, k.Address.String()) } - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) jid := uuid.New() diff --git a/core/services/vrf/v2/integration_v2_test.go b/core/services/vrf/v2/integration_v2_test.go index 0c81c3faca5..543ec943527 100644 --- a/core/services/vrf/v2/integration_v2_test.go +++ b/core/services/vrf/v2/integration_v2_test.go @@ -531,6 +531,7 @@ func createVRFJobs( batchEnabled bool, gasLanePrices ...*assets.Wei, ) (jobs []job.Job) { + ctx := testutils.Context(t) if len(gasLanePrices) != len(fromKeys) { t.Fatalf("must provide one gas lane price for each set of from addresses. len(gasLanePrices) != len(fromKeys) [%d != %d]", len(gasLanePrices), len(fromKeys)) @@ -542,7 +543,7 @@ func createVRFJobs( keyStrs = append(keyStrs, k.Address.String()) } - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) jid := uuid.New() @@ -1838,6 +1839,7 @@ func TestMaliciousConsumer(t *testing.T) { } func TestRequestCost(t *testing.T) { + ctx := testutils.Context(t) key := cltest.MustGenerateRandomKey(t) uni := newVRFCoordinatorV2Universe(t, key, 1) @@ -1845,7 +1847,7 @@ func TestRequestCost(t *testing.T) { app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, cfg, uni.backend, key) require.NoError(t, app.Start(testutils.Context(t))) - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) registerProvingKeyHelper(t, uni.coordinatorV2UniverseCommon, uni.rootContract, vrfkey, nil) t.Run("non-proxied consumer", func(tt *testing.T) { @@ -1943,6 +1945,7 @@ func TestMaxConsumersCost(t *testing.T) { } func TestFulfillmentCost(t *testing.T) { + ctx := testutils.Context(t) key := cltest.MustGenerateRandomKey(t) uni := newVRFCoordinatorV2Universe(t, key, 1) @@ -1950,7 +1953,7 @@ func TestFulfillmentCost(t *testing.T) { app := cltest.NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(t, cfg, uni.backend, key) require.NoError(t, app.Start(testutils.Context(t))) - vrfkey, err := app.GetKeyStore().VRF().Create() + vrfkey, err := app.GetKeyStore().VRF().Create(ctx) require.NoError(t, err) registerProvingKeyHelper(t, uni.coordinatorV2UniverseCommon, uni.rootContract, vrfkey, nil) @@ -2050,7 +2053,7 @@ func TestStartingCountsV1(t *testing.T) { ctx := testutils.Context(t) lggr := logger.TestLogger(t) txStore := txmgr.NewTxStore(db, logger.TestLogger(t)) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg.Database()) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) ec := evmclimocks.NewClient(t) ec.On("ConfiguredChainID").Return(testutils.SimulatedChainID) ec.On("LatestBlockHeight", mock.Anything).Return(big.NewInt(2), nil).Maybe() @@ -2067,7 +2070,7 @@ func TestStartingCountsV1(t *testing.T) { counts, err = listenerV1.GetStartingResponseCountsV1(testutils.Context(t)) require.NoError(t, err) assert.Equal(t, 0, len(counts)) - err = ks.Unlock(testutils.Password) + err = ks.Unlock(ctx, testutils.Password) require.NoError(t, err) k, err := ks.Eth().Create(testutils.Context(t), testutils.SimulatedChainID) require.NoError(t, err) diff --git a/core/services/vrf/v2/listener_v2_log_listener_test.go b/core/services/vrf/v2/listener_v2_log_listener_test.go index 15b0a5ecbe8..a393aec3ee3 100644 --- a/core/services/vrf/v2/listener_v2_log_listener_test.go +++ b/core/services/vrf/v2/listener_v2_log_listener_test.go @@ -64,6 +64,7 @@ func setupVRFLogPollerListenerTH(t *testing.T, finalityDepth, backfillBatchSize, rpcBatchSize, keepFinalizedBlocksDepth int64, mockChainUpdateFn func(*evmmocks.Chain, *vrfLogPollerListenerTH)) *vrfLogPollerListenerTH { + ctx := testutils.Context(t) lggr := logger.TestLogger(t) chainID := testutils.NewRandomEVMChainID() @@ -111,9 +112,8 @@ func setupVRFLogPollerListenerTH(t *testing.T, ec.Commit() // Log Poller Listener - cfg := pgtest.NewQConfig(false) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg) - require.NoError(t, ks.Unlock("blah")) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, "blah")) j, err := vrfcommon.ValidatedVRFSpec(testspecs.GenerateVRFSpec(testspecs.VRFSpecParams{ RequestedConfsDelay: 10, EVMChainID: chainID.String(), @@ -134,7 +134,6 @@ func setupVRFLogPollerListenerTH(t *testing.T, inflightCache: vrfcommon.NewInflightCache(10), chStop: make(chan struct{}), } - ctx := testutils.Context(t) // Filter registration is idempotent, so we can just call it every time // and retry on errors using the ticker. diff --git a/core/services/vrf/v2/listener_v2_test.go b/core/services/vrf/v2/listener_v2_test.go index 4e9e65bfafc..ac59f1fdb69 100644 --- a/core/services/vrf/v2/listener_v2_test.go +++ b/core/services/vrf/v2/listener_v2_test.go @@ -180,11 +180,11 @@ func addConfirmedEthTxNativePayment(t *testing.T, txStore txmgr.TestEvmTxStore, } func testMaybeSubtractReservedLink(t *testing.T, vrfVersion vrfcommon.Version) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) lggr := logger.TestLogger(t) - cfg := pgtest.NewQConfig(false) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg) - require.NoError(t, ks.Unlock("blah")) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, "blah")) chainID := testutils.SimulatedChainID k, err := ks.Eth().Create(testutils.Context(t), chainID) require.NoError(t, err) @@ -206,8 +206,6 @@ func testMaybeSubtractReservedLink(t *testing.T, vrfVersion vrfcommon.Version) { chain: chain, } - ctx := testutils.Context(t) - // Insert an unstarted eth tx with link metadata addEthTx(t, txstore, k.Address, txmgrcommon.TxUnstarted, "10000", subID, reqTxHash, vrfVersion) start, err := listener.MaybeSubtractReservedLink(ctx, big.NewInt(100_000), chainID, subID, vrfVersion) @@ -262,11 +260,11 @@ func TestMaybeSubtractReservedLinkV2Plus(t *testing.T) { } func testMaybeSubtractReservedNative(t *testing.T, vrfVersion vrfcommon.Version) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) lggr := logger.TestLogger(t) - cfg := pgtest.NewQConfig(false) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg) - require.NoError(t, ks.Unlock("blah")) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, "blah")) chainID := testutils.SimulatedChainID k, err := ks.Eth().Create(testutils.Context(t), chainID) require.NoError(t, err) @@ -289,8 +287,6 @@ func testMaybeSubtractReservedNative(t *testing.T, vrfVersion vrfcommon.Version) chain: chain, } - ctx := testutils.Context(t) - // Insert an unstarted eth tx with native metadata addEthTxNativePayment(t, txstore, k.Address, txmgrcommon.TxUnstarted, "10000", subID, reqTxHash, vrfVersion) start, err := listener.MaybeSubtractReservedEth(ctx, big.NewInt(100_000), chainID, subID, vrfVersion) @@ -341,11 +337,11 @@ func TestMaybeSubtractReservedNativeV2Plus(t *testing.T) { } func TestMaybeSubtractReservedNativeV2(t *testing.T) { + ctx := testutils.Context(t) db := pgtest.NewSqlxDB(t) lggr := logger.TestLogger(t) - cfg := pgtest.NewQConfig(false) - ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr, cfg) - require.NoError(t, ks.Unlock("blah")) + ks := keystore.NewInMemory(db, utils.FastScryptParams, lggr) + require.NoError(t, ks.Unlock(ctx, "blah")) chainID := testutils.SimulatedChainID subID := new(big.Int).SetUint64(1) diff --git a/core/services/workflows/engine.go b/core/services/workflows/engine.go index f6b8c63ed15..4694ca4286f 100644 --- a/core/services/workflows/engine.go +++ b/core/services/workflows/engine.go @@ -183,10 +183,17 @@ func (e *Engine) registerTrigger(ctx context.Context, t *triggerCapability) erro Config: tc, Inputs: triggerInputs, } - err = t.trigger.RegisterTrigger(ctx, e.triggerEvents, triggerRegRequest) + eventsCh, err := t.trigger.RegisterTrigger(ctx, triggerRegRequest) if err != nil { return fmt.Errorf("failed to instantiate trigger %s, %s", t.Type, err) } + + go func() { + for event := range eventsCh { + e.triggerEvents <- event + } + }() + return nil } @@ -212,7 +219,12 @@ func (e *Engine) loop(ctx context.Context) { case <-ctx.Done(): e.logger.Debugw("shutting down loop") return - case resp := <-e.triggerEvents: + case resp, isOpen := <-e.triggerEvents: + if !isOpen { + e.logger.Errorf("trigger events channel is no longer open, skipping") + continue + } + if resp.Err != nil { e.logger.Errorf("trigger event was an error; not executing", resp.Err) continue diff --git a/core/services/workflows/engine_test.go b/core/services/workflows/engine_test.go index edb924f9874..7bb6cd00c1c 100644 --- a/core/services/workflows/engine_test.go +++ b/core/services/workflows/engine_test.go @@ -79,16 +79,18 @@ func newMockCapability(info capabilities.CapabilityInfo, transform func(capabili } } -func (m *mockCapability) Execute(ctx context.Context, ch chan<- capabilities.CapabilityResponse, req capabilities.CapabilityRequest) error { +func (m *mockCapability) Execute(ctx context.Context, req capabilities.CapabilityRequest) (<-chan capabilities.CapabilityResponse, error) { cr, err := m.transform(req) if err != nil { - return err + return nil, err } + ch := make(chan capabilities.CapabilityResponse, 10) + + m.response <- cr ch <- cr close(ch) - m.response <- cr - return nil + return ch, nil } func (m *mockCapability) RegisterToWorkflow(ctx context.Context, request capabilities.RegisterToWorkflowRequest) error { @@ -102,13 +104,14 @@ func (m *mockCapability) UnregisterFromWorkflow(ctx context.Context, request cap type mockTriggerCapability struct { capabilities.CapabilityInfo triggerEvent capabilities.CapabilityResponse + ch chan capabilities.CapabilityResponse } var _ capabilities.TriggerCapability = (*mockTriggerCapability)(nil) -func (m *mockTriggerCapability) RegisterTrigger(ctx context.Context, ch chan<- capabilities.CapabilityResponse, req capabilities.CapabilityRequest) error { - ch <- m.triggerEvent - return nil +func (m *mockTriggerCapability) RegisterTrigger(ctx context.Context, req capabilities.CapabilityRequest) (<-chan capabilities.CapabilityResponse, error) { + m.ch <- m.triggerEvent + return m.ch, nil } func (m *mockTriggerCapability) UnregisterTrigger(ctx context.Context, req capabilities.CapabilityRequest) error { @@ -217,6 +220,7 @@ func mockTrigger(t *testing.T) (capabilities.TriggerCapability, capabilities.Cap "issues a trigger when a mercury report is received.", "v1.0.0", ), + ch: make(chan capabilities.CapabilityResponse, 10), } resp, err := values.NewMap(map[string]any{ "123": decimal.NewFromFloat(1.00), diff --git a/core/web/build_info_controller_test.go b/core/web/build_info_controller_test.go index 5a2b88fa0dc..05ae421bf23 100644 --- a/core/web/build_info_controller_test.go +++ b/core/web/build_info_controller_test.go @@ -5,18 +5,19 @@ import ( "strings" "testing" + "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" clhttptest "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/httptest" - - "github.com/stretchr/testify/require" ) func TestBuildInfoController_Show_APICredentials(t *testing.T) { t.Parallel() app := cltest.NewApplicationEVMDisabled(t) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) @@ -32,8 +33,8 @@ func TestBuildInfoController_Show_APICredentials(t *testing.T) { func TestBuildInfoController_Show_NoCredentials(t *testing.T) { t.Parallel() - ctx := testutils.Context(t) app := cltest.NewApplicationEVMDisabled(t) + ctx := testutils.Context(t) require.NoError(t, app.Start(ctx)) client := clhttptest.NewTestLocalOnlyHTTPClient() diff --git a/core/web/cosmos_chains_controller_test.go b/core/web/cosmos_chains_controller_test.go index 5491b33c359..9aaa0dd9eeb 100644 --- a/core/web/cosmos_chains_controller_test.go +++ b/core/web/cosmos_chains_controller_test.go @@ -182,7 +182,8 @@ func setupCosmosChainsControllerTestV2(t *testing.T, cfgs ...*coscfg.TOMLConfig) c.EVM = nil }) app := cltest.NewApplicationWithConfig(t, cfg) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) diff --git a/core/web/cosmos_keys_controller_test.go b/core/web/cosmos_keys_controller_test.go index 3b777de7b7c..1de64625dfa 100644 --- a/core/web/cosmos_keys_controller_test.go +++ b/core/web/cosmos_keys_controller_test.go @@ -40,7 +40,8 @@ func TestCosmosKeysController_Create_HappyPath(t *testing.T) { t.Parallel() app := cltest.NewApplicationEVMDisabled(t) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) keyStore := app.GetKeyStore() @@ -75,12 +76,13 @@ func TestCosmosKeysController_Delete_NonExistentCosmosKeyID(t *testing.T) { func TestCosmosKeysController_Delete_HappyPath(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) client, keyStore := setupCosmosKeysControllerTests(t) keys, _ := keyStore.Cosmos().GetAll() initialLength := len(keys) - key, _ := keyStore.Cosmos().Create() + key, _ := keyStore.Cosmos().Create(ctx) response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/cosmos/%s", key.ID())) t.Cleanup(cleanup) @@ -93,10 +95,11 @@ func TestCosmosKeysController_Delete_HappyPath(t *testing.T) { func setupCosmosKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { t.Helper() + ctx := testutils.Context(t) app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.Cosmos().Add(cltest.DefaultCosmosKey)) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.Cosmos().Add(ctx, cltest.DefaultCosmosKey)) client := app.NewHTTPClient(nil) diff --git a/core/web/csa_keys_controller.go b/core/web/csa_keys_controller.go index fc927c61b3c..f97e5751df0 100644 --- a/core/web/csa_keys_controller.go +++ b/core/web/csa_keys_controller.go @@ -34,7 +34,8 @@ func (ctrl *CSAKeysController) Index(c *gin.Context) { // Example: // "POST /keys/csa" func (ctrl *CSAKeysController) Create(c *gin.Context) { - key, err := ctrl.App.GetKeyStore().CSA().Create() + ctx := c.Request.Context() + key, err := ctrl.App.GetKeyStore().CSA().Create(ctx) if err != nil { if errors.Is(err, keystore.ErrCSAKeyExists) { jsonAPIError(c, http.StatusBadRequest, err) @@ -56,6 +57,7 @@ func (ctrl *CSAKeysController) Create(c *gin.Context) { // Import imports a CSA key func (ctrl *CSAKeysController) Import(c *gin.Context) { defer ctrl.App.GetLogger().ErrorIfFn(c.Request.Body.Close, "Error closing Import request body") + ctx := c.Request.Context() bytes, err := io.ReadAll(c.Request.Body) if err != nil { @@ -63,7 +65,7 @@ func (ctrl *CSAKeysController) Import(c *gin.Context) { return } oldPassword := c.Query("oldpassword") - key, err := ctrl.App.GetKeyStore().CSA().Import(bytes, oldPassword) + key, err := ctrl.App.GetKeyStore().CSA().Import(ctx, bytes, oldPassword) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return diff --git a/core/web/dkgencrypt_keys_controller_test.go b/core/web/dkgencrypt_keys_controller_test.go index 7100cbbb1cd..fde00eb6420 100644 --- a/core/web/dkgencrypt_keys_controller_test.go +++ b/core/web/dkgencrypt_keys_controller_test.go @@ -100,8 +100,9 @@ func setupDKGEncryptKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, t.Helper() app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.DKGEncrypt().Add(cltest.DefaultDKGEncryptKey)) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.DKGEncrypt().Add(ctx, cltest.DefaultDKGEncryptKey)) client := app.NewHTTPClient(nil) diff --git a/core/web/dkgsign_keys_controller_test.go b/core/web/dkgsign_keys_controller_test.go index ed67d71a0d5..b253a36ccc3 100644 --- a/core/web/dkgsign_keys_controller_test.go +++ b/core/web/dkgsign_keys_controller_test.go @@ -100,8 +100,9 @@ func setupDKGSignKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, ke t.Helper() app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.DKGSign().Add(cltest.DefaultDKGSignKey)) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.DKGSign().Add(ctx, cltest.DefaultDKGSignKey)) client := app.NewHTTPClient(nil) diff --git a/core/web/eth_keys_controller_test.go b/core/web/eth_keys_controller_test.go index bab987fbcc2..09a3eb5fa1e 100644 --- a/core/web/eth_keys_controller_test.go +++ b/core/web/eth_keys_controller_test.go @@ -30,6 +30,7 @@ import ( func TestETHKeysController_Index_Success(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -39,7 +40,7 @@ func TestETHKeysController_Index_Success(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // enabled key k0, addr0 := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) @@ -55,7 +56,7 @@ func TestETHKeysController_Index_Success(t *testing.T) { ethClient.On("LINKBalance", mock.Anything, addr1, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() ethClient.On("LINKBalance", mock.Anything, addr2, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) resp, cleanup := client.Get("/v2/keys/evm") @@ -83,6 +84,7 @@ func TestETHKeysController_Index_Success(t *testing.T) { func TestETHKeysController_Index_Errors(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -92,14 +94,14 @@ func TestETHKeysController_Index_Errors(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) _, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) ethClient.On("BalanceAt", mock.Anything, addr, mock.Anything).Return(nil, errors.New("fake error")).Once() ethClient.On("LINKBalance", mock.Anything, addr, mock.Anything).Return(nil, errors.New("fake error")).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) resp, cleanup := client.Get("/v2/keys/eth") @@ -121,6 +123,7 @@ func TestETHKeysController_Index_Errors(t *testing.T) { func TestETHKeysController_Index_Disabled(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -129,11 +132,11 @@ func TestETHKeysController_Index_Disabled(t *testing.T) { app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) _, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) resp, cleanup := client.Get("/v2/keys/eth") @@ -168,7 +171,8 @@ func TestETHKeysController_Index_NotDev(t *testing.T) { ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(assets.NewLinkFromJuels(256), nil).Once() app := cltest.NewApplicationWithConfigAndKey(t, cfg, ethClient) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) resp, cleanup := client.Get("/v2/keys/eth") @@ -193,7 +197,8 @@ func TestETHKeysController_Index_NoAccounts(t *testing.T) { t.Parallel() app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) @@ -227,7 +232,8 @@ func TestETHKeysController_CreateSuccess(t *testing.T) { client := app.NewHTTPClient(nil) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) chainURL := url.URL{Path: "/v2/keys/evm"} query := chainURL.Query() @@ -250,6 +256,7 @@ func TestETHKeysController_CreateSuccess(t *testing.T) { func TestETHKeysController_ChainSuccess_UpdateNonce(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -258,7 +265,7 @@ func TestETHKeysController_ChainSuccess_UpdateNonce(t *testing.T) { c.EVM[0].BalanceMonitor.Enabled = ptr(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // enabled key key, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) @@ -266,7 +273,7 @@ func TestETHKeysController_ChainSuccess_UpdateNonce(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, addr, mock.Anything).Return(big.NewInt(1), nil).Once() ethClient.On("LINKBalance", mock.Anything, addr, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -292,6 +299,7 @@ func TestETHKeysController_ChainSuccess_UpdateNonce(t *testing.T) { func TestETHKeysController_ChainSuccess_Disable(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -301,7 +309,7 @@ func TestETHKeysController_ChainSuccess_Disable(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // enabled key key, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) @@ -309,7 +317,7 @@ func TestETHKeysController_ChainSuccess_Disable(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, addr, mock.Anything).Return(big.NewInt(1), nil).Once() ethClient.On("LINKBalance", mock.Anything, addr, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -337,6 +345,7 @@ func TestETHKeysController_ChainSuccess_Disable(t *testing.T) { func TestETHKeysController_ChainSuccess_Enable(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -345,7 +354,7 @@ func TestETHKeysController_ChainSuccess_Enable(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // disabled key key, addr := cltest.RandomKey{Disabled: true}.MustInsert(t, app.KeyStore.Eth()) @@ -353,7 +362,7 @@ func TestETHKeysController_ChainSuccess_Enable(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, addr, mock.Anything).Return(big.NewInt(1), nil).Once() ethClient.On("LINKBalance", mock.Anything, addr, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -381,6 +390,7 @@ func TestETHKeysController_ChainSuccess_Enable(t *testing.T) { func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -390,7 +400,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // enabled key key, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) @@ -398,7 +408,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, addr, mock.Anything).Return(big.NewInt(1), nil).Once() ethClient.On("LINKBalance", mock.Anything, addr, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) chain := app.GetRelayers().LegacyEVMChains().Slice()[0] subject := uuid.New() @@ -454,6 +464,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { func TestETHKeysController_ChainFailure_InvalidAbandon(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -466,9 +477,9 @@ func TestETHKeysController_ChainFailure_InvalidAbandon(t *testing.T) { // enabled key _, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -487,6 +498,7 @@ func TestETHKeysController_ChainFailure_InvalidAbandon(t *testing.T) { func TestETHKeysController_ChainFailure_InvalidEnabled(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -499,9 +511,9 @@ func TestETHKeysController_ChainFailure_InvalidEnabled(t *testing.T) { // enabled key _, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -520,6 +532,7 @@ func TestETHKeysController_ChainFailure_InvalidEnabled(t *testing.T) { func TestETHKeysController_ChainFailure_InvalidAddress(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -528,9 +541,9 @@ func TestETHKeysController_ChainFailure_InvalidAddress(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -548,6 +561,7 @@ func TestETHKeysController_ChainFailure_InvalidAddress(t *testing.T) { func TestETHKeysController_ChainFailure_MissingAddress(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -556,9 +570,9 @@ func TestETHKeysController_ChainFailure_MissingAddress(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -576,6 +590,7 @@ func TestETHKeysController_ChainFailure_MissingAddress(t *testing.T) { func TestETHKeysController_ChainFailure_InvalidChainID(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -584,9 +599,9 @@ func TestETHKeysController_ChainFailure_InvalidChainID(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -604,6 +619,7 @@ func TestETHKeysController_ChainFailure_InvalidChainID(t *testing.T) { func TestETHKeysController_ChainFailure_MissingChainID(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) @@ -613,12 +629,12 @@ func TestETHKeysController_ChainFailure_MissingChainID(t *testing.T) { }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // enabled key _, addr := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/chain"} @@ -636,6 +652,7 @@ func TestETHKeysController_ChainFailure_MissingChainID(t *testing.T) { func TestETHKeysController_DeleteSuccess(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -643,7 +660,7 @@ func TestETHKeysController_DeleteSuccess(t *testing.T) { c.EVM[0].BalanceMonitor.Enabled = ptr(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) // enabled keys key0, addr0 := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) @@ -654,7 +671,7 @@ func TestETHKeysController_DeleteSuccess(t *testing.T) { ethClient.On("LINKBalance", mock.Anything, addr0, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() ethClient.On("LINKBalance", mock.Anything, addr1, mock.Anything).Return(assets.NewLinkFromJuels(1), nil).Once() - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/" + addr0.Hex()} @@ -688,15 +705,16 @@ func TestETHKeysController_DeleteSuccess(t *testing.T) { func TestETHKeysController_DeleteFailure_InvalidAddress(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].NonceAutoSync = ptr(false) c.EVM[0].BalanceMonitor.Enabled = ptr(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm" + "/bad_address"} @@ -709,15 +727,16 @@ func TestETHKeysController_DeleteFailure_InvalidAddress(t *testing.T) { func TestETHKeysController_DeleteFailure_KeyMissing(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].NonceAutoSync = ptr(false) c.EVM[0].BalanceMonitor.Enabled = ptr(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) - require.NoError(t, app.KeyStore.Unlock(cltest.Password)) + require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) - require.NoError(t, app.Start(testutils.Context(t))) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) chainURL := url.URL{Path: "/v2/keys/evm/" + testutils.NewAddress().Hex()} diff --git a/core/web/evm_chains_controller_test.go b/core/web/evm_chains_controller_test.go index 5d31374cfb7..157978bdd46 100644 --- a/core/web/evm_chains_controller_test.go +++ b/core/web/evm_chains_controller_test.go @@ -202,7 +202,8 @@ func setupEVMChainsControllerTest(t *testing.T, cfg chainlink.GeneralConfig) *Te // Using this instead of `NewApplicationEVMDisabled` since we need the chain set to be loaded in the app // for the sake of the API endpoints to work properly app := cltest.NewApplicationWithConfig(t, cfg) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) diff --git a/core/web/evm_forwarders_controller_test.go b/core/web/evm_forwarders_controller_test.go index 031a1a61c03..38e8c2f91f0 100644 --- a/core/web/evm_forwarders_controller_test.go +++ b/core/web/evm_forwarders_controller_test.go @@ -30,7 +30,8 @@ func setupEVMForwardersControllerTest(t *testing.T, overrideFn func(c *chainlink // Using this instead of `NewApplicationEVMDisabled` since we need the chain set to be loaded in the app // for the sake of the API endpoints to work properly app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, overrideFn)) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) diff --git a/core/web/evm_transactions_controller_test.go b/core/web/evm_transactions_controller_test.go index e6d186fbab3..a4dd21c9f03 100644 --- a/core/web/evm_transactions_controller_test.go +++ b/core/web/evm_transactions_controller_test.go @@ -22,12 +22,12 @@ func TestTransactionsController_Index_Success(t *testing.T) { t.Parallel() app := cltest.NewApplicationWithKey(t) - require.NoError(t, app.Start(testutils.Context(t))) ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) db := app.GetSqlxDB() txStore := cltest.NewTestTxStore(t, app.GetSqlxDB()) - ethKeyStore := cltest.NewKeyStore(t, db, app.Config.Database()).Eth() + ethKeyStore := cltest.NewKeyStore(t, db).Eth() client := app.NewHTTPClient(nil) _, from := cltest.MustInsertRandomKey(t, ethKeyStore) @@ -68,7 +68,8 @@ func TestTransactionsController_Index_Error(t *testing.T) { t.Parallel() app := cltest.NewApplicationWithKey(t) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) resp, cleanup := client.Get("/v2/transactions?size=TrainingDay") @@ -80,7 +81,8 @@ func TestTransactionsController_Show_Success(t *testing.T) { t.Parallel() app := cltest.NewApplicationWithKey(t) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) txStore := cltest.NewTestTxStore(t, app.GetSqlxDB()) client := app.NewHTTPClient(nil) @@ -113,7 +115,8 @@ func TestTransactionsController_Show_NotFound(t *testing.T) { t.Parallel() app := cltest.NewApplicationWithKey(t) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) txStore := cltest.NewTestTxStore(t, app.GetSqlxDB()) client := app.NewHTTPClient(nil) diff --git a/core/web/jobs_controller_test.go b/core/web/jobs_controller_test.go index 5255cad75f3..9c7b529b6bf 100644 --- a/core/web/jobs_controller_test.go +++ b/core/web/jobs_controller_test.go @@ -77,6 +77,7 @@ func TestJobsController_Create_ValidationFailure_OffchainReportingSpec(t *testin } for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { + ctx := testutils.Context(t) ta, client := setupJobsControllerTests(t) var address types.EIP55Address @@ -87,7 +88,7 @@ func TestJobsController_Create_ValidationFailure_OffchainReportingSpec(t *testin address = cltest.NewEIP55Address() } - require.NoError(t, ta.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, ta.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) sp := cltest.MinimalOCRNonBootstrapSpec(contractAddress, address, tc.pid, tc.kb) body, _ := json.Marshal(web.CreateJobRequest{ @@ -104,8 +105,9 @@ func TestJobsController_Create_ValidationFailure_OffchainReportingSpec(t *testin } func TestJobController_Create_DirectRequest_Fast(t *testing.T) { + ctx := testutils.Context(t) app, client := setupJobsControllerTests(t) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) n := 10 @@ -137,9 +139,10 @@ func mustInt32FromString(t *testing.T, s string) int32 { } func TestJobController_Create_HappyPath(t *testing.T) { + ctx := testutils.Context(t) app, client := setupJobsControllerTests(t) b1, b2 := setupBridges(t, app.GetSqlxDB(), app.GetConfig().Database()) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) var pks []vrfkey.KeyV2 var k []p2pkey.KeyV2 { @@ -477,7 +480,6 @@ targets: func TestJobsController_Create_WebhookSpec(t *testing.T) { app := cltest.NewApplicationEVMDisabled(t) require.NoError(t, app.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, app.Stop()) }) _, fetchBridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) _, submitBridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) @@ -608,6 +610,7 @@ func TestJobsController_Show_NonExistentID(t *testing.T) { } func TestJobsController_Update_HappyPath(t *testing.T) { + ctx := testutils.Context(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.OCR.Enabled = ptr(true) c.P2P.V2.Enabled = ptr(true) @@ -616,7 +619,7 @@ func TestJobsController_Update_HappyPath(t *testing.T) { }) app := cltest.NewApplicationWithConfigAndKey(t, cfg, cltest.DefaultP2PKey) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) require.NoError(t, app.Start(testutils.Context(t))) _, bridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) @@ -680,7 +683,7 @@ func TestJobsController_Update_NonExistentID(t *testing.T) { }) app := cltest.NewApplicationWithConfigAndKey(t, cfg, cltest.DefaultP2PKey) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) require.NoError(t, app.Start(ctx)) _, bridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) @@ -766,11 +769,12 @@ func setupJobsControllerTests(t *testing.T) (ta *cltest.TestApplication, cc clte }) ec := setupEthClientForControllerTests(t) app := cltest.NewApplicationWithConfigAndKey(t, cfg, cltest.DefaultP2PKey, ec) - require.NoError(t, app.Start(testutils.Context(t))) + ctx := testutils.Context(t) + require.NoError(t, app.Start(ctx)) client := app.NewHTTPClient(nil) vrfKeyStore := app.GetKeyStore().VRF() - _, err := vrfKeyStore.Create() + _, err := vrfKeyStore.Create(ctx) require.NoError(t, err) return app, client } @@ -793,7 +797,7 @@ func setupJobSpecsControllerTestsWithJobs(t *testing.T) (*cltest.TestApplication }) app := cltest.NewApplicationWithConfigAndKey(t, cfg, cltest.DefaultP2PKey) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) require.NoError(t, app.Start(ctx)) _, bridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}) diff --git a/core/web/keys_controller.go b/core/web/keys_controller.go index 66fd596e719..ca7ef5e134a 100644 --- a/core/web/keys_controller.go +++ b/core/web/keys_controller.go @@ -1,6 +1,7 @@ package web import ( + "context" "fmt" "io" "net/http" @@ -16,9 +17,9 @@ import ( type Keystore[K keystore.Key] interface { Get(id string) (K, error) GetAll() ([]K, error) - Create() (K, error) - Delete(id string) (K, error) - Import(keyJSON []byte, password string) (K, error) + Create(context.Context) (K, error) + Delete(ctx context.Context, id string) (K, error) + Import(ctx context.Context, keyJSON []byte, password string) (K, error) Export(id string, password string) ([]byte, error) } @@ -73,7 +74,8 @@ func (kc *keysController[K, R]) Index(c *gin.Context) { } func (kc *keysController[K, R]) Create(c *gin.Context) { - key, err := kc.ks.Create() + ctx := c.Request.Context() + key, err := kc.ks.Create(ctx) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -88,13 +90,14 @@ func (kc *keysController[K, R]) Create(c *gin.Context) { } func (kc *keysController[K, R]) Delete(c *gin.Context) { + ctx := c.Request.Context() keyID := c.Param("keyID") key, err := kc.ks.Get(keyID) if err != nil { jsonAPIError(c, http.StatusNotFound, err) return } - _, err = kc.ks.Delete(key.ID()) + _, err = kc.ks.Delete(ctx, key.ID()) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -110,6 +113,7 @@ func (kc *keysController[K, R]) Delete(c *gin.Context) { func (kc *keysController[K, R]) Import(c *gin.Context) { defer kc.lggr.ErrorIfFn(c.Request.Body.Close, "Error closing Import request body") + ctx := c.Request.Context() bytes, err := io.ReadAll(c.Request.Body) if err != nil { @@ -117,7 +121,7 @@ func (kc *keysController[K, R]) Import(c *gin.Context) { return } oldPassword := c.Query("oldpassword") - key, err := kc.ks.Import(bytes, oldPassword) + key, err := kc.ks.Import(ctx, bytes, oldPassword) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return diff --git a/core/web/loop_registry_test.go b/core/web/loop_registry_test.go index 93eda32d0e8..f6c71faca50 100644 --- a/core/web/loop_registry_test.go +++ b/core/web/loop_registry_test.go @@ -62,6 +62,7 @@ func (m *mockLoopImpl) run() { } func TestLoopRegistry(t *testing.T) { + ctx := testutils.Context(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.OCR.Enabled = ptr(true) c.P2P.V2.Enabled = ptr(true) @@ -80,7 +81,7 @@ func TestLoopRegistry(t *testing.T) { model.LabelSet{"__metrics_path__": model.LabelValue(expectedLooppEndPoint)}, } - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) require.NoError(t, app.Start(testutils.Context(t))) // register a mock loop diff --git a/core/web/ocr2_keys_controller.go b/core/web/ocr2_keys_controller.go index 22109e90cba..2c4fcd19203 100644 --- a/core/web/ocr2_keys_controller.go +++ b/core/web/ocr2_keys_controller.go @@ -34,8 +34,9 @@ func (ocr2kc *OCR2KeysController) Index(c *gin.Context) { // Example: // "POST /keys/ocr" func (ocr2kc *OCR2KeysController) Create(c *gin.Context) { + ctx := c.Request.Context() chainType := chaintype.ChainType(c.Param("chainType")) - key, err := ocr2kc.App.GetKeyStore().OCR2().Create(chainType) + key, err := ocr2kc.App.GetKeyStore().OCR2().Create(ctx, chainType) if errors.Is(errors.Cause(err), chaintype.ErrInvalidChainType) { jsonAPIError(c, http.StatusBadRequest, err) return @@ -60,13 +61,14 @@ func (ocr2kc *OCR2KeysController) Create(c *gin.Context) { // Example: // "DELETE /keys/ocr/:keyID" func (ocr2kc *OCR2KeysController) Delete(c *gin.Context) { + ctx := c.Request.Context() id := c.Param("keyID") key, err := ocr2kc.App.GetKeyStore().OCR2().Get(id) if err != nil { jsonAPIError(c, http.StatusNotFound, err) return } - err = ocr2kc.App.GetKeyStore().OCR2().Delete(id) + err = ocr2kc.App.GetKeyStore().OCR2().Delete(ctx, id) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -81,6 +83,7 @@ func (ocr2kc *OCR2KeysController) Delete(c *gin.Context) { // "Post /keys/ocr/import" func (ocr2kc *OCR2KeysController) Import(c *gin.Context) { defer ocr2kc.App.GetLogger().ErrorIfFn(c.Request.Body.Close, "Error closing Import request body") + ctx := c.Request.Context() bytes, err := io.ReadAll(c.Request.Body) if err != nil { @@ -88,7 +91,7 @@ func (ocr2kc *OCR2KeysController) Import(c *gin.Context) { return } oldPassword := c.Query("oldpassword") - keyBundle, err := ocr2kc.App.GetKeyStore().OCR2().Import(bytes, oldPassword) + keyBundle, err := ocr2kc.App.GetKeyStore().OCR2().Import(ctx, bytes, oldPassword) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return diff --git a/core/web/ocr2_keys_controller_test.go b/core/web/ocr2_keys_controller_test.go index 815ae3ac20b..a8f480a1520 100644 --- a/core/web/ocr2_keys_controller_test.go +++ b/core/web/ocr2_keys_controller_test.go @@ -81,11 +81,12 @@ func TestOCR2KeysController_Delete_NonExistentOCRKeyID(t *testing.T) { } func TestOCR2KeysController_Delete_HappyPath(t *testing.T) { + ctx := testutils.Context(t) client, OCRKeyStore := setupOCR2KeysControllerTests(t) keys, _ := OCRKeyStore.GetAll() initialLength := len(keys) - key, _ := OCRKeyStore.Create("evm") + key, _ := OCRKeyStore.Create(ctx, "evm") response, cleanup := client.Delete("/v2/keys/ocr2/" + key.ID()) t.Cleanup(cleanup) @@ -98,12 +99,13 @@ func TestOCR2KeysController_Delete_HappyPath(t *testing.T) { func setupOCR2KeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.OCR2) { t.Parallel() + ctx := testutils.Context(t) app := cltest.NewApplicationEVMDisabled(t) require.NoError(t, app.Start(testutils.Context(t))) client := app.NewHTTPClient(nil) - require.NoError(t, app.KeyStore.OCR2().Add(cltest.DefaultOCR2Key)) + require.NoError(t, app.KeyStore.OCR2().Add(ctx, cltest.DefaultOCR2Key)) return client, app.GetKeyStore().OCR2() } diff --git a/core/web/ocr_keys_controller.go b/core/web/ocr_keys_controller.go index 12eaa76372c..9be5dbf33d9 100644 --- a/core/web/ocr_keys_controller.go +++ b/core/web/ocr_keys_controller.go @@ -32,7 +32,8 @@ func (ocrkc *OCRKeysController) Index(c *gin.Context) { // Example: // "POST /keys/ocr" func (ocrkc *OCRKeysController) Create(c *gin.Context) { - key, err := ocrkc.App.GetKeyStore().OCR().Create() + ctx := c.Request.Context() + key, err := ocrkc.App.GetKeyStore().OCR().Create(ctx) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -50,13 +51,14 @@ func (ocrkc *OCRKeysController) Create(c *gin.Context) { // "DELETE /keys/ocr/:keyID" // "DELETE /keys/ocr/:keyID?hard=true" func (ocrkc *OCRKeysController) Delete(c *gin.Context) { + ctx := c.Request.Context() id := c.Param("keyID") key, err := ocrkc.App.GetKeyStore().OCR().Get(id) if err != nil { jsonAPIError(c, http.StatusNotFound, err) return } - _, err = ocrkc.App.GetKeyStore().OCR().Delete(id) + _, err = ocrkc.App.GetKeyStore().OCR().Delete(ctx, id) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -71,6 +73,7 @@ func (ocrkc *OCRKeysController) Delete(c *gin.Context) { // "Post /keys/ocr/import" func (ocrkc *OCRKeysController) Import(c *gin.Context) { defer ocrkc.App.GetLogger().ErrorIfFn(c.Request.Body.Close, "Error closing Import request body") + ctx := c.Request.Context() bytes, err := io.ReadAll(c.Request.Body) if err != nil { @@ -78,7 +81,7 @@ func (ocrkc *OCRKeysController) Import(c *gin.Context) { return } oldPassword := c.Query("oldpassword") - encryptedOCRKeyBundle, err := ocrkc.App.GetKeyStore().OCR().Import(bytes, oldPassword) + encryptedOCRKeyBundle, err := ocrkc.App.GetKeyStore().OCR().Import(ctx, bytes, oldPassword) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return diff --git a/core/web/ocr_keys_controller_test.go b/core/web/ocr_keys_controller_test.go index 31422f47c0c..82a0b9ebc2d 100644 --- a/core/web/ocr_keys_controller_test.go +++ b/core/web/ocr_keys_controller_test.go @@ -69,11 +69,12 @@ func TestOCRKeysController_Delete_NonExistentOCRKeyID(t *testing.T) { } func TestOCRKeysController_Delete_HappyPath(t *testing.T) { + ctx := testutils.Context(t) client, OCRKeyStore := setupOCRKeysControllerTests(t) keys, _ := OCRKeyStore.GetAll() initialLength := len(keys) - key, _ := OCRKeyStore.Create() + key, _ := OCRKeyStore.Create(ctx) response, cleanup := client.Delete("/v2/keys/ocr/" + key.ID()) t.Cleanup(cleanup) @@ -86,12 +87,13 @@ func TestOCRKeysController_Delete_HappyPath(t *testing.T) { func setupOCRKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.OCR) { t.Parallel() + ctx := testutils.Context(t) app := cltest.NewApplicationEVMDisabled(t) require.NoError(t, app.Start(testutils.Context(t))) client := app.NewHTTPClient(nil) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) return client, app.GetKeyStore().OCR() } diff --git a/core/web/p2p_keys_controller.go b/core/web/p2p_keys_controller.go index bbe9d83f741..042f44b7bc5 100644 --- a/core/web/p2p_keys_controller.go +++ b/core/web/p2p_keys_controller.go @@ -35,7 +35,8 @@ const keyType = "Ed25519" // Example: // "POST /keys/p2p" func (p2pkc *P2PKeysController) Create(c *gin.Context) { - key, err := p2pkc.App.GetKeyStore().P2P().Create() + ctx := c.Request.Context() + key, err := p2pkc.App.GetKeyStore().P2P().Create(ctx) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -56,6 +57,7 @@ func (p2pkc *P2PKeysController) Create(c *gin.Context) { // "DELETE /keys/p2p/:keyID" // "DELETE /keys/p2p/:keyID?hard=true" func (p2pkc *P2PKeysController) Delete(c *gin.Context) { + ctx := c.Request.Context() keyID, err := p2pkey.MakePeerID(c.Param("keyID")) if err != nil { jsonAPIError(c, http.StatusUnprocessableEntity, err) @@ -66,7 +68,7 @@ func (p2pkc *P2PKeysController) Delete(c *gin.Context) { jsonAPIError(c, http.StatusNotFound, err) return } - _, err = p2pkc.App.GetKeyStore().P2P().Delete(key.PeerID()) + _, err = p2pkc.App.GetKeyStore().P2P().Delete(ctx, key.PeerID()) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -85,6 +87,7 @@ func (p2pkc *P2PKeysController) Delete(c *gin.Context) { // "Post /keys/p2p/import" func (p2pkc *P2PKeysController) Import(c *gin.Context) { defer p2pkc.App.GetLogger().ErrorIfFn(c.Request.Body.Close, "Error closing Import request body") + ctx := c.Request.Context() bytes, err := io.ReadAll(c.Request.Body) if err != nil { @@ -92,7 +95,7 @@ func (p2pkc *P2PKeysController) Import(c *gin.Context) { return } oldPassword := c.Query("oldpassword") - key, err := p2pkc.App.GetKeyStore().P2P().Import(bytes, oldPassword) + key, err := p2pkc.App.GetKeyStore().P2P().Import(ctx, bytes, oldPassword) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return diff --git a/core/web/p2p_keys_controller_test.go b/core/web/p2p_keys_controller_test.go index df6f556fcb8..63cea5f0ea7 100644 --- a/core/web/p2p_keys_controller_test.go +++ b/core/web/p2p_keys_controller_test.go @@ -91,12 +91,13 @@ func TestP2PKeysController_Delete_InvalidPeerID(t *testing.T) { func TestP2PKeysController_Delete_HappyPath(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) client, keyStore := setupP2PKeysControllerTests(t) keys, _ := keyStore.P2P().GetAll() initialLength := len(keys) - key, _ := keyStore.P2P().Create() + key, _ := keyStore.P2P().Create(ctx) response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/p2p/%s", key.ID())) t.Cleanup(cleanup) @@ -109,11 +110,12 @@ func TestP2PKeysController_Delete_HappyPath(t *testing.T) { func setupP2PKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { t.Helper() + ctx := testutils.Context(t) app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, app.KeyStore.P2P().Add(cltest.DefaultP2PKey)) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.P2P().Add(ctx, cltest.DefaultP2PKey)) client := app.NewHTTPClient(nil) diff --git a/core/web/pipeline_runs_controller_test.go b/core/web/pipeline_runs_controller_test.go index a270a0a92b8..f6b4291a34f 100644 --- a/core/web/pipeline_runs_controller_test.go +++ b/core/web/pipeline_runs_controller_test.go @@ -250,6 +250,7 @@ func TestPipelineRunsController_ShowRun_InvalidID(t *testing.T) { func setupPipelineRunsControllerTests(t *testing.T) (cltest.HTTPClientCleaner, int32, []int64) { t.Parallel() + ctx := testutils.Context(t) ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("PendingNonceAt", mock.Anything, mock.Anything).Return(uint64(0), nil) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { @@ -261,8 +262,8 @@ func setupPipelineRunsControllerTests(t *testing.T) (cltest.HTTPClientCleaner, i c.EVM[0].BalanceMonitor.Enabled = ptr(false) }) app := cltest.NewApplicationWithConfigAndKey(t, cfg, ethClient, cltest.DefaultP2PKey) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) client := app.NewHTTPClient(nil) key, _ := cltest.MustInsertRandomKey(t, app.KeyStore.Eth()) diff --git a/core/web/resolver/csa_keys_test.go b/core/web/resolver/csa_keys_test.go index a94a934efa3..1048d9aa4bc 100644 --- a/core/web/resolver/csa_keys_test.go +++ b/core/web/resolver/csa_keys_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" @@ -109,7 +110,7 @@ func Test_CreateCSAKey(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.csa.On("Create").Return(fakeKey, nil) + f.Mocks.csa.On("Create", mock.Anything).Return(fakeKey, nil) f.Mocks.keystore.On("CSA").Return(f.Mocks.csa) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -120,7 +121,7 @@ func Test_CreateCSAKey(t *testing.T) { name: "csa key exists error", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.csa.On("Create").Return(csakey.KeyV2{}, keystore.ErrCSAKeyExists) + f.Mocks.csa.On("Create", mock.Anything).Return(csakey.KeyV2{}, keystore.ErrCSAKeyExists) f.Mocks.keystore.On("CSA").Return(f.Mocks.csa) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -180,7 +181,7 @@ func Test_DeleteCSAKey(t *testing.T) { before: func(f *gqlTestFramework) { f.App.On("GetKeyStore").Return(f.Mocks.keystore) f.Mocks.keystore.On("CSA").Return(f.Mocks.csa) - f.Mocks.csa.On("Delete", fakeKey.ID()).Return(fakeKey, nil) + f.Mocks.csa.On("Delete", mock.Anything, fakeKey.ID()).Return(fakeKey, nil) }, query: query, variables: variables, @@ -193,7 +194,7 @@ func Test_DeleteCSAKey(t *testing.T) { f.App.On("GetKeyStore").Return(f.Mocks.keystore) f.Mocks.keystore.On("CSA").Return(f.Mocks.csa) f.Mocks.csa. - On("Delete", fakeKey.ID()). + On("Delete", mock.Anything, fakeKey.ID()). Return(csakey.KeyV2{}, keystore.KeyNotFoundError{ID: fakeKey.ID(), KeyType: "CSA"}) }, query: query, diff --git a/core/web/resolver/mutation.go b/core/web/resolver/mutation.go index 551b8d8e89a..9b0f5e50a03 100644 --- a/core/web/resolver/mutation.go +++ b/core/web/resolver/mutation.go @@ -113,7 +113,7 @@ func (r *Resolver) CreateCSAKey(ctx context.Context) (*CreateCSAKeyPayloadResolv return nil, err } - key, err := r.App.GetKeyStore().CSA().Create() + key, err := r.App.GetKeyStore().CSA().Create(ctx) if err != nil { if errors.Is(err, keystore.ErrCSAKeyExists) { return NewCreateCSAKeyPayload(nil, err), nil @@ -137,7 +137,7 @@ func (r *Resolver) DeleteCSAKey(ctx context.Context, args struct { return nil, err } - key, err := r.App.GetKeyStore().CSA().Delete(string(args.ID)) + key, err := r.App.GetKeyStore().CSA().Delete(ctx, string(args.ID)) if err != nil { if errors.As(err, &keystore.KeyNotFoundError{}) { return NewDeleteCSAKeyPayload(csakey.KeyV2{}, err), nil @@ -561,7 +561,7 @@ func (r *Resolver) CreateOCRKeyBundle(ctx context.Context) (*CreateOCRKeyBundleP return nil, err } - key, err := r.App.GetKeyStore().OCR().Create() + key, err := r.App.GetKeyStore().OCR().Create(ctx) if err != nil { return nil, err } @@ -581,7 +581,7 @@ func (r *Resolver) DeleteOCRKeyBundle(ctx context.Context, args struct { return nil, err } - deletedKey, err := r.App.GetKeyStore().OCR().Delete(args.ID) + deletedKey, err := r.App.GetKeyStore().OCR().Delete(ctx, args.ID) if err != nil { if errors.As(err, &keystore.KeyNotFoundError{}) { return NewDeleteOCRKeyBundlePayloadResolver(ocrkey.KeyV2{}, err), nil @@ -636,7 +636,7 @@ func (r *Resolver) CreateP2PKey(ctx context.Context) (*CreateP2PKeyPayloadResolv return nil, err } - key, err := r.App.GetKeyStore().P2P().Create() + key, err := r.App.GetKeyStore().P2P().Create(ctx) if err != nil { return nil, err } @@ -665,7 +665,7 @@ func (r *Resolver) DeleteP2PKey(ctx context.Context, args struct { return nil, err } - key, err := r.App.GetKeyStore().P2P().Delete(keyID) + key, err := r.App.GetKeyStore().P2P().Delete(ctx, keyID) if err != nil { if errors.As(err, &keystore.KeyNotFoundError{}) { return NewDeleteP2PKeyPayload(p2pkey.KeyV2{}, err), nil @@ -686,7 +686,7 @@ func (r *Resolver) CreateVRFKey(ctx context.Context) (*CreateVRFKeyPayloadResolv return nil, err } - key, err := r.App.GetKeyStore().VRF().Create() + key, err := r.App.GetKeyStore().VRF().Create(ctx) if err != nil { return nil, err } @@ -708,7 +708,7 @@ func (r *Resolver) DeleteVRFKey(ctx context.Context, args struct { return nil, err } - key, err := r.App.GetKeyStore().VRF().Delete(string(args.ID)) + key, err := r.App.GetKeyStore().VRF().Delete(ctx, string(args.ID)) if err != nil { if errors.Is(errors.Cause(err), keystore.ErrMissingVRFKey) { return NewDeleteVRFKeyPayloadResolver(vrfkey.KeyV2{}, err), nil @@ -1206,7 +1206,7 @@ func (r *Resolver) CreateOCR2KeyBundle(ctx context.Context, args struct { ct := FromOCR2ChainType(args.ChainType) - key, err := r.App.GetKeyStore().OCR2().Create(chaintype.ChainType(ct)) + key, err := r.App.GetKeyStore().OCR2().Create(ctx, chaintype.ChainType(ct)) if err != nil { // Not covering the `chaintype.ErrInvalidChainType` since the GQL model would prevent a non-accepted chain-type from being received return nil, err @@ -1238,7 +1238,7 @@ func (r *Resolver) DeleteOCR2KeyBundle(ctx context.Context, args struct { return NewDeleteOCR2KeyBundlePayloadResolver(nil, err), nil } - err = r.App.GetKeyStore().OCR2().Delete(id) + err = r.App.GetKeyStore().OCR2().Delete(ctx, id) if err != nil { return nil, err } diff --git a/core/web/resolver/ocr2_keys_test.go b/core/web/resolver/ocr2_keys_test.go index 35ee1925cdb..fc82d070dd9 100644 --- a/core/web/resolver/ocr2_keys_test.go +++ b/core/web/resolver/ocr2_keys_test.go @@ -8,13 +8,13 @@ import ( gqlerrors "github.com/graph-gophers/graphql-go/errors" "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/keystest" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/chaintype" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocr2key" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestResolver_GetOCR2KeyBundles(t *testing.T) { @@ -151,7 +151,7 @@ func TestResolver_CreateOCR2KeyBundle(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.ocr2.On("Create", chaintype.ChainType("evm")).Return(fakeKey, nil) + f.Mocks.ocr2.On("Create", mock.Anything, chaintype.ChainType("evm")).Return(fakeKey, nil) f.Mocks.keystore.On("OCR2").Return(f.Mocks.ocr2) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -163,7 +163,7 @@ func TestResolver_CreateOCR2KeyBundle(t *testing.T) { name: "generic error on Create()", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.ocr2.On("Create", chaintype.ChainType("evm")).Return(nil, gError) + f.Mocks.ocr2.On("Create", mock.Anything, chaintype.ChainType("evm")).Return(nil, gError) f.Mocks.keystore.On("OCR2").Return(f.Mocks.ocr2) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -239,7 +239,7 @@ func TestResolver_DeleteOCR2KeyBundle(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.ocr2.On("Delete", fakeKey.ID()).Return(nil) + f.Mocks.ocr2.On("Delete", mock.Anything, fakeKey.ID()).Return(nil) f.Mocks.ocr2.On("Get", fakeKey.ID()).Return(fakeKey, nil) f.Mocks.keystore.On("OCR2").Return(f.Mocks.ocr2) f.App.On("GetKeyStore").Return(f.Mocks.keystore) @@ -269,7 +269,7 @@ func TestResolver_DeleteOCR2KeyBundle(t *testing.T) { name: "generic error on Delete()", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.ocr2.On("Delete", fakeKey.ID()).Return(gError) + f.Mocks.ocr2.On("Delete", mock.Anything, fakeKey.ID()).Return(gError) f.Mocks.ocr2.On("Get", fakeKey.ID()).Return(fakeKey, nil) f.Mocks.keystore.On("OCR2").Return(f.Mocks.ocr2) f.App.On("GetKeyStore").Return(f.Mocks.keystore) diff --git a/core/web/resolver/ocr_test.go b/core/web/resolver/ocr_test.go index d1a0351842d..5ca56c4bd04 100644 --- a/core/web/resolver/ocr_test.go +++ b/core/web/resolver/ocr_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ocrkey" @@ -105,7 +106,7 @@ func TestResolver_OCRCreateBundle(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.ocr.On("Create").Return(fakeKey, nil) + f.Mocks.ocr.On("Create", mock.Anything).Return(fakeKey, nil) f.Mocks.keystore.On("OCR").Return(f.Mocks.ocr) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -163,7 +164,7 @@ func TestResolver_OCRDeleteBundle(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.ocr.On("Delete", fakeKey.ID()).Return(fakeKey, nil) + f.Mocks.ocr.On("Delete", mock.Anything, fakeKey.ID()).Return(fakeKey, nil) f.Mocks.keystore.On("OCR").Return(f.Mocks.ocr) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -176,7 +177,7 @@ func TestResolver_OCRDeleteBundle(t *testing.T) { authenticated: true, before: func(f *gqlTestFramework) { f.Mocks.ocr. - On("Delete", fakeKey.ID()). + On("Delete", mock.Anything, fakeKey.ID()). Return(ocrkey.KeyV2{}, keystore.KeyNotFoundError{ID: "helloWorld", KeyType: "OCR"}) f.Mocks.keystore.On("OCR").Return(f.Mocks.ocr) f.App.On("GetKeyStore").Return(f.Mocks.keystore) diff --git a/core/web/resolver/p2p_test.go b/core/web/resolver/p2p_test.go index e2470f7fac5..6502ffc821a 100644 --- a/core/web/resolver/p2p_test.go +++ b/core/web/resolver/p2p_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/p2pkey" @@ -102,7 +103,7 @@ func TestResolver_CreateP2PKey(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.p2p.On("Create").Return(fakeKey, nil) + f.Mocks.p2p.On("Create", mock.Anything).Return(fakeKey, nil) f.Mocks.keystore.On("P2P").Return(f.Mocks.p2p) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -163,7 +164,7 @@ func TestResolver_DeleteP2PKey(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.p2p.On("Delete", peerID).Return(fakeKey, nil) + f.Mocks.p2p.On("Delete", mock.Anything, peerID).Return(fakeKey, nil) f.Mocks.keystore.On("P2P").Return(f.Mocks.p2p) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -176,7 +177,7 @@ func TestResolver_DeleteP2PKey(t *testing.T) { authenticated: true, before: func(f *gqlTestFramework) { f.Mocks.p2p. - On("Delete", peerID). + On("Delete", mock.Anything, peerID). Return( p2pkey.KeyV2{}, keystore.KeyNotFoundError{ID: peerID.String(), KeyType: "P2P"}, diff --git a/core/web/resolver/vrf_test.go b/core/web/resolver/vrf_test.go index e1ee73b9984..5101bc5937b 100644 --- a/core/web/resolver/vrf_test.go +++ b/core/web/resolver/vrf_test.go @@ -8,6 +8,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/vrfkey" @@ -198,7 +199,7 @@ func TestResolver_CreateVRFKey(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.vrf.On("Create").Return(fakeKey, nil) + f.Mocks.vrf.On("Create", mock.Anything).Return(fakeKey, nil) f.Mocks.keystore.On("VRF").Return(f.Mocks.vrf) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -261,7 +262,7 @@ func TestResolver_DeleteVRFKey(t *testing.T) { name: "success", authenticated: true, before: func(f *gqlTestFramework) { - f.Mocks.vrf.On("Delete", fakeKey.PublicKey.String()).Return(fakeKey, nil) + f.Mocks.vrf.On("Delete", mock.Anything, fakeKey.PublicKey.String()).Return(fakeKey, nil) f.Mocks.keystore.On("VRF").Return(f.Mocks.vrf) f.App.On("GetKeyStore").Return(f.Mocks.keystore) }, @@ -274,7 +275,7 @@ func TestResolver_DeleteVRFKey(t *testing.T) { authenticated: true, before: func(f *gqlTestFramework) { f.Mocks.vrf. - On("Delete", fakeKey.PublicKey.String()). + On("Delete", mock.Anything, fakeKey.PublicKey.String()). Return(vrfkey.KeyV2{}, errors.Wrapf( keystore.ErrMissingVRFKey, "unable to find VRF key with id %s", diff --git a/core/web/solana_keys_controller_test.go b/core/web/solana_keys_controller_test.go index 94b11207c92..b71f8287d0f 100644 --- a/core/web/solana_keys_controller_test.go +++ b/core/web/solana_keys_controller_test.go @@ -5,15 +5,15 @@ import ( "net/http" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/web" "github.com/smartcontractkit/chainlink/v2/core/web/presenters" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestSolanaKeysController_Index_HappyPath(t *testing.T) { @@ -75,12 +75,13 @@ func TestSolanaKeysController_Delete_NonExistentSolanaKeyID(t *testing.T) { func TestSolanaKeysController_Delete_HappyPath(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) client, keyStore := setupSolanaKeysControllerTests(t) keys, _ := keyStore.Solana().GetAll() initialLength := len(keys) - key, _ := keyStore.Solana().Create() + key, _ := keyStore.Solana().Create(ctx) response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/solana/%s", key.ID())) t.Cleanup(cleanup) @@ -93,11 +94,12 @@ func TestSolanaKeysController_Delete_HappyPath(t *testing.T) { func setupSolanaKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { t.Helper() + ctx := testutils.Context(t) app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, app.KeyStore.Solana().Add(cltest.DefaultSolanaKey)) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.Solana().Add(ctx, cltest.DefaultSolanaKey)) client := app.NewHTTPClient(nil) diff --git a/core/web/starknet_keys_controller_test.go b/core/web/starknet_keys_controller_test.go index 9215fb8f9c5..05f611f2f22 100644 --- a/core/web/starknet_keys_controller_test.go +++ b/core/web/starknet_keys_controller_test.go @@ -75,12 +75,13 @@ func TestStarkNetKeysController_Delete_NonExistentStarkNetKeyID(t *testing.T) { func TestStarkNetKeysController_Delete_HappyPath(t *testing.T) { t.Parallel() + ctx := testutils.Context(t) client, keyStore := setupStarkNetKeysControllerTests(t) keys, _ := keyStore.StarkNet().GetAll() initialLength := len(keys) - key, _ := keyStore.StarkNet().Create() + key, _ := keyStore.StarkNet().Create(ctx) response, cleanup := client.Delete(fmt.Sprintf("/v2/keys/starknet/%s", key.ID())) t.Cleanup(cleanup) @@ -93,11 +94,12 @@ func TestStarkNetKeysController_Delete_HappyPath(t *testing.T) { func setupStarkNetKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, keystore.Master) { t.Helper() + ctx := testutils.Context(t) app := cltest.NewApplication(t) - require.NoError(t, app.Start(testutils.Context(t))) - require.NoError(t, app.KeyStore.OCR().Add(cltest.DefaultOCRKey)) - require.NoError(t, app.KeyStore.StarkNet().Add(cltest.DefaultStarkNetKey)) + require.NoError(t, app.Start(ctx)) + require.NoError(t, app.KeyStore.OCR().Add(ctx, cltest.DefaultOCRKey)) + require.NoError(t, app.KeyStore.StarkNet().Add(ctx, cltest.DefaultStarkNetKey)) client := app.NewHTTPClient(nil) diff --git a/core/web/vrf_keys_controller.go b/core/web/vrf_keys_controller.go index a54a3f9d596..567b8acc995 100644 --- a/core/web/vrf_keys_controller.go +++ b/core/web/vrf_keys_controller.go @@ -32,7 +32,8 @@ func (vrfkc *VRFKeysController) Index(c *gin.Context) { // Example: // "POST /keys/vrf" func (vrfkc *VRFKeysController) Create(c *gin.Context) { - pk, err := vrfkc.App.GetKeyStore().VRF().Create() + ctx := c.Request.Context() + pk, err := vrfkc.App.GetKeyStore().VRF().Create(ctx) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -53,13 +54,14 @@ func (vrfkc *VRFKeysController) Create(c *gin.Context) { // "DELETE /keys/vrf/:keyID" // "DELETE /keys/vrf/:keyID?hard=true" func (vrfkc *VRFKeysController) Delete(c *gin.Context) { + ctx := c.Request.Context() keyID := c.Param("keyID") key, err := vrfkc.App.GetKeyStore().VRF().Get(keyID) if err != nil { jsonAPIError(c, http.StatusNotFound, err) return } - _, err = vrfkc.App.GetKeyStore().VRF().Delete(keyID) + _, err = vrfkc.App.GetKeyStore().VRF().Delete(ctx, keyID) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return @@ -78,6 +80,7 @@ func (vrfkc *VRFKeysController) Delete(c *gin.Context) { // "Post /keys/vrf/import" func (vrfkc *VRFKeysController) Import(c *gin.Context) { defer vrfkc.App.GetLogger().ErrorIfFn(c.Request.Body.Close, "Error closing Import request body") + ctx := c.Request.Context() bytes, err := io.ReadAll(c.Request.Body) if err != nil { @@ -85,7 +88,7 @@ func (vrfkc *VRFKeysController) Import(c *gin.Context) { return } oldPassword := c.Query("oldpassword") - key, err := vrfkc.App.GetKeyStore().VRF().Import(bytes, oldPassword) + key, err := vrfkc.App.GetKeyStore().VRF().Import(ctx, bytes, oldPassword) if err != nil { jsonAPIError(c, http.StatusInternalServerError, err) return diff --git a/go.mod b/go.mod index 3970b20a4bf..470a07da052 100644 --- a/go.mod +++ b/go.mod @@ -72,8 +72,8 @@ require ( github.com/shopspring/decimal v1.3.1 github.com/smartcontractkit/chain-selectors v1.0.10 github.com/smartcontractkit/chainlink-automation v1.0.3 - github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 - github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 + github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e + github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 github.com/smartcontractkit/chainlink-solana v1.0.3-0.20240216142700-c5869534c19e diff --git a/go.sum b/go.sum index 753ffcda235..7b7a1123baa 100644 --- a/go.sum +++ b/go.sum @@ -1180,10 +1180,10 @@ github.com/smartcontractkit/chain-selectors v1.0.10 h1:t9kJeE6B6G+hKD0GYR4kGJSCq github.com/smartcontractkit/chain-selectors v1.0.10/go.mod h1:d4Hi+E1zqjy9HqMkjBE5q1vcG9VGgxf5VxiRHfzi2kE= github.com/smartcontractkit/chainlink-automation v1.0.3 h1:h/ijT0NiyV06VxYVgcNfsE3+8OEzT3Q0Z9au0z1BPWs= github.com/smartcontractkit/chainlink-automation v1.0.3/go.mod h1:RjboV0Qd7YP+To+OrzHGXaxUxoSONveCoAK2TQ1INLU= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 h1:K7Y+gd0lEumrhgaIQFjC8reXadJOMVgDI4xsCAsiuSo= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 h1:I326nw5GwHQHsLKHwtu5Sb9EBLylC8CfUd7BFAS0jtg= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8/go.mod h1:a65NtrK4xZb01mf0dDNghPkN2wXgcqFQ55ADthVBgMc= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e h1:nHs5mFOR7FPII20GrCGIPywDW43MhEUlD7DqHnTgu6Q= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 h1:MvaNzuaQh1vX4CAYLM8qFd99cf0ZF1JNwtDZtLU7WvU= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92/go.mod h1:uATrrJ8IsuBkOBJ46USuf73gz9gZy5k5bzGE5/ji/rc= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 h1:xFSv8561jsLtF6gYZr/zW2z5qUUAkcFkApin2mnbYTo= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540/go.mod h1:sjAmX8K2kbQhvDarZE1ZZgDgmHJ50s0BBc/66vKY2ek= github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 h1:1BcjXuviSAKttOX7BZoVHRZZGfxqoA2+AL8tykmkdoc= diff --git a/integration-tests/go.mod b/integration-tests/go.mod index 7746cca72d6..e0c50d14bc5 100644 --- a/integration-tests/go.mod +++ b/integration-tests/go.mod @@ -24,7 +24,7 @@ require ( github.com/segmentio/ksuid v1.0.4 github.com/slack-go/slack v0.12.2 github.com/smartcontractkit/chainlink-automation v1.0.3 - github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 + github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e github.com/smartcontractkit/chainlink-testing-framework v1.28.3 github.com/smartcontractkit/chainlink-vrf v0.0.0-20240222010609-cd67d123c772 github.com/smartcontractkit/chainlink/v2 v2.0.0-00010101000000-000000000000 @@ -378,7 +378,7 @@ require ( github.com/shopspring/decimal v1.3.1 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartcontractkit/chain-selectors v1.0.10 // indirect - github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 // indirect + github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 // indirect github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 // indirect github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 // indirect github.com/smartcontractkit/chainlink-solana v1.0.3-0.20240216142700-c5869534c19e // indirect diff --git a/integration-tests/go.sum b/integration-tests/go.sum index c18825a1f24..af600c8b550 100644 --- a/integration-tests/go.sum +++ b/integration-tests/go.sum @@ -1519,10 +1519,10 @@ github.com/smartcontractkit/chain-selectors v1.0.10 h1:t9kJeE6B6G+hKD0GYR4kGJSCq github.com/smartcontractkit/chain-selectors v1.0.10/go.mod h1:d4Hi+E1zqjy9HqMkjBE5q1vcG9VGgxf5VxiRHfzi2kE= github.com/smartcontractkit/chainlink-automation v1.0.3 h1:h/ijT0NiyV06VxYVgcNfsE3+8OEzT3Q0Z9au0z1BPWs= github.com/smartcontractkit/chainlink-automation v1.0.3/go.mod h1:RjboV0Qd7YP+To+OrzHGXaxUxoSONveCoAK2TQ1INLU= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 h1:K7Y+gd0lEumrhgaIQFjC8reXadJOMVgDI4xsCAsiuSo= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 h1:I326nw5GwHQHsLKHwtu5Sb9EBLylC8CfUd7BFAS0jtg= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8/go.mod h1:a65NtrK4xZb01mf0dDNghPkN2wXgcqFQ55ADthVBgMc= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e h1:nHs5mFOR7FPII20GrCGIPywDW43MhEUlD7DqHnTgu6Q= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 h1:MvaNzuaQh1vX4CAYLM8qFd99cf0ZF1JNwtDZtLU7WvU= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92/go.mod h1:uATrrJ8IsuBkOBJ46USuf73gz9gZy5k5bzGE5/ji/rc= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 h1:xFSv8561jsLtF6gYZr/zW2z5qUUAkcFkApin2mnbYTo= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540/go.mod h1:sjAmX8K2kbQhvDarZE1ZZgDgmHJ50s0BBc/66vKY2ek= github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 h1:1BcjXuviSAKttOX7BZoVHRZZGfxqoA2+AL8tykmkdoc= diff --git a/integration-tests/load/go.mod b/integration-tests/load/go.mod index f0f62ce41e7..da76545c616 100644 --- a/integration-tests/load/go.mod +++ b/integration-tests/load/go.mod @@ -16,7 +16,7 @@ require ( github.com/rs/zerolog v1.30.0 github.com/slack-go/slack v0.12.2 github.com/smartcontractkit/chainlink-automation v1.0.3 - github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 + github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e github.com/smartcontractkit/chainlink-testing-framework v1.28.3 github.com/smartcontractkit/chainlink/integration-tests v0.0.0-20240214231432-4ad5eb95178c github.com/smartcontractkit/chainlink/v2 v2.9.0-beta0.0.20240216210048-da02459ddad8 @@ -367,7 +367,7 @@ require ( github.com/shopspring/decimal v1.3.1 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartcontractkit/chain-selectors v1.0.10 // indirect - github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 // indirect + github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 // indirect github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 // indirect github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 // indirect github.com/smartcontractkit/chainlink-solana v1.0.3-0.20240216142700-c5869534c19e // indirect diff --git a/integration-tests/load/go.sum b/integration-tests/load/go.sum index 13d80e3a8e1..cdb5a488d37 100644 --- a/integration-tests/load/go.sum +++ b/integration-tests/load/go.sum @@ -1502,10 +1502,10 @@ github.com/smartcontractkit/chain-selectors v1.0.10 h1:t9kJeE6B6G+hKD0GYR4kGJSCq github.com/smartcontractkit/chain-selectors v1.0.10/go.mod h1:d4Hi+E1zqjy9HqMkjBE5q1vcG9VGgxf5VxiRHfzi2kE= github.com/smartcontractkit/chainlink-automation v1.0.3 h1:h/ijT0NiyV06VxYVgcNfsE3+8OEzT3Q0Z9au0z1BPWs= github.com/smartcontractkit/chainlink-automation v1.0.3/go.mod h1:RjboV0Qd7YP+To+OrzHGXaxUxoSONveCoAK2TQ1INLU= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0 h1:K7Y+gd0lEumrhgaIQFjC8reXadJOMVgDI4xsCAsiuSo= -github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419013737-4554767e4db0/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8 h1:I326nw5GwHQHsLKHwtu5Sb9EBLylC8CfUd7BFAS0jtg= -github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240213120401-01a23955f9f8/go.mod h1:a65NtrK4xZb01mf0dDNghPkN2wXgcqFQ55ADthVBgMc= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e h1:nHs5mFOR7FPII20GrCGIPywDW43MhEUlD7DqHnTgu6Q= +github.com/smartcontractkit/chainlink-common v0.1.7-0.20240419105123-fc5d616c7d2e/go.mod h1:GTDBbovHUSAUk+fuGIySF2A/whhdtHGaWmU61BoERks= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92 h1:MvaNzuaQh1vX4CAYLM8qFd99cf0ZF1JNwtDZtLU7WvU= +github.com/smartcontractkit/chainlink-cosmos v0.4.1-0.20240419131812-73d148593d92/go.mod h1:uATrrJ8IsuBkOBJ46USuf73gz9gZy5k5bzGE5/ji/rc= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540 h1:xFSv8561jsLtF6gYZr/zW2z5qUUAkcFkApin2mnbYTo= github.com/smartcontractkit/chainlink-data-streams v0.0.0-20240220203239-09be0ea34540/go.mod h1:sjAmX8K2kbQhvDarZE1ZZgDgmHJ50s0BBc/66vKY2ek= github.com/smartcontractkit/chainlink-feeds v0.0.0-20240119021347-3c541a78cdb8 h1:1BcjXuviSAKttOX7BZoVHRZZGfxqoA2+AL8tykmkdoc= diff --git a/shell.nix b/shell.nix index ca785283fd5..69bf202351d 100644 --- a/shell.nix +++ b/shell.nix @@ -42,6 +42,9 @@ mkShell' { kubectl kubernetes-helm + # cross-compiling, used in CRIB + zig + # gofuzz ] ++ lib.optionals stdenv.isLinux [ # some dependencies needed for node-gyp on pnpm install diff --git a/testdata/scripts/health/multi-chain.txtar b/testdata/scripts/health/multi-chain.txtar index 112d9e3cdb1..fd48c0ad1ce 100644 --- a/testdata/scripts/health/multi-chain.txtar +++ b/testdata/scripts/health/multi-chain.txtar @@ -61,6 +61,7 @@ URL = 'http://stark.node' -- out.txt -- ok Cosmos.Foo.Chain +ok Cosmos.Foo.Relayer ok Cosmos.Foo.Txm ok EVM.1 ok EVM.1.BalanceMonitor @@ -97,6 +98,15 @@ ok TelemetryManager "output": "" } }, + { + "type": "checks", + "id": "Cosmos.Foo.Relayer", + "attributes": { + "name": "Cosmos.Foo.Relayer", + "status": "passing", + "output": "" + } + }, { "type": "checks", "id": "Cosmos.Foo.Txm",