From 81062de03f33307ba55d6caf0c944d5a593e107c Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Thu, 16 Jul 2026 09:44:37 -0500 Subject: [PATCH] go fix ./... --- core/auth/auth.go | 6 +- .../ccip/ccipevm/msghasher_test.go | 5 +- .../ccip/ccipsolana/extradatacodec.go | 4 +- .../capabilities/ccip/ccipsolana/msghasher.go | 2 +- .../ccip/ccipsolana/msghasher_test.go | 6 +- .../ccip/configs/sui/chain_writer.go | 16 +- .../observation_metrics_collector_test.go | 6 +- .../fakes/confidential_http_action.go | 2 +- .../triggers/trigger_event_store.go | 2 +- core/capabilities/vault/capability_test.go | 54 +- core/capabilities/vault/jwt_based_auth.go | 10 +- .../capabilities/vault/jwt_based_auth_test.go | 88 +-- core/capabilities/vault/jwt_oauth_scope.go | 6 +- .../vault/request_lifecycle_tracker.go | 14 +- core/cmd/blocks_commands_test.go | 2 +- core/cmd/chains_commands_test.go | 6 +- core/cmd/eth_keys_commands_test.go | 41 +- core/cmd/evm_transaction_commands_test.go | 12 +- core/cmd/forwarders_commands_test.go | 6 +- core/cmd/jobs_commands_test.go | 14 +- core/cmd/node_commands_test.go | 13 +- core/cmd/shell_local_test.go | 6 +- core/cmd/shell_remote_test.go | 24 +- core/cmd/shell_test.go | 2 +- core/config/toml/types.go | 4 +- core/internal/cltest/cltest.go | 4 +- core/internal/testutils/testutils.go | 4 +- core/logger/logger_unix.go | 1 - core/logger/logger_windows.go | 1 - core/services/arbiter/arbiter.go | 6 +- core/services/arbiter/grpc_server_test.go | 2 +- core/services/arbiter/shardconfig.go | 6 +- core/services/arbiter/state_test.go | 2 +- core/services/chainlink/config_general.go | 8 +- .../chainlink/config_telemetry_test.go | 54 +- core/services/chainlink/config_test.go | 663 +++++++++--------- core/services/chainlink/node_platform_test.go | 5 +- .../relayer_chain_interoperators_test.go | 30 +- core/services/functions/listener_test.go | 4 +- .../gateway/handlers/capabilities/handler.go | 6 +- .../handlers/capabilities/v2/http_handler.go | 12 +- .../capabilities/v2/http_trigger_handler.go | 6 +- .../capabilities/v2/response_cache.go | 2 +- .../capabilities/v2/response_cache_test.go | 6 +- .../v2/workflow_metadata_handler.go | 6 +- .../confidentialrelay/handler_test.go | 42 +- .../handlers/functions/allowlist/allowlist.go | 11 +- .../gateway/handlers/vault/aggregator_test.go | 7 +- .../gateway/handlers/vault/handler_test.go | 60 +- core/services/job/runner_integration_test.go | 11 +- core/services/llo/telem/sampling.go | 6 +- core/services/llo/telem/sampling_test.go | 6 +- core/services/llo/telem/telemetry.go | 6 +- core/services/llo/telem/telemetry_test.go | 36 +- .../jobspec/job_spec_reporter.go | 23 +- core/services/ocr2/plugins/vault/plugin.go | 2 +- .../ocr2/plugins/vault/plugin_test.go | 11 +- core/services/ocrcommon/peer_wrapper_test.go | 28 +- core/services/p2p/shared_peer_test.go | 6 +- core/services/pg/lease_lock.go | 3 +- core/services/pipeline/common.go | 51 +- core/services/pipeline/common_eth.go | 2 +- core/services/pipeline/common_eth_test.go | 2 +- core/services/pipeline/common_test.go | 12 +- core/services/pipeline/runner.go | 8 +- core/services/pipeline/task.divide_test.go | 2 +- core/services/pipeline/task.eth_tx.go | 4 +- core/services/pipeline/task.eth_tx_test.go | 3 +- core/services/registrysyncer/syncer.go | 12 +- core/services/registrysyncer/v2/syncer.go | 12 +- .../testutils/signing_keystore.go | 7 +- .../relay/evm/chain_components_test.go | 8 +- .../evm/evmtesting/bindings_test_adapter.go | 24 +- core/services/ring/plugin_test.go | 2 +- core/services/ring/store.go | 4 +- core/services/ring/store_test.go | 4 +- .../shardorchestrator/shard_orchestrator.go | 6 +- .../standard_capabilities.go | 6 +- core/services/streams/delegate_test.go | 3 +- core/services/streams/stream_registry_test.go | 10 +- core/services/streams/stream_test.go | 4 +- .../chip_ingress_batch_client_test.go | 4 +- .../chip_ingress_batch_worker_test.go | 2 +- core/services/telemetry/chip_ingress_test.go | 2 +- core/utils/finite_ticker.go | 6 +- core/utils/utils.go | 5 +- core/web/chains_controller_test.go | 31 +- core/web/cors_test.go | 4 +- core/web/eth_keys_controller_test.go | 70 +- core/web/evm_forwarders_controller_test.go | 4 +- core/web/evm_transfer_controller_test.go | 6 +- .../external_initiators_controller_test.go | 12 +- core/web/jobs_controller_test.go | 16 +- core/web/log_controller_test.go | 2 +- core/web/loop_registry_test.go | 4 +- core/web/pipeline_runs_controller_test.go | 8 +- tools/ci-testshard/main_test.go | 8 +- tools/plugout/main.go | 8 +- 98 files changed, 842 insertions(+), 973 deletions(-) diff --git a/core/auth/auth.go b/core/auth/auth.go index d7cde489724..6a414b01119 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -1,14 +1,14 @@ package auth import ( + "crypto/sha3" "encoding/hex" "fmt" + "hash" pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/v2/core/utils" - - "golang.org/x/crypto/sha3" ) var ( @@ -55,7 +55,7 @@ func hashInput(ta *Token, salt string) []byte { // HashedSecret generates a hashed password for an external initiator // authentication func HashedSecret(ta *Token, salt string) (string, error) { - hasher := sha3.New256() + hasher := hash.Hash(sha3.New256()) _, err := hasher.Write(hashInput(ta, salt)) if err != nil { return "", pkgerrors.Wrap(err, "error writing external initiator authentication to hasher") diff --git a/core/capabilities/ccip/ccipevm/msghasher_test.go b/core/capabilities/ccip/ccipevm/msghasher_test.go index 7933365400c..bbd36785ab1 100644 --- a/core/capabilities/ccip/ccipevm/msghasher_test.go +++ b/core/capabilities/ccip/ccipevm/msghasher_test.go @@ -8,7 +8,8 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" + "os" + "math/big" "math/rand" "strings" @@ -464,7 +465,7 @@ func TestMessagerHasher_againstRmnSharedVector(t *testing.T) { // onramp address: 0x89559ce6904d4c4b0f6aab9065ad02b1ed531be4 // sequence numbers 386 to 419. var msgs []cciptypes.Message - data, err := ioutil.ReadFile("msgs_test_vector.json") + data, err := os.ReadFile("msgs_test_vector.json") require.NoError(t, err) err = json.Unmarshal(data, &msgs) diff --git a/core/capabilities/ccip/ccipsolana/extradatacodec.go b/core/capabilities/ccip/ccipsolana/extradatacodec.go index 27642e901d5..1a13f10fed2 100644 --- a/core/capabilities/ccip/ccipsolana/extradatacodec.go +++ b/core/capabilities/ccip/ccipsolana/extradatacodec.go @@ -52,7 +52,7 @@ func (d ExtraDataDecoder) DecodeExtraArgsToMap(extraArgs cciptypes.Bytes) (map[s return nil, fmt.Errorf("failed to decode extra args: %w", err) } val = reflect.ValueOf(args) - typ = reflect.TypeOf(args) + typ = reflect.TypeFor[fee_quoter.GenericExtraArgsV2]() case string(svmExtraArgsV1Tag): var args fee_quoter.SVMExtraArgsV1 decoder := agbinary.NewBorshDecoder(extraArgs[4:]) @@ -61,7 +61,7 @@ func (d ExtraDataDecoder) DecodeExtraArgsToMap(extraArgs cciptypes.Bytes) (map[s return nil, fmt.Errorf("failed to decode extra args: %w", err) } val = reflect.ValueOf(args) - typ = reflect.TypeOf(args) + typ = reflect.TypeFor[fee_quoter.SVMExtraArgsV1]() default: return nil, fmt.Errorf("unknown extra args tag: %x", extraArgs[:4]) } diff --git a/core/capabilities/ccip/ccipsolana/msghasher.go b/core/capabilities/ccip/ccipsolana/msghasher.go index 437fe2e6d03..ffaf82d7b31 100644 --- a/core/capabilities/ccip/ccipsolana/msghasher.go +++ b/core/capabilities/ccip/ccipsolana/msghasher.go @@ -151,7 +151,7 @@ func parseExtraDataMap(input map[string]any) (extraData, error) { a[i] = solana.PublicKeyFromBytes(val[:]) } accounts = a - case []interface{}: // LOOP gRPC converts [][32]byte -> []interface{} + case []any: // LOOP gRPC converts [][32]byte -> []interface{} a := make([]solana.PublicKey, len(v)) for i, elem := range v { bs, ok := elem.([]byte) diff --git a/core/capabilities/ccip/ccipsolana/msghasher_test.go b/core/capabilities/ccip/ccipsolana/msghasher_test.go index ad250130a74..3e732b80616 100644 --- a/core/capabilities/ccip/ccipsolana/msghasher_test.go +++ b/core/capabilities/ccip/ccipsolana/msghasher_test.go @@ -141,7 +141,7 @@ func TestParseExtraDataMap_LOOPConvertedTypes(t *testing.T) { "AccountIsWritableBitmap": int64(6), // LOOP: uint64 -> int64 "AllowOutOfOrderExecution": true, "TokenReceiver": receiver, // LOOP: [32]byte -> []byte - "Accounts": []interface{}{ // LOOP: [][32]byte -> []interface{} + "Accounts": []any{ // LOOP: [][32]byte -> []interface{} account1, account2, }, @@ -194,7 +194,7 @@ func TestParseExtraDataMap_InvalidTypes(t *testing.T) { t.Run("Accounts element wrong length", func(t *testing.T) { input := map[string]any{ - "Accounts": []interface{}{ + "Accounts": []any{ []byte{0x01, 0x02}, // not 32 bytes }, } @@ -204,7 +204,7 @@ func TestParseExtraDataMap_InvalidTypes(t *testing.T) { t.Run("Accounts element wrong type", func(t *testing.T) { input := map[string]any{ - "Accounts": []interface{}{ + "Accounts": []any{ "not bytes", }, } diff --git a/core/capabilities/ccip/configs/sui/chain_writer.go b/core/capabilities/ccip/configs/sui/chain_writer.go index 9ad340e768f..6b29563d37c 100644 --- a/core/capabilities/ccip/configs/sui/chain_writer.go +++ b/core/capabilities/ccip/configs/sui/chain_writer.go @@ -32,8 +32,8 @@ func GetChainWriterConfig(publicKeyStr string) (types.ChainWriterConfig, error) PTBCommands: []types.ChainWriterPTBCommand{ { Type: types.SuiPTBCommandMoveCall, - ModuleId: strPtr("offramp"), - Function: strPtr("commit"), + ModuleId: new("offramp"), + Function: new("commit"), Params: []types.SuiFunctionParam{ { Name: "ref", @@ -77,8 +77,8 @@ func GetChainWriterConfig(publicKeyStr string) (types.ChainWriterConfig, error) PTBCommands: []types.ChainWriterPTBCommand{ { Type: types.SuiPTBCommandMoveCall, - ModuleId: strPtr("offramp"), - Function: strPtr("init_execute"), + ModuleId: new("offramp"), + Function: new("init_execute"), Params: []types.SuiFunctionParam{ { Name: "ref", @@ -116,8 +116,8 @@ func GetChainWriterConfig(publicKeyStr string) (types.ChainWriterConfig, error) }, { Type: types.SuiPTBCommandMoveCall, - ModuleId: strPtr("offramp"), - Function: strPtr("finish_execute"), + ModuleId: new("offramp"), + Function: new("finish_execute"), Params: []types.SuiFunctionParam{ { Name: "ref", @@ -151,6 +151,8 @@ func GetChainWriterConfig(publicKeyStr string) (types.ChainWriterConfig, error) } // Helper function to convert a string to a string pointer +// +//go:fix inline func strPtr(s string) *string { - return &s + return new(s) } diff --git a/core/capabilities/ccip/oraclecreator/observation_metrics_collector_test.go b/core/capabilities/ccip/oraclecreator/observation_metrics_collector_test.go index 477ab1a245a..669ea891747 100644 --- a/core/capabilities/ccip/oraclecreator/observation_metrics_collector_test.go +++ b/core/capabilities/ccip/oraclecreator/observation_metrics_collector_test.go @@ -232,9 +232,9 @@ func TestWrappedCounter_ConcurrentIncrements(t *testing.T) { const incrementsPerGoroutine = 100 done := make(chan bool, numGoroutines) - for i := 0; i < numGoroutines; i++ { + for range numGoroutines { go func() { - for j := 0; j < incrementsPerGoroutine; j++ { + for range incrementsPerGoroutine { baseCounter.Inc() } done <- true @@ -242,7 +242,7 @@ func TestWrappedCounter_ConcurrentIncrements(t *testing.T) { } // Wait for all goroutines - for i := 0; i < numGoroutines; i++ { + for range numGoroutines { <-done } diff --git a/core/capabilities/fakes/confidential_http_action.go b/core/capabilities/fakes/confidential_http_action.go index 3f222ef0699..b563d5a3245 100644 --- a/core/capabilities/fakes/confidential_http_action.go +++ b/core/capabilities/fakes/confidential_http_action.go @@ -121,7 +121,7 @@ func (fh *DirectConfidentialHTTPAction) SendRequest(ctx context.Context, metadat method = strings.ToUpper(method) // Prepare template data from loaded secrets - templateData := make(map[string]interface{}) + templateData := make(map[string]any) for k, v := range fh.secretsConfig.SecretsNames { if len(v) == 1 { templateData[k] = v[0] diff --git a/core/capabilities/triggers/trigger_event_store.go b/core/capabilities/triggers/trigger_event_store.go index 0a4a517165a..0b744c8afa7 100644 --- a/core/capabilities/triggers/trigger_event_store.go +++ b/core/capabilities/triggers/trigger_event_store.go @@ -54,7 +54,7 @@ UPDATE ` + triggerPendingEventsTable + ` SET last_sent_at = $3, attempts = $4 WHERE trigger_id = $1 AND event_id = $2 ` - var lastSent interface{} + var lastSent any if !lastSentAt.IsZero() { lastSent = lastSentAt } diff --git a/core/capabilities/vault/capability_test.go b/core/capabilities/vault/capability_test.go index e4ab19c2e8a..8cb45dd8096 100644 --- a/core/capabilities/vault/capability_test.go +++ b/core/capabilities/vault/capability_test.go @@ -97,9 +97,7 @@ func TestCapability_CapabilityCall(t *testing.T) { require.NoError(t, err) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -116,7 +114,7 @@ func TestCapability_CapabilityCall(t *testing.T) { } } } - }() + }) resp, err := capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -196,9 +194,7 @@ func TestCapability_CapabilityCall_DuringSubscriptionPhase(t *testing.T) { require.NoError(t, err) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -215,7 +211,7 @@ func TestCapability_CapabilityCall_DuringSubscriptionPhase(t *testing.T) { } } } - }() + }) resp, err := capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -497,9 +493,7 @@ func TestCapability_CapabilityCall_SecretIdentifierOwnerMismatch(t *testing.T) { if !tc.shouldReject { var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -515,7 +509,7 @@ func TestCapability_CapabilityCall_SecretIdentifierOwnerMismatch(t *testing.T) { } } } - }() + }) defer wg.Wait() } @@ -584,9 +578,7 @@ func TestCapability_CapabilityCall_UsesMetadataWorkflowOwner(t *testing.T) { require.NoError(t, err) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -599,7 +591,7 @@ func TestCapability_CapabilityCall_UsesMetadataWorkflowOwner(t *testing.T) { } } } - }() + }) _, err = capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -664,9 +656,7 @@ func TestCapability_CapabilityCall_ForwardsRequestGetSecretsIdentity(t *testing. forward *vault.GetSecretsRequest forwardedOK bool ) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -690,7 +680,7 @@ func TestCapability_CapabilityCall_ForwardsRequestGetSecretsIdentity(t *testing. return } } - }() + }) _, err = capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -759,9 +749,7 @@ func TestCapability_CapabilityCall_BackfillsGetSecretsWorkflowOwnerFromFirstSecr forward *vault.GetSecretsRequest forwardedOK bool ) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -785,7 +773,7 @@ func TestCapability_CapabilityCall_BackfillsGetSecretsWorkflowOwnerFromFirstSecr return } } - }() + }) _, err = capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -846,9 +834,7 @@ func TestCapability_CapabilityCall_ReturnsIncorrectType(t *testing.T) { require.NoError(t, err) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -865,7 +851,7 @@ func TestCapability_CapabilityCall_ReturnsIncorrectType(t *testing.T) { } } } - }() + }) _, err = capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -924,9 +910,7 @@ func TestCapability_CapabilityCall_TimeOut(t *testing.T) { require.NoError(t, err) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -939,7 +923,7 @@ func TestCapability_CapabilityCall_TimeOut(t *testing.T) { } } } - }() + }) _, err = capability.Execute(t.Context(), capabilities.CapabilityRequest{ Payload: anyproto, @@ -1613,9 +1597,7 @@ func TestCapability_CRUD(t *testing.T) { wait := func() {} if tc.error == "" { var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-t.Context().Done(): @@ -1629,7 +1611,7 @@ func TestCapability_CRUD(t *testing.T) { } } } - }() + }) wait = wg.Wait } diff --git a/core/capabilities/vault/jwt_based_auth.go b/core/capabilities/vault/jwt_based_auth.go index 79d6b842b7f..f1aa497fa78 100644 --- a/core/capabilities/vault/jwt_based_auth.go +++ b/core/capabilities/vault/jwt_based_auth.go @@ -299,7 +299,7 @@ func (v *jwtBasedAuth) validateToken(ctx context.Context, tokenString string) (* return nil, err } - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { if _, methodOK := token.Method.(*jwt.SigningMethodRSA); !methodOK { return nil, fmt.Errorf("%w: unsupported alg %v", ErrInvalidToken, token.Header["alg"]) } @@ -361,7 +361,7 @@ func extractVaultClaims(claims jwt.MapClaims) (*JWTClaims, error) { } func extractTenantNumericIDFromClaims(claims jwt.MapClaims) (uint64, error) { - var raw interface{} + var raw any ok := false if v, exists := claims[ClaimChainlinkTenantID]; exists && v != nil { raw, ok = v, true @@ -378,7 +378,7 @@ func extractTenantNumericIDFromClaims(claims jwt.MapClaims) (uint64, error) { return id, nil } -func parseJWTUnsignedIntegerClaim(raw interface{}) (uint64, error) { +func parseJWTUnsignedIntegerClaim(raw any) (uint64, error) { switch v := raw.(type) { case string: s := strings.TrimSpace(v) @@ -412,13 +412,13 @@ func extractAuthorizationDetails(claims jwt.MapClaims) (workflowOwner, requestDi return "", "", ErrMissingRequestDigest } - details, ok := rawDetails.([]interface{}) + details, ok := rawDetails.([]any) if !ok { return "", "", fmt.Errorf("%w: authorization_details must be an array", ErrInvalidToken) } for _, rawDetail := range details { - detail, ok := rawDetail.(map[string]interface{}) + detail, ok := rawDetail.(map[string]any) if !ok { continue } diff --git a/core/capabilities/vault/jwt_based_auth_test.go b/core/capabilities/vault/jwt_based_auth_test.go index a26e9cf06c3..84e749cece3 100644 --- a/core/capabilities/vault/jwt_based_auth_test.go +++ b/core/capabilities/vault/jwt_based_auth_test.go @@ -136,12 +136,12 @@ func validTestClaims(tb testing.TB, issuer, audience string) jwt.MapClaims { "org_id": "org_test123", ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": "abc123def456", }, - map[string]interface{}{ + map[string]any{ "type": "workflow_owner", "value": testJWTExpectedWorkflowOwner(tb, 1, "org_test123"), }, @@ -199,8 +199,8 @@ func TestJWTBasedAuth_ValidTokenWithoutWorkflowOwner(t *testing.T) { "org_id": "org_no_wfowner", ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": "digest456", }, @@ -419,8 +419,8 @@ func TestJWTBasedAuth_MissingRequestDigest(t *testing.T) { v := newTestValidator(t, issuer, audience) claims := validTestClaims(t, issuer, audience) - claims["authorization_details"] = []interface{}{ - map[string]interface{}{ + claims["authorization_details"] = []any{ + map[string]any{ "type": "workflow_owner", "value": "0xAbCd", }, @@ -505,12 +505,12 @@ func TestJWTBasedAuth_JWKSKeyRotation(t *testing.T) { // Token signed with key-B succeeds after JWKS refresh claimsB := validTestClaims(t, issuer, audience) claimsB["org_id"] = "org_after_rotation" - claimsB["authorization_details"] = []interface{}{ - map[string]interface{}{ + claimsB["authorization_details"] = []any{ + map[string]any{ "type": "request_digest", "value": "abc123def456", }, - map[string]interface{}{ + map[string]any{ "type": "workflow_owner", "value": testJWTExpectedWorkflowOwner(t, 1, "org_after_rotation"), }, @@ -537,9 +537,9 @@ func TestJWTBasedAuth_AuthorizationDetailsFromTypedArray(t *testing.T) { "org_id": "org_single", ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", - "authorization_details": []interface{}{ - map[string]interface{}{"type": "request_digest", "value": "single_digest"}, - map[string]interface{}{"type": "workflow_owner", "value": testJWTExpectedWorkflowOwner(t, 1, "org_single")}, + "authorization_details": []any{ + map[string]any{"type": "request_digest", "value": "single_digest"}, + map[string]any{"type": "workflow_owner", "value": testJWTExpectedWorkflowOwner(t, 1, "org_single")}, }, } tokenString := createTestJWT(t, rsaKey, claims) @@ -693,7 +693,7 @@ func TestJWTBasedAuth_AuthorizeCreateRequestFromRawJSON(t *testing.T) { v := newTestValidator(t, issuer, audience) derivedOrg123Owner := testJWTExpectedWorkflowOwner(t, 1, "org-123") - rawRequest := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.create","params":{"request_id":"req-1","encrypted_secrets":[{"id":{"key":"7611","namespace":"main","owner":"%s"},"encrypted_value":"cipher+/=="}]}}`, derivedOrg123Owner)) + rawRequest := fmt.Appendf(nil, `{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.create","params":{"request_id":"req-1","encrypted_secrets":[{"id":{"key":"7611","namespace":"main","owner":"%s"},"encrypted_value":"cipher+/=="}]}}`, derivedOrg123Owner) req, err := jsonrpc.DecodeRequest[json.RawMessage](rawRequest, "") require.NoError(t, err) @@ -709,12 +709,12 @@ func TestJWTBasedAuth_AuthorizeCreateRequestFromRawJSON(t *testing.T) { ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", "scope": OAuthScopeVaultSecretsCreate, - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, - map[string]interface{}{ + map[string]any{ "type": "workflow_owner", "value": derivedOrg123Owner, }, @@ -753,8 +753,8 @@ func TestJWTBasedAuth_RejectsMissingOAuthScope(t *testing.T) { "iat": jwt.NewNumericDate(time.Now()), "org_id": "org-123", ClaimVaultSecretManagementEnabled: "true", - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -792,8 +792,8 @@ func TestJWTBasedAuth_RejectsMismatchedOAuthScope(t *testing.T) { "org_id": "org-123", ClaimVaultSecretManagementEnabled: "true", "scope": OAuthScopeVaultSecretsCreate, - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -831,8 +831,8 @@ func TestJWTBasedAuth_RejectsMultipleVaultOAuthScopes(t *testing.T) { "org_id": "org-123", ClaimVaultSecretManagementEnabled: "true", "scope": OAuthScopeVaultSecretsCreate + " " + OAuthScopeVaultSecretsDelete, - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -856,7 +856,7 @@ func TestJWTBasedAuth_AcceptsOpenIDPlusSingleVaultScope(t *testing.T) { v := newTestValidator(t, issuer, audience) derivedOrg123Owner := testJWTExpectedWorkflowOwner(t, 1, "org-123") - rawRequest := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.create","params":{"request_id":"req-1","encrypted_secrets":[{"id":{"key":"7611","namespace":"main","owner":"%s"},"encrypted_value":"cipher+/=="}]}}`, derivedOrg123Owner)) + rawRequest := fmt.Appendf(nil, `{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.create","params":{"request_id":"req-1","encrypted_secrets":[{"id":{"key":"7611","namespace":"main","owner":"%s"},"encrypted_value":"cipher+/=="}]}}`, derivedOrg123Owner) req, err := jsonrpc.DecodeRequest[json.RawMessage](rawRequest, "") require.NoError(t, err) @@ -872,8 +872,8 @@ func TestJWTBasedAuth_AcceptsOpenIDPlusSingleVaultScope(t *testing.T) { ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", "scope": "openid profile " + OAuthScopeVaultSecretsCreate, - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -897,7 +897,7 @@ func TestJWTBasedAuth_AcceptsPermissionsClaimInsteadOfScope(t *testing.T) { v := newTestValidator(t, issuer, audience) derivedOrg123Owner := testJWTExpectedWorkflowOwner(t, 1, "org-123") - rawRequest := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.list","params":{"request_id":"req-1","owner":"%s","namespace":"main"}}`, derivedOrg123Owner)) + rawRequest := fmt.Appendf(nil, `{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.list","params":{"request_id":"req-1","owner":"%s","namespace":"main"}}`, derivedOrg123Owner) req, err := jsonrpc.DecodeRequest[json.RawMessage](rawRequest, "") require.NoError(t, err) @@ -912,9 +912,9 @@ func TestJWTBasedAuth_AcceptsPermissionsClaimInsteadOfScope(t *testing.T) { "org_id": "org-123", ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", - "permissions": []interface{}{OAuthScopeVaultSecretsList}, - "authorization_details": []interface{}{ - map[string]interface{}{ + "permissions": []any{OAuthScopeVaultSecretsList}, + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -938,7 +938,7 @@ func TestJWTBasedAuth_AuthorizeCreateRequestWithoutWorkflowOwnerWhenIdentifiersU v := newTestValidator(t, issuer, audience) derivedOrg123Owner := testJWTExpectedWorkflowOwner(t, 1, "org-123") - rawRequest := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.create","params":{"request_id":"req-1","encrypted_secrets":[{"id":{"key":"7611","namespace":"main","owner":"%s"},"encrypted_value":"cipher+/=="}]}}`, derivedOrg123Owner)) + rawRequest := fmt.Appendf(nil, `{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.create","params":{"request_id":"req-1","encrypted_secrets":[{"id":{"key":"7611","namespace":"main","owner":"%s"},"encrypted_value":"cipher+/=="}]}}`, derivedOrg123Owner) req, err := jsonrpc.DecodeRequest[json.RawMessage](rawRequest, "") require.NoError(t, err) @@ -954,8 +954,8 @@ func TestJWTBasedAuth_AuthorizeCreateRequestWithoutWorkflowOwnerWhenIdentifiersU ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", "scope": OAuthScopeVaultSecretsCreate, - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -996,8 +996,8 @@ func TestJWTBasedAuth_RejectsCreateRequestWithoutWorkflowOwnerWhenIdentifierOwne ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", "scope": OAuthScopeVaultSecretsCreate, - "authorization_details": []interface{}{ - map[string]interface{}{ + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -1024,7 +1024,7 @@ func TestJWTBasedAuth_AuthorizeRequest_RejectsMissingTenantClaim(t *testing.T) { v := newTestValidator(t, issuer, audience) derivedOrg123Owner := testJWTExpectedWorkflowOwner(t, 1, "org-123") - rawRequest := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.list","params":{"request_id":"req-1","owner":"%s","namespace":"main"}}`, derivedOrg123Owner)) + rawRequest := fmt.Appendf(nil, `{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.list","params":{"request_id":"req-1","owner":"%s","namespace":"main"}}`, derivedOrg123Owner) req, err := jsonrpc.DecodeRequest[json.RawMessage](rawRequest, "") require.NoError(t, err) @@ -1038,9 +1038,9 @@ func TestJWTBasedAuth_AuthorizeRequest_RejectsMissingTenantClaim(t *testing.T) { "iat": jwt.NewNumericDate(time.Now()), "org_id": "org-123", ClaimVaultSecretManagementEnabled: "true", - "permissions": []interface{}{OAuthScopeVaultSecretsList}, - "authorization_details": []interface{}{ - map[string]interface{}{ + "permissions": []any{OAuthScopeVaultSecretsList}, + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, @@ -1071,7 +1071,7 @@ func TestJWTBasedAuth_AuthorizeRequest_RejectsTenantAgainstJobSpecMismatch(t *te require.NoError(t, err) owner := testJWTExpectedWorkflowOwner(t, 1, "org-123") - rawRequest := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.delete","params":{"request_id":"req-1","ids":[{"owner":"%s","namespace":"main","key":"k"}]}}`, owner)) + rawRequest := fmt.Appendf(nil, `{"jsonrpc":"2.0","id":"req-1","method":"vault.secrets.delete","params":{"request_id":"req-1","ids":[{"owner":"%s","namespace":"main","key":"k"}]}}`, owner) req, err := jsonrpc.DecodeRequest[json.RawMessage](rawRequest, "") require.NoError(t, err) @@ -1086,13 +1086,13 @@ func TestJWTBasedAuth_AuthorizeRequest_RejectsTenantAgainstJobSpecMismatch(t *te "org_id": "org-123", ClaimVaultSecretManagementEnabled: "true", ClaimChainlinkTenantID: "1", - "permissions": []interface{}{OAuthScopeVaultSecretsDelete}, - "authorization_details": []interface{}{ - map[string]interface{}{ + "permissions": []any{OAuthScopeVaultSecretsDelete}, + "authorization_details": []any{ + map[string]any{ "type": "request_digest", "value": digest, }, - map[string]interface{}{ + map[string]any{ "type": "workflow_owner", "value": owner, }, diff --git a/core/capabilities/vault/jwt_oauth_scope.go b/core/capabilities/vault/jwt_oauth_scope.go index 1290eca9d27..308fab8f8a2 100644 --- a/core/capabilities/vault/jwt_oauth_scope.go +++ b/core/capabilities/vault/jwt_oauth_scope.go @@ -102,10 +102,10 @@ func extractOAuthScopesFromClaims(claims jwt.MapClaims) []string { if raw, ok := claims["scope"]; ok { switch v := raw.(type) { case string: - for _, part := range strings.Fields(v) { + for part := range strings.FieldsSeq(v) { add(part) } - case []interface{}: + case []any: for _, item := range v { if s, ok := item.(string); ok { add(s) @@ -121,7 +121,7 @@ func extractOAuthScopesFromClaims(claims jwt.MapClaims) []string { // Auth0 API Authorization often emits custom permissions as a string array claim. if raw, ok := claims["permissions"]; ok { switch v := raw.(type) { - case []interface{}: + case []any: for _, item := range v { if s, ok := item.(string); ok { add(s) diff --git a/core/capabilities/vault/request_lifecycle_tracker.go b/core/capabilities/vault/request_lifecycle_tracker.go index 0550a93c728..20c2b597a69 100644 --- a/core/capabilities/vault/request_lifecycle_tracker.go +++ b/core/capabilities/vault/request_lifecycle_tracker.go @@ -424,10 +424,7 @@ func (t *RequestLifecycleTracker) emitLatenciesAndRounds(ctx context.Context, tr if !ok || at.IsZero() { return } - ms := at.Sub(base).Milliseconds() - if ms < 0 { - ms = 0 - } + ms := max(at.Sub(base).Milliseconds(), 0) t.metrics.stageLatencyMs.Record(ctx, ms, t.attrs(attribute.String("stage", stage))) } @@ -448,10 +445,7 @@ func (t *RequestLifecycleTracker) emitLatenciesAndRounds(ctx context.Context, tr if !ok { return } - delta := uint64SeqDeltaToInt64(seq, tr.blobBroadcastingSeq) - if delta < 0 { - delta = 0 - } + delta := max(uint64SeqDeltaToInt64(seq, tr.blobBroadcastingSeq), 0) t.metrics.roundDelta.Record(ctx, delta, t.attrs(attribute.String("stage", stage))) } @@ -491,9 +485,9 @@ func uint64SeqDeltaToInt64(a, b uint64) int64 { return -int64(d) } -func traceLogFields(tr *requestLifecycleTrace) []interface{} { +func traceLogFields(tr *requestLifecycleTrace) []any { baseSeq, baseOK := tr.blobBroadcastingSeq, tr.hasBlobBroadcasting - return []interface{}{ + return []any{ "receivedAt", tr.receivedAt, "blob_broadcasting", tr.hasBlobBroadcasting, "blob_broadcasting_at", tr.blobBroadcastingAt, "blob_broadcasting_seq", tr.blobBroadcastingSeq, "blob_broadcasted", tr.hasBlobBroadcasted, "blob_broadcasted_at", tr.blobBroadcastedAt, "blob_broadcasted_seq", tr.blobBroadcastedSeq, diff --git a/core/cmd/blocks_commands_test.go b/core/cmd/blocks_commands_test.go index 060f0719782..3c2197bb608 100644 --- a/core/cmd/blocks_commands_test.go +++ b/core/cmd/blocks_commands_test.go @@ -17,7 +17,7 @@ func Test_ReplayFromBlock(t *testing.T) { app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].ChainID = (*sqlutil.Big)(big.NewInt(5)) - c.EVM[0].Enabled = ptr(true) + c.EVM[0].Enabled = new(true) }) client, _ := app.NewShellAndRenderer() diff --git a/core/cmd/chains_commands_test.go b/core/cmd/chains_commands_test.go index 645b0d4551e..c0904c213ab 100644 --- a/core/cmd/chains_commands_test.go +++ b/core/cmd/chains_commands_test.go @@ -23,9 +23,9 @@ func TestShell_IndexEVMChains(t *testing.T) { t.Parallel() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) client, r := app.NewShellAndRenderer() diff --git a/core/cmd/eth_keys_commands_test.go b/core/cmd/eth_keys_commands_test.go index 51ec82aecbc..21a32478bc6 100644 --- a/core/cmd/eth_keys_commands_test.go +++ b/core/cmd/eth_keys_commands_test.go @@ -28,7 +28,8 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/web/presenters" ) -func ptr[T any](t T) *T { return &t } +//go:fix inline +func ptr[T any](t T) *T { return new(t) } func TestEthKeysPresenter_RenderTable(t *testing.T) { t.Parallel() @@ -94,9 +95,9 @@ func TestShell_ListETHKeys(t *testing.T) { ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(commonassets.NewLinkFromJuels(13), nil) ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Maybe() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }, withKey(), withMocks(ethClient), @@ -119,9 +120,9 @@ func TestShell_ListETHKeys_Error(t *testing.T) { ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(nil, errors.New("fake error")) ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Maybe() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }, withKey(), withMocks(ethClient), @@ -141,7 +142,7 @@ func TestShell_ListETHKeys_Disabled(t *testing.T) { ethClient := newEthMock(t) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(false) + c.EVM[0].Enabled = new(false) }, withKey(), withMocks(ethClient), @@ -174,9 +175,9 @@ func TestShell_CreateETHKey(t *testing.T) { ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Maybe() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }, withKey(), withMocks(ethClient), @@ -210,9 +211,9 @@ func TestShell_DeleteETHKey(t *testing.T) { t.Parallel() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }, withKey(), ) @@ -248,9 +249,9 @@ func TestShell_ImportExportETHKey_NoChains(t *testing.T) { ethClient.On("LINKBalance", mock.Anything, mock.Anything, mock.Anything).Return(commonassets.NewLinkFromJuels(42), nil) ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Maybe() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }, withMocks(ethClient), ) @@ -352,9 +353,9 @@ func TestShell_ImportExportETHKey_WithChains(t *testing.T) { ethClient := newEthMock(t) ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Maybe() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }, withMocks(ethClient), ) diff --git a/core/cmd/evm_transaction_commands_test.go b/core/cmd/evm_transaction_commands_test.go index 97f1b362fcd..7285146cd08 100644 --- a/core/cmd/evm_transaction_commands_test.go +++ b/core/cmd/evm_transaction_commands_test.go @@ -144,9 +144,9 @@ func TestShell_SendEther_From_Txm(t *testing.T) { ethMock.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) // NOTE: FallbackPollInterval is used in this test to quickly create TxAttempts // Testing triggers requires committing transactions and does not work with transactional tests @@ -207,9 +207,9 @@ func TestShell_SendEther_From_Txm_WEI(t *testing.T) { ethMock.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) // NOTE: FallbackPollInterval is used in this test to quickly create TxAttempts // Testing triggers requires committing transactions and does not work with transactional tests diff --git a/core/cmd/forwarders_commands_test.go b/core/cmd/forwarders_commands_test.go index 4e8838affce..9e974237430 100644 --- a/core/cmd/forwarders_commands_test.go +++ b/core/cmd/forwarders_commands_test.go @@ -68,7 +68,7 @@ func TestShell_TrackEVMForwarder(t *testing.T) { id := newRandChainID() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].ChainID = id - c.EVM[0].Enabled = ptr(true) + c.EVM[0].Enabled = new(true) }) client, r := app.NewShellAndRenderer() @@ -113,7 +113,7 @@ func TestShell_TrackEVMForwarder_BadAddress(t *testing.T) { id := newRandChainID() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM[0].ChainID = id - c.EVM[0].Enabled = ptr(true) + c.EVM[0].Enabled = new(true) }) client, _ := app.NewShellAndRenderer() @@ -132,7 +132,7 @@ func TestShell_DeleteEVMForwarders_MissingFwdId(t *testing.T) { t.Parallel() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) + c.EVM[0].Enabled = new(true) }) client, _ := app.NewShellAndRenderer() diff --git a/core/cmd/jobs_commands_test.go b/core/cmd/jobs_commands_test.go index aba93d91487..0aea86e02c4 100644 --- a/core/cmd/jobs_commands_test.go +++ b/core/cmd/jobs_commands_test.go @@ -275,7 +275,6 @@ func TestJob_ToRows(t *testing.T) { }, job.ToRows()) } - //go:embed ocr-bootstrap-spec.yml var ocrBootstrapSpec string @@ -284,14 +283,14 @@ func TestShell_CreateJobV2(t *testing.T) { app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Database.Listener.FallbackPollInterval = commonconfig.MustNewDuration(100 * time.Millisecond) - c.OCR.Enabled = ptr(true) - c.P2P.V2.Enabled = ptr(true) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) - c.EVM[0].GasEstimator.Mode = ptr("FixedPrice") + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) + c.EVM[0].GasEstimator.Mode = new("FixedPrice") }, func(opts *startOptions) { opts.FlagsAndDeps = append(opts.FlagsAndDeps, cltest.DefaultP2PKey) }) @@ -317,7 +316,6 @@ func TestShell_CreateJobV2(t *testing.T) { assert.Equal(t, "0x27548a32b9aD5D64c5945EaE9Da5337bc3169D15", output.OffChainReportingSpec.ContractAddress.String()) } - func requireJobsCount(t *testing.T, orm job.ORM, expected int) { ctx := testutils.Context(t) jobs, _, err := orm.FindJobs(ctx, 0, 1000) diff --git a/core/cmd/node_commands_test.go b/core/cmd/node_commands_test.go index 3841d8ddece..32a9e38fd21 100644 --- a/core/cmd/node_commands_test.go +++ b/core/cmd/node_commands_test.go @@ -31,18 +31,18 @@ func TestShell_IndexEVMNodes(t *testing.T) { chainID := newRandChainID() node1 := configtoml.Node{ - Name: ptr("Test node 1"), + Name: new("Test node 1"), WSURL: config.MustParseURL("ws://localhost:8546"), HTTPURL: config.MustParseURL("http://localhost:8546"), - SendOnly: ptr(false), - Order: ptr(int32(15)), + SendOnly: new(false), + Order: new(int32(15)), } node2 := configtoml.Node{ - Name: ptr("Test node 2"), + Name: new("Test node 2"), WSURL: config.MustParseURL("ws://localhost:8547"), HTTPURL: config.MustParseURL("http://localhost:8547"), - SendOnly: ptr(false), - Order: ptr(int32(36)), + SendOnly: new(false), + Order: new(int32(36)), } chain := configtoml.EVMConfig{ ChainID: chainID, @@ -93,4 +93,3 @@ func TestShell_IndexEVMNodes(t *testing.T) { assert.Contains(t, renderLines[14], "State") assert.Contains(t, renderLines[14], n2.State) } - diff --git a/core/cmd/shell_local_test.go b/core/cmd/shell_local_test.go index 1682c8dbe16..5756715354a 100644 --- a/core/cmd/shell_local_test.go +++ b/core/cmd/shell_local_test.go @@ -113,7 +113,7 @@ func TestShell_RunNodeWithAPICredentialsFile(t *testing.T) { t.Run(test.name, func(t *testing.T) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { s.Password.Keystore = models.NewSecret("16charlengthp4SsW0rD1!@#_") - c.EVM[0].Nodes[0].Name = ptr("fake") + c.EVM[0].Nodes[0].Name = new("fake") c.EVM[0].Nodes[0].WSURL = commonconfig.MustParseURL("WSS://fake.com/ws") c.EVM[0].Nodes[0].HTTPURL = commonconfig.MustParseURL("http://fake.com") // seems to be needed for config validate @@ -473,7 +473,7 @@ func TestShell_RemoveBlocks(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { s.Password.Keystore = models.NewSecret("dummy") - c.EVM[0].Nodes[0].Name = ptr("fake") + c.EVM[0].Nodes[0].Name = new("fake") c.EVM[0].Nodes[0].HTTPURL = commonconfig.MustParseURL("http://fake.com") c.EVM[0].Nodes[0].WSURL = commonconfig.MustParseURL("WSS://fake.com/ws") // seems to be needed for config validate @@ -732,7 +732,7 @@ func TestShell_RunNode_WithBeforeNode(t *testing.T) { t.Run(test.name, func(t *testing.T) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { s.Password.Keystore = models.NewSecret("dummy") - c.EVM[0].Nodes[0].Name = ptr("fake") + c.EVM[0].Nodes[0].Name = new("fake") c.EVM[0].Nodes[0].HTTPURL = commonconfig.MustParseURL("http://fake.com") c.EVM[0].Nodes[0].WSURL = commonconfig.MustParseURL("WSS://fake.com/ws") // seems to be needed for config validate diff --git a/core/cmd/shell_remote_test.go b/core/cmd/shell_remote_test.go index 319dcbe0c47..2359f9ce71a 100644 --- a/core/cmd/shell_remote_test.go +++ b/core/cmd/shell_remote_test.go @@ -118,10 +118,10 @@ func deleteKeyExportFile(t *testing.T) { func TestShell_ReplayBlocks(t *testing.T) { t.Parallel() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(true) - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) - c.EVM[0].GasEstimator.Mode = ptr("FixedPrice") + c.EVM[0].Enabled = new(true) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) + c.EVM[0].GasEstimator.Mode = new("FixedPrice") }) client, _ := app.NewShellAndRenderer() @@ -156,7 +156,7 @@ func TestShell_CreateExternalInitiator(t *testing.T) { t.Run(test.name, func(t *testing.T) { ctx := testutils.Context(t) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) }) client, _ := app.NewShellAndRenderer() @@ -195,7 +195,7 @@ func TestShell_CreateExternalInitiator_Errors(t *testing.T) { test := tt t.Run(test.name, func(t *testing.T) { app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) }) client, _ := app.NewShellAndRenderer() @@ -220,7 +220,7 @@ func TestShell_DestroyExternalInitiator(t *testing.T) { t.Parallel() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) }) client, r := app.NewShellAndRenderer() @@ -246,7 +246,7 @@ func TestShell_DestroyExternalInitiator_NotFound(t *testing.T) { t.Parallel() app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) }) client, r := app.NewShellAndRenderer() @@ -541,12 +541,12 @@ func TestShell_RunOCRJob_HappyPath(t *testing.T) { ctx := testutils.Context(t) app := startNewApplicationV2(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.JobPipeline.HTTPRequest.DefaultTimeout = commonconfig.MustNewDuration(2 * time.Second) - c.EVM[0].Enabled = ptr(true) - c.OCR.Enabled = ptr(true) - c.P2P.V2.Enabled = ptr(true) + c.EVM[0].Enabled = new(true) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID - c.EVM[0].GasEstimator.Mode = ptr("FixedPrice") + c.EVM[0].GasEstimator.Mode = new("FixedPrice") }, func(opts *startOptions) { opts.FlagsAndDeps = append(opts.FlagsAndDeps, cltest.DefaultP2PKey) }) diff --git a/core/cmd/shell_test.go b/core/cmd/shell_test.go index 905b57501b4..649da07841c 100644 --- a/core/cmd/shell_test.go +++ b/core/cmd/shell_test.go @@ -463,7 +463,7 @@ func TestSetupStarkNetRelayer(t *testing.T) { }, { "ChainID": "disabled-starknet-id-1", - "Enabled": ptr(false), + "Enabled": new(false), "FeederURL": commoncfg.MustParseURL("https://feeder.url"), }, } diff --git a/core/config/toml/types.go b/core/config/toml/types.go index 1fbd21c1bc8..98afb79a127 100644 --- a/core/config/toml/types.go +++ b/core/config/toml/types.go @@ -2826,9 +2826,7 @@ func (c *CapabilityNodeConfig) setFrom(f *CapabilityNodeConfig) { if c.Config == nil { c.Config = make(map[string]string) } - for k, v := range f.Config { - c.Config[k] = v - } + maps.Copy(c.Config, f.Config) } } diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index 4674980f7ab..8bd3785873a 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -1308,7 +1308,7 @@ type EthereumLogIterator interface{ Next() bool } func GetLogs(t *testing.T, rv any, logs EthereumLogIterator) []any { v := reflect.ValueOf(rv) require.True(t, rv == nil || - v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Slice, + v.Kind() == reflect.Pointer && v.Elem().Kind() == reflect.Slice, "must pass a slice to receive logs") var e reflect.Value if rv != nil { @@ -1317,7 +1317,7 @@ func GetLogs(t *testing.T, rv any, logs EthereumLogIterator) []any { var irv []any for logs.Next() { log := reflect.Indirect(reflect.ValueOf(logs)).FieldByName("Event") - if v.Kind() == reflect.Ptr { + if v.Kind() == reflect.Pointer { e.Set(reflect.Append(e, log)) } irv = append(irv, log.Interface()) diff --git a/core/internal/testutils/testutils.go b/core/internal/testutils/testutils.go index d0e906e541a..911e7a217a2 100644 --- a/core/internal/testutils/testutils.go +++ b/core/internal/testutils/testutils.go @@ -248,6 +248,8 @@ func AssertCount(t testing.TB, ds sqlutil.DataSource, tableName string, expected // Ptr takes pointer of anything // // Deprecated: use new() +// +//go:fix inline func Ptr[T any](v T) *T { - return &v + return new(v) } diff --git a/core/logger/logger_unix.go b/core/logger/logger_unix.go index 77034468879..41c0b2ff133 100644 --- a/core/logger/logger_unix.go +++ b/core/logger/logger_unix.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows package logger diff --git a/core/logger/logger_windows.go b/core/logger/logger_windows.go index d067bcd26f9..0de01e87b31 100644 --- a/core/logger/logger_windows.go +++ b/core/logger/logger_windows.go @@ -1,5 +1,4 @@ //go:build windows -// +build windows package logger diff --git a/core/services/arbiter/arbiter.go b/core/services/arbiter/arbiter.go index bd368151c50..d173d7557e7 100644 --- a/core/services/arbiter/arbiter.go +++ b/core/services/arbiter/arbiter.go @@ -105,11 +105,9 @@ func (a *arbiter) Start(ctx context.Context) error { } // Start gRPC server in a goroutine - a.wg.Add(1) - go func() { - defer a.wg.Done() + a.wg.Go(func() { a.runGRPCServer(ctx) - }() + }) a.lggr.Infow("Arbiter service started", "grpcAddr", a.grpcAddr, diff --git a/core/services/arbiter/grpc_server_test.go b/core/services/arbiter/grpc_server_test.go index cb8d3a12c62..f8787834955 100644 --- a/core/services/arbiter/grpc_server_test.go +++ b/core/services/arbiter/grpc_server_test.go @@ -139,7 +139,7 @@ func TestGRPCServer_GetDesiredReplicas_LargeShardCount(t *testing.T) { // Simulate many healthy shards status := make(map[uint32]*ringpb.ShardStatus) - for i := uint32(0); i < 100; i++ { + for i := range uint32(100) { status[i] = &ringpb.ShardStatus{IsHealthy: true} } diff --git a/core/services/arbiter/shardconfig.go b/core/services/arbiter/shardconfig.go index 588c7497575..3bfec6463fb 100644 --- a/core/services/arbiter/shardconfig.go +++ b/core/services/arbiter/shardconfig.go @@ -84,11 +84,9 @@ func (s *shardConfigSyncer) Start(ctx context.Context) error { s.lggr.Info("Starting ShardConfig syncer") // Start async initialization and polling - s.wg.Add(1) - go func() { - defer s.wg.Done() + s.wg.Go(func() { s.run() - }() + }) return nil }) diff --git a/core/services/arbiter/state_test.go b/core/services/arbiter/state_test.go index 595e017a1f5..f6e2e163378 100644 --- a/core/services/arbiter/state_test.go +++ b/core/services/arbiter/state_test.go @@ -69,7 +69,7 @@ func TestState_Concurrency(t *testing.T) { var wg sync.WaitGroup // Run concurrent writes and reads - for i := 0; i < 100; i++ { + for i := range 100 { wg.Add(3) // Writer goroutine - SetCurrentReplicas diff --git a/core/services/chainlink/config_general.go b/core/services/chainlink/config_general.go index fd75e41e5bb..77e72388d1b 100644 --- a/core/services/chainlink/config_general.go +++ b/core/services/chainlink/config_general.go @@ -263,12 +263,12 @@ func validateEnv() (err error) { if strings.TrimSpace(kv) == "" { continue } - i := strings.Index(kv, "=") - if i == -1 { + before, _, ok := strings.Cut(kv, "=") + if !ok { return errors.Errorf("malformed .env file line: %s", kv) } - k := kv[:i] - _, ok := os.LookupEnv(k) + k := before + _, ok = os.LookupEnv(k) if ok { err = stderrors.Join(err, fmt.Errorf("environment variable %s must not be set: %w", k, v2.ErrUnsupported)) } diff --git a/core/services/chainlink/config_telemetry_test.go b/core/services/chainlink/config_telemetry_test.go index bfbea39f69c..c01204fb85e 100644 --- a/core/services/chainlink/config_telemetry_test.go +++ b/core/services/chainlink/config_telemetry_test.go @@ -60,7 +60,7 @@ func TestTelemetryConfig_CACertFile(t *testing.T) { telemetry toml.Telemetry expected string }{ - {"CACertFileSet", toml.Telemetry{CACertFile: ptr("test.pem")}, "test.pem"}, + {"CACertFileSet", toml.Telemetry{CACertFile: new("test.pem")}, "test.pem"}, {"CACertFileNil", toml.Telemetry{CACertFile: nil}, ""}, } @@ -78,7 +78,7 @@ func TestTelemetryConfig_OtelExporterGRPCEndpoint(t *testing.T) { telemetry toml.Telemetry expected string }{ - {"EndpointSet", toml.Telemetry{Endpoint: ptr("localhost:4317")}, "localhost:4317"}, + {"EndpointSet", toml.Telemetry{Endpoint: new("localhost:4317")}, "localhost:4317"}, {"EndpointNil", toml.Telemetry{Endpoint: nil}, ""}, } @@ -133,7 +133,7 @@ func TestTelemetryConfig_TraceSampleRatio(t *testing.T) { telemetry toml.Telemetry expected float64 }{ - {"TraceSampleRatioSet", toml.Telemetry{TraceSampleRatio: ptrFloat(0.5)}, 0.5}, + {"TraceSampleRatioSet", toml.Telemetry{TraceSampleRatio: new(0.5)}, 0.5}, } for _, tt := range tests { @@ -150,8 +150,8 @@ func TestTelemetryConfig_EmitterBatchProcessor(t *testing.T) { telemetry toml.Telemetry expected bool }{ - {"EmitterBatchProcessorTrue", toml.Telemetry{EmitterBatchProcessor: ptr(true)}, true}, - {"EmitterBatchProcessorFalse", toml.Telemetry{EmitterBatchProcessor: ptr(false)}, false}, + {"EmitterBatchProcessorTrue", toml.Telemetry{EmitterBatchProcessor: new(true)}, true}, + {"EmitterBatchProcessorFalse", toml.Telemetry{EmitterBatchProcessor: new(false)}, false}, } for _, tt := range tests { @@ -187,9 +187,9 @@ func TestTelemetryConfig_ChipIngressEndpoint(t *testing.T) { telemetry toml.Telemetry expected string }{ - {"ChipIngressEndpointSet", toml.Telemetry{ChipIngressEndpoint: ptr("localhost:8080")}, "localhost:8080"}, + {"ChipIngressEndpointSet", toml.Telemetry{ChipIngressEndpoint: new("localhost:8080")}, "localhost:8080"}, {"ChipIngressEndpointNil", toml.Telemetry{ChipIngressEndpoint: nil}, ""}, - {"ChipIngressEndpointEmpty", toml.Telemetry{ChipIngressEndpoint: ptr("")}, ""}, + {"ChipIngressEndpointEmpty", toml.Telemetry{ChipIngressEndpoint: new("")}, ""}, } for _, tt := range tests { @@ -206,8 +206,8 @@ func TestTelemetryConfig_ChipIngressInsecureConnection(t *testing.T) { telemetry toml.Telemetry expected bool }{ - {"ChipIngressInsecureConnectionTrue", toml.Telemetry{ChipIngressInsecureConnection: ptr(true)}, true}, - {"ChipIngressInsecureConnectionFalse", toml.Telemetry{ChipIngressInsecureConnection: ptr(false)}, false}, + {"ChipIngressInsecureConnectionTrue", toml.Telemetry{ChipIngressInsecureConnection: new(true)}, true}, + {"ChipIngressInsecureConnectionFalse", toml.Telemetry{ChipIngressInsecureConnection: new(false)}, false}, } for _, tt := range tests { @@ -225,8 +225,8 @@ func TestTelemetryConfig_ChipIngressBatchEmitterEnabled(t *testing.T) { expected bool }{ {"DefaultNil", toml.Telemetry{ChipIngressBatchEmitterEnabled: nil}, true}, - {"ExplicitTrue", toml.Telemetry{ChipIngressBatchEmitterEnabled: ptr(true)}, true}, - {"ExplicitFalse", toml.Telemetry{ChipIngressBatchEmitterEnabled: ptr(false)}, false}, + {"ExplicitTrue", toml.Telemetry{ChipIngressBatchEmitterEnabled: new(true)}, true}, + {"ExplicitFalse", toml.Telemetry{ChipIngressBatchEmitterEnabled: new(false)}, false}, } for _, tt := range tests { @@ -245,7 +245,7 @@ func TestTelemetryConfig_DurableEmitterMaxQueuePayloadBytes(t *testing.T) { telemetry toml.Telemetry expected int64 }{ - {"Set", toml.Telemetry{DurableEmitterMaxQueuePayloadBytes: ptr[int64](2048)}, 2048}, + {"Set", toml.Telemetry{DurableEmitterMaxQueuePayloadBytes: new(int64(2048))}, 2048}, {"Nil", toml.Telemetry{DurableEmitterMaxQueuePayloadBytes: nil}, 1 << 30}, // Default 1 GiB } @@ -263,10 +263,6 @@ func ptrDuration(d time.Duration) *config.Duration { return config.MustNewDuration(d) } -func ptrFloat(f float64) *float64 { - return &f -} - func TestTelemetryConfig_HeartbeatInterval(t *testing.T) { tests := []struct { name string @@ -292,8 +288,8 @@ func TestTelemetryConfig_LogStreamingEnabled(t *testing.T) { telemetry toml.Telemetry expected bool }{ - {"LogStreamingEnabledTrue", toml.Telemetry{LogStreamingEnabled: ptr(true)}, true}, - {"LogStreamingEnabledFalse", toml.Telemetry{LogStreamingEnabled: ptr(false)}, false}, + {"LogStreamingEnabledTrue", toml.Telemetry{LogStreamingEnabled: new(true)}, true}, + {"LogStreamingEnabledFalse", toml.Telemetry{LogStreamingEnabled: new(false)}, false}, } for _, tt := range tests { @@ -310,12 +306,12 @@ func TestTelemetryConfig_LogLevel(t *testing.T) { telemetry toml.Telemetry expected zapcore.Level }{ - {"LogLevelSet", toml.Telemetry{LogLevel: ptr("debug")}, zapcore.DebugLevel}, - {"LogLevelInfo", toml.Telemetry{LogLevel: ptr("info")}, zapcore.InfoLevel}, - {"LogLevelWarn", toml.Telemetry{LogLevel: ptr("warn")}, zapcore.WarnLevel}, - {"LogLevelError", toml.Telemetry{LogLevel: ptr("error")}, zapcore.ErrorLevel}, + {"LogLevelSet", toml.Telemetry{LogLevel: new("debug")}, zapcore.DebugLevel}, + {"LogLevelInfo", toml.Telemetry{LogLevel: new("info")}, zapcore.InfoLevel}, + {"LogLevelWarn", toml.Telemetry{LogLevel: new("warn")}, zapcore.WarnLevel}, + {"LogLevelError", toml.Telemetry{LogLevel: new("error")}, zapcore.ErrorLevel}, {"LogLevelNil", toml.Telemetry{LogLevel: nil}, zapcore.InfoLevel}, - {"LogLevelInvalid", toml.Telemetry{LogLevel: ptr("invalid")}, zapcore.InfoLevel}, + {"LogLevelInvalid", toml.Telemetry{LogLevel: new("invalid")}, zapcore.InfoLevel}, } for _, tt := range tests { @@ -332,8 +328,8 @@ func TestTelemetryConfig_LogBatchProcessor(t *testing.T) { telemetry toml.Telemetry expected bool }{ - {"LogBatchProcessorTrue", toml.Telemetry{LogBatchProcessor: ptr(true)}, true}, - {"LogBatchProcessorFalse", toml.Telemetry{LogBatchProcessor: ptr(false)}, false}, + {"LogBatchProcessorTrue", toml.Telemetry{LogBatchProcessor: new(true)}, true}, + {"LogBatchProcessorFalse", toml.Telemetry{LogBatchProcessor: new(false)}, false}, {"LogBatchProcessorNil", toml.Telemetry{LogBatchProcessor: nil}, true}, // Default value } @@ -368,7 +364,7 @@ func TestTelemetryConfig_LogExportMaxBatchSize(t *testing.T) { telemetry toml.Telemetry expected int }{ - {"LogExportMaxBatchSizeSet", toml.Telemetry{LogExportMaxBatchSize: ptrInt(512)}, 512}, + {"LogExportMaxBatchSizeSet", toml.Telemetry{LogExportMaxBatchSize: new(512)}, 512}, {"LogExportMaxBatchSizeNil", toml.Telemetry{LogExportMaxBatchSize: nil}, 512}, // Default value } @@ -380,10 +376,6 @@ func TestTelemetryConfig_LogExportMaxBatchSize(t *testing.T) { } } -func ptrInt(i int) *int { - return &i -} - func TestTelemetryConfig_LogExportInterval(t *testing.T) { tests := []struct { name string @@ -408,7 +400,7 @@ func TestTelemetryConfig_LogMaxQueueSize(t *testing.T) { telemetry toml.Telemetry expected int }{ - {"LogMaxQueueSizeSet", toml.Telemetry{LogMaxQueueSize: ptrInt(2048)}, 2048}, + {"LogMaxQueueSizeSet", toml.Telemetry{LogMaxQueueSize: new(2048)}, 2048}, {"LogMaxQueueSizeNil", toml.Telemetry{LogMaxQueueSize: nil}, 2048}, // Default value } diff --git a/core/services/chainlink/config_test.go b/core/services/chainlink/config_test.go index 97a7d484250..05d2177abfd 100644 --- a/core/services/chainlink/config_test.go +++ b/core/services/chainlink/config_test.go @@ -48,11 +48,11 @@ var ( multiChain = Config{ Core: toml.Core{ - RootDir: ptr("my/root/dir"), + RootDir: new("my/root/dir"), AuditLogger: toml.AuditLogger{ - Enabled: ptr(true), + Enabled: new(true), ForwardToUrl: mustURL("http://localhost:9898"), - Headers: ptr([]models.ServiceHeader{ + Headers: new([]models.ServiceHeader{ { Header: "Authorization", Value: "token", @@ -62,7 +62,7 @@ var ( Value: "value with spaces | and a bar+*", }, }), - JsonWrapperKey: ptr("event"), + JsonWrapperKey: new("event"), }, Database: toml.Database{ Listener: toml.DatabaseListener{ @@ -71,7 +71,7 @@ var ( }, Log: toml.Log{ Level: ptr(toml.LogLevel(zapcore.PanicLevel)), - JSONConsole: ptr(true), + JSONConsole: new(true), }, JobPipeline: toml.JobPipeline{ HTTPRequest: toml.JobPipelineHTTPRequest{ @@ -79,23 +79,23 @@ var ( }, }, OCR2: toml.OCR2{ - Enabled: ptr(true), + Enabled: new(true), DatabaseTimeout: commoncfg.MustNewDuration(20 * time.Second), }, OCR: toml.OCR{ - Enabled: ptr(true), + Enabled: new(true), BlockchainTimeout: commoncfg.MustNewDuration(5 * time.Second), }, P2P: toml.P2P{ - IncomingMessageBufferSize: ptr[int64](999), + IncomingMessageBufferSize: new(int64(999)), }, AutoPprof: toml.AutoPprof{ - CPUProfileRate: ptr[int64](7), + CPUProfileRate: new(int64(7)), }, Workflows: toml.Workflows{ Limits: toml.Limits{ - Global: ptr(int32(200)), - PerOwner: ptr(int32(200)), + Global: new(int32(200)), + PerOwner: new(int32(200)), }, }, }, @@ -103,21 +103,21 @@ var ( { ChainID: sqlutil.NewI(1), Chain: evmcfg.Chain{ - FinalityDepth: ptr[uint32](26), - SafeDepth: ptr[uint32](0), - FinalityTagEnabled: ptr[bool](true), - SafeTagSupported: ptr(true), - FinalizedBlockOffset: ptr[uint32](12), + FinalityDepth: new(uint32(26)), + SafeDepth: new(uint32(0)), + FinalityTagEnabled: new(true), + SafeTagSupported: new(true), + FinalizedBlockOffset: new(uint32(12)), }, Nodes: []*evmcfg.Node{ { - Name: ptr("primary"), + Name: new("primary"), WSURL: mustURL("wss://web.socket/mainnet"), }, { - Name: ptr("secondary"), + Name: new("secondary"), HTTPURL: mustURL("http://broadcast.mirror"), - SendOnly: ptr(true), + SendOnly: new(true), }, }}, { @@ -129,7 +129,7 @@ var ( }, Nodes: []*evmcfg.Node{ { - Name: ptr("foo"), + Name: new("foo"), WSURL: mustURL("wss://web.socket/test/foo"), }, }}, @@ -137,12 +137,12 @@ var ( ChainID: sqlutil.NewI(137), Chain: evmcfg.Chain{ GasEstimator: evmcfg.GasEstimator{ - Mode: ptr("FixedPrice"), + Mode: new("FixedPrice"), }, }, Nodes: []*evmcfg.Node{ { - Name: ptr("bar"), + Name: new("bar"), WSURL: mustURL("wss://web.socket/test/bar"), }, }}, @@ -174,23 +174,23 @@ func TestConfig_Marshal(t *testing.T) { global := Config{ Core: toml.Core{ - InsecureFastScrypt: ptr(true), - InsecurePPROFHeap: ptr(true), - RootDir: ptr("test/root/dir"), + InsecureFastScrypt: new(true), + InsecurePPROFHeap: new(true), + RootDir: new("test/root/dir"), ShutdownGracePeriod: commoncfg.MustNewDuration(10 * time.Second), Insecure: toml.Insecure{ - DevWebServer: ptr(false), - OCRDevelopmentMode: ptr(false), - InfiniteDepthQueries: ptr(false), - DisableRateLimiting: ptr(false), + DevWebServer: new(false), + OCRDevelopmentMode: new(false), + InfiniteDepthQueries: new(false), + DisableRateLimiting: new(false), }, Tracing: toml.Tracing{ - Enabled: ptr(true), - CollectorTarget: ptr("localhost:4317"), - NodeID: ptr("clc-ocr-sol-devnet-node-1"), - SamplingRatio: ptr(1.0), - Mode: ptr("tls"), - TLSCertPath: ptr("/path/to/cert.pem"), + Enabled: new(true), + CollectorTarget: new("localhost:4317"), + NodeID: new("clc-ocr-sol-devnet-node-1"), + SamplingRatio: new(1.0), + Mode: new("tls"), + TLSCertPath: new("/path/to/cert.pem"), Attributes: map[string]string{ "test": "load", "env": "dev", @@ -206,193 +206,193 @@ func TestConfig_Marshal(t *testing.T) { {Header: "X-SomeOther-Header", Value: "value with spaces | and a bar+*"}, } full.AuditLogger = toml.AuditLogger{ - Enabled: ptr(true), + Enabled: new(true), ForwardToUrl: mustURL("http://localhost:9898"), - Headers: ptr(serviceHeaders), - JsonWrapperKey: ptr("event"), + Headers: new(serviceHeaders), + JsonWrapperKey: new("event"), } full.Feature = toml.Feature{ - FeedsManager: ptr(true), - LogPoller: ptr(true), - UICSAKeys: ptr(true), - CCIP: ptr(true), - MultiFeedsManagers: ptr(true), + FeedsManager: new(true), + LogPoller: new(true), + UICSAKeys: new(true), + CCIP: new(true), + MultiFeedsManagers: new(true), } full.Database = toml.Database{ DefaultIdleInTxSessionTimeout: commoncfg.MustNewDuration(time.Minute), DefaultLockTimeout: commoncfg.MustNewDuration(time.Hour), DefaultQueryTimeout: commoncfg.MustNewDuration(time.Second), - LogQueries: ptr(true), - MigrateOnStartup: ptr(true), - MaxIdleConns: ptr[int64](7), - MaxOpenConns: ptr[int64](13), + LogQueries: new(true), + MigrateOnStartup: new(true), + MaxIdleConns: new(int64(7)), + MaxOpenConns: new(int64(13)), Listener: toml.DatabaseListener{ MaxReconnectDuration: commoncfg.MustNewDuration(time.Minute), MinReconnectInterval: commoncfg.MustNewDuration(5 * time.Minute), FallbackPollInterval: commoncfg.MustNewDuration(2 * time.Minute), }, Lock: toml.DatabaseLock{ - Enabled: ptr(false), + Enabled: new(false), LeaseDuration: &minute, LeaseRefreshInterval: &second, }, Backup: toml.DatabaseBackup{ - Dir: ptr("test/backup/dir"), + Dir: new("test/backup/dir"), Frequency: &hour, Mode: &config.DatabaseBackupModeFull, - OnVersionUpgrade: ptr(true), + OnVersionUpgrade: new(true), }, } full.TelemetryIngress = toml.TelemetryIngress{ - UniConn: ptr(false), - Logging: ptr(true), - BufferSize: ptr[uint16](1234), - MaxBatchSize: ptr[uint16](4321), + UniConn: new(false), + Logging: new(true), + BufferSize: new(uint16(1234)), + MaxBatchSize: new(uint16(4321)), SendInterval: commoncfg.MustNewDuration(time.Minute), SendTimeout: commoncfg.MustNewDuration(5 * time.Second), - UseBatchSend: ptr(true), - ChipIngressEnabled: ptr(false), + UseBatchSend: new(true), + ChipIngressEnabled: new(false), Endpoints: []toml.TelemetryIngressEndpoint{{ - Network: ptr("EVM"), - ChainID: ptr("1"), - ServerPubKey: ptr("test-pub-key"), + Network: new("EVM"), + ChainID: new("1"), + ServerPubKey: new("test-pub-key"), URL: mustURL("prom.test")}, }, } full.Log = toml.Log{ Level: ptr(toml.LogLevel(zapcore.DPanicLevel)), - JSONConsole: ptr(true), - UnixTS: ptr(true), + JSONConsole: new(true), + UnixTS: new(true), File: toml.LogFile{ - Dir: ptr("log/file/dir"), - MaxSize: ptr[utils.FileSize](100 * utils.GB), - MaxAgeDays: ptr[int64](17), - MaxBackups: ptr[int64](9), + Dir: new("log/file/dir"), + MaxSize: new((utils.FileSize)(100 * utils.GB)), + MaxAgeDays: new(int64(17)), + MaxBackups: new(int64(9)), }, } full.WebServer = toml.WebServer{ - AuthenticationMethod: ptr("local"), - AllowOrigins: ptr("*"), + AuthenticationMethod: new("local"), + AllowOrigins: new("*"), BridgeResponseURL: mustURL("https://bridge.response"), BridgeCacheTTL: commoncfg.MustNewDuration(10 * time.Second), HTTPWriteTimeout: commoncfg.MustNewDuration(time.Minute), - HTTPPort: ptr[uint16](56), - SecureCookies: ptr(true), + HTTPPort: new(uint16(56)), + SecureCookies: new(true), SessionTimeout: commoncfg.MustNewDuration(time.Hour), SessionReaperExpiration: commoncfg.MustNewDuration(7 * 24 * time.Hour), HTTPMaxSize: ptr(utils.FileSize(uint64(32770))), StartTimeout: commoncfg.MustNewDuration(15 * time.Second), ListenIP: mustIP("192.158.1.37"), MFA: toml.WebServerMFA{ - RPID: ptr("test-rpid"), - RPOrigin: ptr("test-rp-origin"), + RPID: new("test-rpid"), + RPOrigin: new("test-rp-origin"), }, LDAP: toml.WebServerLDAP{ - ServerTLS: ptr(true), + ServerTLS: new(true), SessionTimeout: commoncfg.MustNewDuration(15 * time.Minute), QueryTimeout: commoncfg.MustNewDuration(2 * time.Minute), - BaseUserAttr: ptr("uid"), - BaseDN: ptr("dc=custom,dc=example,dc=com"), - UsersDN: ptr("ou=users"), - GroupsDN: ptr("ou=groups"), - ActiveAttribute: ptr("organizationalStatus"), - ActiveAttributeAllowedValue: ptr("ACTIVE"), - AdminUserGroupCN: ptr("NodeAdmins"), - EditUserGroupCN: ptr("NodeEditors"), - RunUserGroupCN: ptr("NodeRunners"), - ReadUserGroupCN: ptr("NodeReadOnly"), - UserApiTokenEnabled: ptr(false), + BaseUserAttr: new("uid"), + BaseDN: new("dc=custom,dc=example,dc=com"), + UsersDN: new("ou=users"), + GroupsDN: new("ou=groups"), + ActiveAttribute: new("organizationalStatus"), + ActiveAttributeAllowedValue: new("ACTIVE"), + AdminUserGroupCN: new("NodeAdmins"), + EditUserGroupCN: new("NodeEditors"), + RunUserGroupCN: new("NodeRunners"), + ReadUserGroupCN: new("NodeReadOnly"), + UserApiTokenEnabled: new(false), UserAPITokenDuration: commoncfg.MustNewDuration(240 * time.Hour), UpstreamSyncInterval: commoncfg.MustNewDuration(0 * time.Second), UpstreamSyncRateLimit: commoncfg.MustNewDuration(2 * time.Minute), }, OIDC: toml.WebServerOIDC{ - ClientID: ptr("abcd1234"), - ProviderURL: ptr("https://id.provider.com/oauth2/default"), - RedirectURL: ptr("http://localhost:3000/signin"), - ClaimName: ptr("groups"), - AdminClaim: ptr("NodeAdmins"), - EditClaim: ptr("NodeEditors"), - RunClaim: ptr("NodeRunners"), - ReadClaim: ptr("NodeReadOnly"), + ClientID: new("abcd1234"), + ProviderURL: new("https://id.provider.com/oauth2/default"), + RedirectURL: new("http://localhost:3000/signin"), + ClaimName: new("groups"), + AdminClaim: new("NodeAdmins"), + EditClaim: new("NodeEditors"), + RunClaim: new("NodeRunners"), + ReadClaim: new("NodeReadOnly"), SessionTimeout: commoncfg.MustNewDuration(15 * time.Minute), - UserAPITokenEnabled: ptr(false), + UserAPITokenEnabled: new(false), UserAPITokenDuration: commoncfg.MustNewDuration(240 * time.Hour), }, RateLimit: toml.WebServerRateLimit{ - Authenticated: ptr[int64](42), + Authenticated: new(int64(42)), AuthenticatedPeriod: commoncfg.MustNewDuration(time.Second), - Unauthenticated: ptr[int64](7), + Unauthenticated: new(int64(7)), UnauthenticatedPeriod: commoncfg.MustNewDuration(time.Minute), }, TLS: toml.WebServerTLS{ - CertPath: ptr("tls/cert/path"), - Host: ptr("tls-host"), - KeyPath: ptr("tls/key/path"), - HTTPSPort: ptr[uint16](6789), - ForceRedirect: ptr(true), + CertPath: new("tls/cert/path"), + Host: new("tls-host"), + KeyPath: new("tls/key/path"), + HTTPSPort: new(uint16(6789)), + ForceRedirect: new(true), ListenIP: mustIP("192.158.1.38"), }, } full.JobPipeline = toml.JobPipeline{ - ExternalInitiatorsEnabled: ptr(true), + ExternalInitiatorsEnabled: new(true), MaxRunDuration: commoncfg.MustNewDuration(time.Hour), - MaxSuccessfulRuns: ptr[uint64](123456), + MaxSuccessfulRuns: new(uint64(123456)), ReaperInterval: commoncfg.MustNewDuration(4 * time.Hour), ReaperThreshold: commoncfg.MustNewDuration(7 * 24 * time.Hour), - ResultWriteQueueDepth: ptr[uint32](10), - VerboseLogging: ptr(false), + ResultWriteQueueDepth: new(uint32(10)), + VerboseLogging: new(false), HTTPRequest: toml.JobPipelineHTTPRequest{ - MaxSize: ptr[utils.FileSize](100 * utils.MB), + MaxSize: new((utils.FileSize)(100 * utils.MB)), DefaultTimeout: commoncfg.MustNewDuration(time.Minute), }, } full.FluxMonitor = toml.FluxMonitor{ //nolint:staticcheck // deprecated config surface must match embedded config-full.toml - DefaultTransactionQueueDepth: ptr[uint32](1), - SimulateTransactions: ptr(false), + DefaultTransactionQueueDepth: new(uint32(1)), + SimulateTransactions: new(false), } full.OCR2 = toml.OCR2{ - Enabled: ptr(true), - ContractConfirmations: ptr[uint32](11), + Enabled: new(true), + ContractConfirmations: new(uint32(11)), BlockchainTimeout: commoncfg.MustNewDuration(3 * time.Second), ContractPollInterval: commoncfg.MustNewDuration(time.Hour), ContractSubscribeInterval: commoncfg.MustNewDuration(time.Minute), ContractTransmitterTransmitTimeout: commoncfg.MustNewDuration(time.Minute), DatabaseTimeout: commoncfg.MustNewDuration(8 * time.Second), - KeyBundleID: ptr(corekeys.MustSha256HashFromHex("7a5f66bbe6594259325bf2b4f5b1a9c9")), - CaptureEATelemetry: ptr(false), - CaptureAutomationCustomTelemetry: ptr(true), - AllowNoBootstrappers: ptr(true), - DefaultTransactionQueueDepth: ptr[uint32](1), - SimulateTransactions: ptr(false), - TraceLogging: ptr(false), - SampleTelemetry: ptr(false), - KeyValueStoreRootDir: ptr("~/.chainlink-data"), + KeyBundleID: new(corekeys.MustSha256HashFromHex("7a5f66bbe6594259325bf2b4f5b1a9c9")), + CaptureEATelemetry: new(false), + CaptureAutomationCustomTelemetry: new(true), + AllowNoBootstrappers: new(true), + DefaultTransactionQueueDepth: new(uint32(1)), + SimulateTransactions: new(false), + TraceLogging: new(false), + SampleTelemetry: new(false), + KeyValueStoreRootDir: new("~/.chainlink-data"), } full.OCR = toml.OCR{ - Enabled: ptr(true), + Enabled: new(true), ObservationTimeout: commoncfg.MustNewDuration(11 * time.Second), BlockchainTimeout: commoncfg.MustNewDuration(3 * time.Second), ContractPollInterval: commoncfg.MustNewDuration(time.Hour), ContractSubscribeInterval: commoncfg.MustNewDuration(time.Minute), - DefaultTransactionQueueDepth: ptr[uint32](12), - KeyBundleID: ptr(corekeys.MustSha256HashFromHex("acdd42797a8b921b2910497badc50006")), - SimulateTransactions: ptr(true), - TransmitterAddress: ptr(types.MustEIP55Address("0xa0788FC17B1dEe36f057c42B6F373A34B014687e")), - CaptureEATelemetry: ptr(false), - TraceLogging: ptr(false), - ConfigLogValidation: ptr(false), + DefaultTransactionQueueDepth: new(uint32(12)), + KeyBundleID: new(corekeys.MustSha256HashFromHex("acdd42797a8b921b2910497badc50006")), + SimulateTransactions: new(true), + TransmitterAddress: new(types.MustEIP55Address("0xa0788FC17B1dEe36f057c42B6F373A34B014687e")), + CaptureEATelemetry: new(false), + TraceLogging: new(false), + ConfigLogValidation: new(false), } full.P2P = toml.P2P{ - IncomingMessageBufferSize: ptr[int64](13), - OutgoingMessageBufferSize: ptr[int64](17), + IncomingMessageBufferSize: new(int64(13)), + OutgoingMessageBufferSize: new(int64(17)), PeerID: mustPeerID("12D3KooWMoejJznyDuEk5aX6GvbjaG12UzeornPCBNzMRqdwrFJw"), - TraceLogging: ptr(true), - EnableExperimentalRageP2P: ptr(true), + TraceLogging: new(true), + EnableExperimentalRageP2P: new(true), V2: toml.P2PV2{ - Enabled: ptr(false), + Enabled: new(false), AnnounceAddresses: &[]string{"a", "b", "c"}, DefaultBootstrappers: &[]ocrcommontypes.BootstrapperLocator{ {PeerID: "12D3KooWMoejJznyDuEk5aX6GvbjaG12UzeornPCBNzMRqdwrFJw", Addrs: []string{"foo:42", "bar:10"}}, @@ -405,20 +405,20 @@ func TestConfig_Marshal(t *testing.T) { } full.Capabilities = toml.Capabilities{ RateLimit: toml.EngineExecutionRateLimit{ - GlobalRPS: ptr(200.00), - GlobalBurst: ptr(200), - PerSenderRPS: ptr(200.0), - PerSenderBurst: ptr(200), + GlobalRPS: new(200.00), + GlobalBurst: new(200), + PerSenderRPS: new(200.0), + PerSenderBurst: new(200), }, Peering: toml.P2P{ - IncomingMessageBufferSize: ptr[int64](13), - OutgoingMessageBufferSize: ptr[int64](17), + IncomingMessageBufferSize: new(int64(13)), + OutgoingMessageBufferSize: new(int64(17)), PeerID: mustPeerID("12D3KooWMoejJznyDuEk5aX6GvbjaG12UzeornPCBNzMRqdwrFJw"), - TraceLogging: ptr(true), - EnableExperimentalRageP2P: ptr(true), + TraceLogging: new(true), + EnableExperimentalRageP2P: new(true), V2: toml.P2PV2{ - Enabled: ptr(false), + Enabled: new(false), AnnounceAddresses: &[]string{"a", "b", "c"}, DefaultBootstrappers: &[]ocrcommontypes.BootstrapperLocator{ {PeerID: "12D3KooWMoejJznyDuEk5aX6GvbjaG12UzeornPCBNzMRqdwrFJw", Addrs: []string{"foo:42", "bar:10"}}, @@ -430,77 +430,77 @@ func TestConfig_Marshal(t *testing.T) { }, }, SharedPeering: toml.SharedPeering{ - Enabled: ptr(false), + Enabled: new(false), Bootstrappers: &[]ocrcommontypes.BootstrapperLocator{ {PeerID: "12D3KooWMoejJznyDuEk5aX6GvbjaG12UzeornPCBNzMRqdwrFJw", Addrs: []string{"foo:42", "bar:10"}}, {PeerID: "12D3KooWMoejJznyDuEk5aX6GvbjaG12UzeornPCBNzMRqdwrFJw", Addrs: []string{"test:99"}}, }, StreamConfig: toml.StreamConfig{ - IncomingMessageBufferSize: ptr(500), - OutgoingMessageBufferSize: ptr(500), - MaxMessageLenBytes: ptr(500000), - MessageRateLimiterRate: ptr(100.0), - MessageRateLimiterCapacity: ptr(uint32(500)), - BytesRateLimiterRate: ptr(5000000.0), - BytesRateLimiterCapacity: ptr(uint32(10000000)), + IncomingMessageBufferSize: new(500), + OutgoingMessageBufferSize: new(500), + MaxMessageLenBytes: new(500000), + MessageRateLimiterRate: new(100.0), + MessageRateLimiterCapacity: new(uint32(500)), + BytesRateLimiterRate: new(5000000.0), + BytesRateLimiterCapacity: new(uint32(10000000)), }, }, ExternalRegistry: toml.ExternalRegistry{ - Address: ptr(""), - ChainID: ptr("1"), - NetworkID: ptr("evm"), - ContractVersion: ptr("1.0.0"), + Address: new(""), + ChainID: new("1"), + NetworkID: new("evm"), + ContractVersion: new("1.0.0"), }, WorkflowRegistry: toml.WorkflowRegistry{ - Address: ptr(""), - ChainID: ptr("1"), - ContractVersion: ptr("1.0.0"), - NetworkID: ptr("evm"), + Address: new(""), + ChainID: new("1"), + ContractVersion: new("1.0.0"), + NetworkID: new("evm"), MaxBinarySize: ptr(utils.FileSize(20 * utils.MB)), MaxEncryptedSecretsSize: ptr(utils.FileSize(26.4 * utils.KB)), MaxConfigSize: ptr(utils.FileSize(50 * utils.KB)), - SyncStrategy: ptr("event"), - MaxConcurrency: ptr(12), + SyncStrategy: new("event"), + MaxConcurrency: new(12), MaxActivationRetries: new(100), WorkflowStorage: toml.WorkflowStorage{ - ArtifactStorageHost: ptr(""), - URL: ptr(""), - TLSEnabled: ptr(true), + ArtifactStorageHost: new(""), + URL: new(""), + TLSEnabled: new(true), }, ModuleCache: toml.ModuleCache{ - Enabled: ptr(false), - DiskMonitorEnabled: ptr(false), - IdleEviction: ptr(true), + Enabled: new(false), + DiskMonitorEnabled: new(false), + IdleEviction: new(true), IdleTimeout: commoncfg.MustNewDuration(10 * time.Minute), - MaxLoaded: ptr(200), - CacheDir: ptr(""), + MaxLoaded: new(200), + CacheDir: new(""), }, AdditionalSourcesConfig: []toml.AdditionalWorkflowSource{ { - URL: ptr("localhost:50051"), - TLSEnabled: ptr(true), - Name: ptr("test-grpc-source"), + URL: new("localhost:50051"), + TLSEnabled: new(true), + Name: new("test-grpc-source"), }, }, }, Dispatcher: toml.Dispatcher{ - SupportedVersion: ptr(1), - ReceiverBufferSize: ptr(10000), + SupportedVersion: new(1), + ReceiverBufferSize: new(10000), RateLimit: toml.DispatcherRateLimit{ - GlobalRPS: ptr(800.0), - GlobalBurst: ptr(1000), - PerSenderRPS: ptr(10.0), - PerSenderBurst: ptr(50), + GlobalRPS: new(800.0), + GlobalBurst: new(1000), + PerSenderRPS: new(10.0), + PerSenderBurst: new(50), }, - SendToSharedPeer: ptr(false), + SendToSharedPeer: new(false), }, GatewayConnector: toml.GatewayConnector{ - ChainIDForNodeKey: ptr("11155111"), - NodeAddress: ptr("0x68902d681c28119f9b2531473a417088bf008e59"), - DonID: ptr("example_don"), - WSHandshakeTimeoutMillis: ptr[uint32](100), - AuthMinChallengeLen: ptr[int](10), - AuthTimestampToleranceSec: ptr[uint32](10), + ChainIDForNodeKey: new("11155111"), + NodeAddress: new("0x68902d681c28119f9b2531473a417088bf008e59"), + DonID: new("example_don"), + WSHandshakeTimeoutMillis: new(uint32(100)), + AuthMinChallengeLen: new(10), + AuthTimestampToleranceSec: new(uint32(10)), Gateways: []toml.ConnectorGateway{ {ID: new("example_gateway"), DonID: new("example_gateway_don"), URL: new("wss://localhost:8081/node")}, }, @@ -509,11 +509,11 @@ func TestConfig_Marshal(t *testing.T) { RegistryBasedLaunchAllowlist: []string{`^cron@1\.0\.0$`, `^http-action@.*$`}, Capabilities: map[string]toml.CapabilityNodeConfig{ "http-action@1.0.0": { - BinaryPathOverride: ptr("/opt/chainlink/binaries/http_action"), + BinaryPathOverride: new("/opt/chainlink/binaries/http_action"), Config: map[string]string{"proxyMode": "gateway", "allowedPorts": "443,8443"}, }, "cron@1.0.0": { - BinaryPathOverride: ptr("/opt/chainlink/binaries/cron"), + BinaryPathOverride: new("/opt/chainlink/binaries/cron"), Config: map[string]string{"fastestScheduleIntervalSeconds": "60"}, }, }, @@ -521,34 +521,34 @@ func TestConfig_Marshal(t *testing.T) { } full.Workflows = toml.Workflows{ Limits: toml.Limits{ - Global: ptr(int32(200)), - PerOwner: ptr(int32(200)), + Global: new(int32(200)), + PerOwner: new(int32(200)), }, } full.AutoPprof = toml.AutoPprof{ - Enabled: ptr(true), - ProfileRoot: ptr("prof/root"), + Enabled: new(true), + ProfileRoot: new("prof/root"), PollInterval: commoncfg.MustNewDuration(time.Minute), GatherDuration: commoncfg.MustNewDuration(12 * time.Second), GatherTraceDuration: commoncfg.MustNewDuration(13 * time.Second), - MaxProfileSize: ptr[utils.FileSize](utils.GB), - CPUProfileRate: ptr[int64](7), - MemProfileRate: ptr[int64](9), - BlockProfileRate: ptr[int64](5), - MutexProfileFraction: ptr[int64](2), - MemThreshold: ptr[utils.FileSize](utils.GB), - GoroutineThreshold: ptr[int64](999), + MaxProfileSize: new((utils.FileSize)(utils.GB)), + CPUProfileRate: new(int64(7)), + MemProfileRate: new(int64(9)), + BlockProfileRate: new(int64(5)), + MutexProfileFraction: new(int64(2)), + MemThreshold: new((utils.FileSize)(utils.GB)), + GoroutineThreshold: new(int64(999)), } full.Pyroscope = toml.Pyroscope{ - ServerAddress: ptr("http://localhost:4040"), - Environment: ptr("tests"), - LinkTracesToProfiles: ptr(true), + ServerAddress: new("http://localhost:4040"), + Environment: new("tests"), + LinkTracesToProfiles: new(true), } full.Sentry = toml.Sentry{ - Debug: ptr(true), - DSN: ptr("sentry-dsn"), - Environment: ptr("dev"), - Release: ptr("v1.2.3"), + Debug: new(true), + DSN: new("sentry-dsn"), + Environment: new("dev"), + Release: new("v1.2.3"), } full.Telemetry = toml.Telemetry{ Enabled: new(true), @@ -582,19 +582,19 @@ func TestConfig_Marshal(t *testing.T) { }, } full.CRE = toml.CreConfig{ - UseLocalTimeProvider: ptr(true), - EnableDKGRecipient: ptr(false), - DebugMode: ptr(false), + UseLocalTimeProvider: new(true), + EnableDKGRecipient: new(false), + DebugMode: new(false), Streams: &toml.StreamsConfig{ - WsURL: ptr("streams.url"), - RestURL: ptr("streams.url"), + WsURL: new("streams.url"), + RestURL: new("streams.url"), }, WorkflowFetcher: &toml.WorkflowFetcherConfig{ - URL: ptr("https://workflow.fetcher.url"), + URL: new("https://workflow.fetcher.url"), }, Linking: &toml.LinkingConfig{ - URL: ptr(""), - TLSEnabled: ptr(true), + URL: new(""), + TLSEnabled: new(true), }, ConfidentialRelay: &toml.ConfidentialRelayConfig{ Enabled: new(bool), @@ -603,69 +603,69 @@ func TestConfig_Marshal(t *testing.T) { }, } full.Billing = toml.Billing{ - URL: ptr("localhost:4319"), - TLSEnabled: ptr(true), + URL: new("localhost:4319"), + TLSEnabled: new(true), } full.BridgeStatusReporter = toml.BridgeStatusReporter{ - Enabled: ptr(false), - StatusPath: ptr("/status"), + Enabled: new(false), + StatusPath: new("/status"), PollingInterval: commoncfg.MustNewDuration(5 * time.Minute), - IgnoreInvalidBridges: ptr(true), - IgnoreJoblessBridges: ptr(false), + IgnoreInvalidBridges: new(true), + IgnoreJoblessBridges: new(false), } enabledOCR2PluginTypes := []string{"median"} full.JobSpecReporter = toml.JobSpecReporter{ - Enabled: ptr(true), + Enabled: new(true), PollingInterval: commoncfg.MustNewDuration(time.Hour), EnabledOCR2PluginTypes: &enabledOCR2PluginTypes, } full.Sharding = toml.Sharding{ - ShardingEnabled: ptr(false), - ArbiterPort: ptr[uint16](9876), + ShardingEnabled: new(false), + ArbiterPort: new(uint16(9876)), ArbiterPollInterval: commoncfg.MustNewDuration(12 * time.Second), ArbiterRetryInterval: commoncfg.MustNewDuration(12 * time.Second), - ShardIndex: ptr[uint16](0), - ShardOrchestratorPort: ptr[uint16](50051), + ShardIndex: new(uint16(0)), + ShardOrchestratorPort: new(uint16(50051)), ShardOrchestratorAddress: &commoncfg.URL{}, } full.LOOPP = toml.LOOPP{ - GRPCServerMaxRecvMsgSize: ptr[utils.FileSize](42 * utils.MB), + GRPCServerMaxRecvMsgSize: new((utils.FileSize)(42 * utils.MB)), } full.JobDistributor = toml.JobDistributor{ - DisplayName: ptr("test-node"), + DisplayName: new("test-node"), } full.EVM = []*evmcfg.EVMConfig{ { ChainID: sqlutil.NewI(1), - Enabled: ptr(false), + Enabled: new(false), Chain: evmcfg.Chain{ - AutoCreateKey: ptr(false), + AutoCreateKey: new(false), BalanceMonitor: evmcfg.BalanceMonitor{ - Enabled: ptr(true), + Enabled: new(true), }, - BlockBackfillDepth: ptr[uint32](100), - BlockBackfillSkip: ptr(true), + BlockBackfillDepth: new(uint32(100)), + BlockBackfillSkip: new(true), ChainType: chaintype.NewConfig("Optimism"), - FinalityDepth: ptr[uint32](42), - SafeDepth: ptr[uint32](0), - FinalityTagEnabled: ptr[bool](true), - SafeTagSupported: ptr(true), + FinalityDepth: new(uint32(42)), + SafeDepth: new(uint32(0)), + FinalityTagEnabled: new(true), + SafeTagSupported: new(true), FlagsContractAddress: mustAddress("0xae4E781a6218A8031764928E88d457937A954fC3"), - FinalizedBlockOffset: ptr[uint32](16), + FinalizedBlockOffset: new(uint32(16)), GasEstimator: evmcfg.GasEstimator{ - Mode: ptr("SuggestedPrice"), - EIP1559DynamicFees: ptr(true), - BumpPercent: ptr[uint16](10), - BumpThreshold: ptr[uint32](6), - BumpTxDepth: ptr[uint32](6), + Mode: new("SuggestedPrice"), + EIP1559DynamicFees: new(true), + BumpPercent: new(uint16(10)), + BumpThreshold: new(uint32(6)), + BumpTxDepth: new(uint32(6)), BumpMin: assets.NewWeiI(100), FeeCapDefault: assets.NewWeiI(math.MaxInt64), - LimitDefault: ptr[uint64](12), - LimitMax: ptr[uint64](17), + LimitDefault: new(uint64(12)), + LimitMax: new(uint64(17)), LimitMultiplier: mustDecimal("1.234"), - LimitTransfer: ptr[uint64](100), - EstimateLimit: ptr(false), + LimitTransfer: new(uint64(100)), + EstimateLimit: new(false), TipCapDefault: assets.NewWeiI(2), TipCapMin: assets.NewWeiI(1), PriceDefault: assets.NewWeiI(math.MaxInt64), @@ -673,21 +673,21 @@ func TestConfig_Marshal(t *testing.T) { PriceMin: assets.NewWeiI(13), LimitJobType: evmcfg.GasLimitJobType{ - OCR: ptr[uint32](1001), - DR: ptr[uint32](1002), - VRF: ptr[uint32](1003), - FM: ptr[uint32](1004), - Keeper: ptr[uint32](1005), - OCR2: ptr[uint32](1006), + OCR: new(uint32(1001)), + DR: new(uint32(1002)), + VRF: new(uint32(1003)), + FM: new(uint32(1004)), + Keeper: new(uint32(1005)), + OCR2: new(uint32(1006)), }, BlockHistory: evmcfg.BlockHistoryEstimator{ - BatchSize: ptr[uint32](17), - BlockHistorySize: ptr[uint16](12), - CheckInclusionBlocks: ptr[uint16](18), - CheckInclusionPercentile: ptr[uint16](19), - EIP1559FeeCapBufferBlocks: ptr[uint16](13), - TransactionPercentile: ptr[uint16](15), + BatchSize: new(uint32(17)), + BlockHistorySize: new(uint16(12)), + CheckInclusionBlocks: new(uint16(18)), + CheckInclusionPercentile: new(uint16(19)), + EIP1559FeeCapBufferBlocks: new(uint16(13)), + TransactionPercentile: new(uint16(15)), }, FeeHistory: evmcfg.FeeHistoryEstimator{ CacheTimeout: &second, @@ -704,89 +704,89 @@ func TestConfig_Marshal(t *testing.T) { }, LinkContractAddress: mustAddress("0x538aAaB4ea120b2bC2fe5D296852D948F07D849e"), - LogBackfillBatchSize: ptr[uint32](17), + LogBackfillBatchSize: new(uint32(17)), LogPollInterval: &minute, - LogKeepBlocksDepth: ptr[uint32](100000), - LogPollerSkipEmptyBlocks: ptr(false), - LogPrunePageSize: ptr[uint32](0), - BackupLogPollerBlockDelay: ptr[uint64](532), + LogKeepBlocksDepth: new(uint32(100000)), + LogPollerSkipEmptyBlocks: new(false), + LogPrunePageSize: new(uint32(0)), + BackupLogPollerBlockDelay: new(uint64(532)), MinContractPayment: commonassets.NewLinkFromJuels(math.MaxInt64), - MinIncomingConfirmations: ptr[uint32](13), - NonceAutoSync: ptr(true), + MinIncomingConfirmations: new(uint32(13)), + NonceAutoSync: new(true), NoNewHeadsThreshold: &minute, OperatorFactoryAddress: mustAddress("0xa5B85635Be42F21f94F28034B7DA440EeFF0F418"), - LogBroadcasterEnabled: ptr(true), - RPCDefaultBatchSize: ptr[uint32](17), - RPCBlockQueryDelay: ptr[uint16](10), + LogBroadcasterEnabled: new(true), + RPCDefaultBatchSize: new(uint32(17)), + RPCBlockQueryDelay: new(uint16(10)), NoNewFinalizedHeadsThreshold: &hour, Transactions: evmcfg.Transactions{ - Enabled: ptr(true), - MaxInFlight: ptr[uint32](19), - MaxQueued: ptr[uint32](99), + Enabled: new(true), + MaxInFlight: new(uint32(19)), + MaxQueued: new(uint32(99)), ReaperInterval: &minute, ReaperThreshold: &minute, ResendAfterThreshold: &hour, - ForwardersEnabled: ptr(true), + ForwardersEnabled: new(true), AutoPurge: evmcfg.AutoPurgeConfig{ - Enabled: ptr(false), + Enabled: new(false), }, TransactionManagerV2: evmcfg.TransactionManagerV2Config{ - Enabled: ptr(false), - ReadRequestsToMultipleNodes: ptr(false), - Bundles: ptr(false), + Enabled: new(false), + ReadRequestsToMultipleNodes: new(false), + Bundles: new(false), }, ConfirmationTimeout: &minute, }, HeadTracker: evmcfg.HeadTracker{ - HistoryDepth: ptr[uint32](15), - MaxBufferSize: ptr[uint32](17), + HistoryDepth: new(uint32(15)), + MaxBufferSize: new(uint32(17)), SamplingInterval: &hour, - FinalityTagBypass: ptr[bool](false), - MaxAllowedFinalityDepth: ptr[uint32](1500), - PersistenceEnabled: ptr(false), - PersistenceBatchSize: ptr[int64](100), + FinalityTagBypass: new(false), + MaxAllowedFinalityDepth: new(uint32(1500)), + PersistenceEnabled: new(false), + PersistenceBatchSize: new(int64(100)), }, NodePool: evmcfg.NodePool{ - PollFailureThreshold: ptr[uint32](5), - PollSuccessThreshold: ptr[uint32](0), + PollFailureThreshold: new(uint32(5)), + PollSuccessThreshold: new(uint32(0)), PollInterval: &minute, SelectionMode: &selectionMode, - SyncThreshold: ptr[uint32](13), + SyncThreshold: new(uint32(13)), LeaseDuration: &zeroSeconds, - NodeIsSyncingEnabled: ptr(true), + NodeIsSyncingEnabled: new(true), FinalizedBlockPollInterval: &second, - HistoricalBalanceCheckAddress: ptr(types.MustEIP55Address("0x0000000000000000000000000000000000000000")), - EnforceRepeatableRead: ptr(true), + HistoricalBalanceCheckAddress: new(types.MustEIP55Address("0x0000000000000000000000000000000000000000")), + EnforceRepeatableRead: new(true), DeathDeclarationDelay: &minute, - VerifyChainID: ptr(true), + VerifyChainID: new(true), NewHeadsPollInterval: &zeroSeconds, - ExternalRequestMaxResponseSize: ptr[uint32](10), - FinalizedStateCheckFailureThreshold: ptr[uint32](0), + ExternalRequestMaxResponseSize: new(uint32(10)), + FinalizedStateCheckFailureThreshold: new(uint32(0)), Errors: evmcfg.ClientErrors{ - NonceTooLow: ptr[string]("(: |^)nonce too low"), - NonceTooHigh: ptr[string]("(: |^)nonce too high"), - ReplacementTransactionUnderpriced: ptr[string]("(: |^)replacement transaction underpriced"), - LimitReached: ptr[string]("(: |^)limit reached"), - TransactionAlreadyInMempool: ptr[string]("(: |^)transaction already in mempool"), - TerminallyUnderpriced: ptr[string]("(: |^)terminally underpriced"), - InsufficientEth: ptr[string]("(: |^)insufficient eth"), - TxFeeExceedsCap: ptr[string]("(: |^)tx fee exceeds cap"), - L2FeeTooLow: ptr[string]("(: |^)l2 fee too low"), - L2FeeTooHigh: ptr[string]("(: |^)l2 fee too high"), - L2Full: ptr[string]("(: |^)l2 full"), - TransactionAlreadyMined: ptr[string]("(: |^)transaction already mined"), - Fatal: ptr[string]("(: |^)fatal"), - ServiceUnavailable: ptr[string]("(: |^)service unavailable"), - TooManyResults: ptr[string]("(: |^)too many results"), - MissingBlocks: ptr[string]("(: |^)missing blocks"), - FinalizedStateUnavailable: ptr[string]("(: |^)(missing trie node|state not available|historical state unavailable)"), + NonceTooLow: new("(: |^)nonce too low"), + NonceTooHigh: new("(: |^)nonce too high"), + ReplacementTransactionUnderpriced: new("(: |^)replacement transaction underpriced"), + LimitReached: new("(: |^)limit reached"), + TransactionAlreadyInMempool: new("(: |^)transaction already in mempool"), + TerminallyUnderpriced: new("(: |^)terminally underpriced"), + InsufficientEth: new("(: |^)insufficient eth"), + TxFeeExceedsCap: new("(: |^)tx fee exceeds cap"), + L2FeeTooLow: new("(: |^)l2 fee too low"), + L2FeeTooHigh: new("(: |^)l2 fee too high"), + L2Full: new("(: |^)l2 full"), + TransactionAlreadyMined: new("(: |^)transaction already mined"), + Fatal: new("(: |^)fatal"), + ServiceUnavailable: new("(: |^)service unavailable"), + TooManyResults: new("(: |^)too many results"), + MissingBlocks: new("(: |^)missing blocks"), + FinalizedStateUnavailable: new("(: |^)(missing trie node|state not available|historical state unavailable)"), }, }, OCR: evmcfg.OCR{ - ContractConfirmations: ptr[uint16](11), + ContractConfirmations: new(uint16(11)), ContractTransmitterTransmitTimeout: &minute, DatabaseTimeout: &second, DeltaCOverride: commoncfg.MustNewDuration(time.Hour), @@ -795,11 +795,11 @@ func TestConfig_Marshal(t *testing.T) { }, OCR2: evmcfg.OCR2{ Automation: evmcfg.Automation{ - GasLimit: ptr[uint32](540), + GasLimit: new(uint32(540)), }, }, Workflow: evmcfg.Workflow{ - GasLimitDefault: ptr[uint64](400000), + GasLimitDefault: new(uint64(400000)), TxAcceptanceState: ptr(commontypes.Unconfirmed), PollPeriod: commoncfg.MustNewDuration(time.Second * 2), AcceptanceTimeout: commoncfg.MustNewDuration(time.Second * 30), @@ -807,20 +807,20 @@ func TestConfig_Marshal(t *testing.T) { }, Nodes: []*evmcfg.Node{ { - Name: ptr("foo"), + Name: new("foo"), HTTPURL: mustURL("https://foo.web"), WSURL: mustURL("wss://web.socket/test/foo"), HTTPURLExtraWrite: mustURL("https://foo.web/extra"), }, { - Name: ptr("bar"), + Name: new("bar"), HTTPURL: mustURL("https://bar.com"), WSURL: mustURL("wss://web.socket/test/bar"), }, { - Name: ptr("broadcast"), + Name: new("broadcast"), HTTPURL: mustURL("http://broadcast.mirror"), - SendOnly: ptr(true), + SendOnly: new(true), }, }}, } @@ -831,17 +831,17 @@ func TestConfig_Marshal(t *testing.T) { LatestReportDeadline: commoncfg.MustNewDuration(102 * time.Second), }, TLS: toml.MercuryTLS{ - CertFile: ptr("/path/to/cert.pem"), + CertFile: new("/path/to/cert.pem"), }, Transmitter: toml.MercuryTransmitter{ Protocol: ptr(mercurytransmitter.MercuryTransmitterProtocolGRPC), - TransmitQueueMaxSize: ptr(uint32(123)), + TransmitQueueMaxSize: new(uint32(123)), TransmitTimeout: commoncfg.MustNewDuration(234 * time.Second), - TransmitConcurrency: ptr(uint32(456)), + TransmitConcurrency: new(uint32(456)), ReaperFrequency: commoncfg.MustNewDuration(567 * time.Second), ReaperMaxAge: commoncfg.MustNewDuration(678 * time.Hour), }, - VerboseLogging: ptr(true), + VerboseLogging: new(true), } for _, tt := range []struct { @@ -1317,23 +1317,23 @@ func TestConfig_full(t *testing.T) { got.EVM[c].Workflow.ForwarderAddress = &addr } if got.EVM[c].Workflow.GasLimitDefault == nil { - got.EVM[c].Workflow.GasLimitDefault = ptr(uint64(400000)) + got.EVM[c].Workflow.GasLimitDefault = new(uint64(400000)) } for n := range got.EVM[c].Nodes { if got.EVM[c].Nodes[n].WSURL == nil { got.EVM[c].Nodes[n].WSURL = new(commoncfg.URL) } if got.EVM[c].Nodes[n].SendOnly == nil { - got.EVM[c].Nodes[n].SendOnly = ptr(true) + got.EVM[c].Nodes[n].SendOnly = new(true) } if got.EVM[c].Nodes[n].Order == nil { - got.EVM[c].Nodes[n].Order = ptr(int32(100)) + got.EVM[c].Nodes[n].Order = new(int32(100)) } if got.EVM[c].Nodes[n].HTTPURLExtraWrite == nil { got.EVM[c].Nodes[n].HTTPURLExtraWrite = new(commoncfg.URL) } if got.EVM[c].Nodes[n].IsLoadBalancedRPC == nil { - got.EVM[c].Nodes[n].IsLoadBalancedRPC = ptr(false) + got.EVM[c].Nodes[n].IsLoadBalancedRPC = new(false) } } if got.EVM[c].Transactions.TransactionManagerV2.BlockTime == nil { @@ -1343,25 +1343,25 @@ func TestConfig_full(t *testing.T) { got.EVM[c].Transactions.TransactionManagerV2.CustomURL = new(commoncfg.URL) } if got.EVM[c].Transactions.TransactionManagerV2.DualBroadcast == nil { - got.EVM[c].Transactions.TransactionManagerV2.DualBroadcast = ptr(false) + got.EVM[c].Transactions.TransactionManagerV2.DualBroadcast = new(false) } if got.EVM[c].Transactions.TransactionManagerV2.ReadRequestsToMultipleNodes == nil { - got.EVM[c].Transactions.TransactionManagerV2.ReadRequestsToMultipleNodes = ptr(false) + got.EVM[c].Transactions.TransactionManagerV2.ReadRequestsToMultipleNodes = new(false) } if got.EVM[c].Transactions.TransactionManagerV2.Bundles == nil { - got.EVM[c].Transactions.TransactionManagerV2.Bundles = ptr(false) + got.EVM[c].Transactions.TransactionManagerV2.Bundles = new(false) } if got.EVM[c].Transactions.TransactionManagerV2.FastlaneAuctionRequestTimeout == nil { got.EVM[c].Transactions.TransactionManagerV2.FastlaneAuctionRequestTimeout = new(commoncfg.Duration) } if got.EVM[c].Transactions.TransactionManagerV2.FeeBoost == nil { - got.EVM[c].Transactions.TransactionManagerV2.FeeBoost = ptr(false) + got.EVM[c].Transactions.TransactionManagerV2.FeeBoost = new(false) } if got.EVM[c].Transactions.AutoPurge.Threshold == nil { - got.EVM[c].Transactions.AutoPurge.Threshold = ptr(uint32(0)) + got.EVM[c].Transactions.AutoPurge.Threshold = new(uint32(0)) } if got.EVM[c].Transactions.AutoPurge.MinAttempts == nil { - got.EVM[c].Transactions.AutoPurge.MinAttempts = ptr(uint32(0)) + got.EVM[c].Transactions.AutoPurge.MinAttempts = new(uint32(0)) } if got.EVM[c].Transactions.AutoPurge.DetectionApiUrl == nil { got.EVM[c].Transactions.AutoPurge.DetectionApiUrl = new(commoncfg.URL) @@ -1722,9 +1722,9 @@ func assertValidationError(t *testing.T, invalid interface{ Validate() error }, func TestConfig_setDefaults(t *testing.T) { var c Config c.EVM = evmcfg.EVMConfigs{{ChainID: sqlutil.NewI(99999133712345)}} - c.Cosmos = RawConfigs{{"ChainID": ptr("unknown cosmos chain")}} - c.Solana = RawConfigs{{"ChainID": ptr("unknown solana chain")}} - c.Starknet = RawConfigs{{"ChainID": ptr("unknown starknet chain")}} + c.Cosmos = RawConfigs{{"ChainID": new("unknown cosmos chain")}} + c.Solana = RawConfigs{{"ChainID": new("unknown solana chain")}} + c.Starknet = RawConfigs{{"ChainID": new("unknown starknet chain")}} c.setDefaults() s, err := c.TOMLString() @@ -1794,9 +1794,9 @@ func TestConfig_warnings(t *testing.T) { config: Config{ Core: toml.Core{ Tracing: toml.Tracing{ - Enabled: ptr(true), - Mode: ptr("unencrypted"), - TLSCertPath: ptr("/path/to/cert.pem"), + Enabled: new(true), + Mode: new("unencrypted"), + TLSCertPath: new("/path/to/cert.pem"), }, }, }, @@ -1818,7 +1818,8 @@ func TestConfig_warnings(t *testing.T) { } } -func ptr[T any](t T) *T { return &t } +//go:fix inline +func ptr[T any](t T) *T { return new(t) } func mustHexToBig(t *testing.T, hx string) *big.Int { n, err := hex.ParseBig(hx) diff --git a/core/services/chainlink/node_platform_test.go b/core/services/chainlink/node_platform_test.go index 5475ebb5fee..5a7e3e86dda 100644 --- a/core/services/chainlink/node_platform_test.go +++ b/core/services/chainlink/node_platform_test.go @@ -43,10 +43,7 @@ func (f fakeNodePlatformJobReader) FindJobs(_ context.Context, offset, limit int return nil, len(f.jobs), nil } - end := offset + limit - if end > len(f.jobs) { - end = len(f.jobs) - } + end := min(offset+limit, len(f.jobs)) return f.jobs[offset:end], len(f.jobs), nil } diff --git a/core/services/chainlink/relayer_chain_interoperators_test.go b/core/services/chainlink/relayer_chain_interoperators_test.go index e45b9338fa6..be811b888c0 100644 --- a/core/services/chainlink/relayer_chain_interoperators_test.go +++ b/core/services/chainlink/relayer_chain_interoperators_test.go @@ -36,32 +36,32 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { newConfig := func() chainlink.GeneralConfig { return configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { node1_1 := toml.Node{ - Name: ptr("Test node chain1:1"), + Name: new("Test node chain1:1"), WSURL: commonconfig.MustParseURL("ws://localhost:8546"), HTTPURL: commonconfig.MustParseURL("http://localhost:8546"), - SendOnly: ptr(false), - Order: ptr(int32(15)), - IsLoadBalancedRPC: ptr[bool](false), + SendOnly: new(false), + Order: new(int32(15)), + IsLoadBalancedRPC: new(false), } node1_2 := toml.Node{ - Name: ptr("Test node chain1:2"), + Name: new("Test node chain1:2"), WSURL: commonconfig.MustParseURL("ws://localhost:8547"), HTTPURL: commonconfig.MustParseURL("http://localhost:8547"), - SendOnly: ptr(false), - Order: ptr(int32(36)), - IsLoadBalancedRPC: ptr[bool](false), + SendOnly: new(false), + Order: new(int32(36)), + IsLoadBalancedRPC: new(false), } node2_1 := toml.Node{ - Name: ptr("Test node chain2:1"), + Name: new("Test node chain2:1"), WSURL: commonconfig.MustParseURL("ws://localhost:8547"), HTTPURL: commonconfig.MustParseURL("http://localhost:8547"), - SendOnly: ptr(false), - Order: ptr(int32(11)), - IsLoadBalancedRPC: ptr[bool](false), + SendOnly: new(false), + Order: new(int32(11)), + IsLoadBalancedRPC: new(false), } c.EVM[0] = &toml.EVMConfig{ ChainID: evmChainID1, - Enabled: ptr(true), + Enabled: new(true), Chain: toml.Defaults(evmChainID1), Nodes: toml.EVMNodes{&node1_1, &node1_2}, } @@ -69,7 +69,7 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { c.EVM = append(c.EVM, &toml.EVMConfig{ ChainID: evmChainID2, Chain: toml.Defaults(id2), - Enabled: ptr(true), + Enabled: new(true), Nodes: toml.EVMNodes{&node2_1}, }) }) @@ -289,5 +289,3 @@ func TestCoreRelayerChainInteroperators(t *testing.T) { assert.ErrorIs(t, err, errBadFunc) }) } - -func ptr[T any](t T) *T { return &t } diff --git a/core/services/functions/listener_test.go b/core/services/functions/listener_test.go index 826c2ce67f7..6fb693f0141 100644 --- a/core/services/functions/listener_test.go +++ b/core/services/functions/listener_test.go @@ -58,8 +58,6 @@ type FunctionsListenerUniverse struct { logPollerWrapper *evmrelay_mocks.LogPollerWrapper } -func ptr[T any](t T) *T { return &t } - var ( RequestID = newRequestID() RequestIDStr = fmt.Sprintf("0x%x", [32]byte(RequestID)) @@ -78,7 +76,7 @@ var ( func NewFunctionsListenerUniverse(t *testing.T, timeoutSec int, pruneFrequencySec int) *FunctionsListenerUniverse { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].MinIncomingConfirmations = ptr[uint32](1) + c.EVM[0].MinIncomingConfirmations = new(uint32(1)) }) ethClient := client.NewNullClient(big.NewInt(evmtest.NullClientChainID), logger.TestLogger(t)) broadcaster := log_mocks.NewBroadcaster(t) diff --git a/core/services/gateway/handlers/capabilities/handler.go b/core/services/gateway/handlers/capabilities/handler.go index ef5d2cf009a..293fa1c8782 100644 --- a/core/services/gateway/handlers/capabilities/handler.go +++ b/core/services/gateway/handlers/capabilities/handler.go @@ -184,9 +184,7 @@ func (h *handler) handleWebAPIOutgoingMessage(ctx context.Context, msg *api.Mess } // send response to node async - h.wg.Add(1) - go func() { - defer h.wg.Done() + h.wg.Go(func() { // not cancelled when parent is cancelled to ensure the goroutine can finish newCtx := context.WithoutCancel(ctx) newCtx, cancel := context.WithTimeout(newCtx, timeout) @@ -235,7 +233,7 @@ func (h *handler) handleWebAPIOutgoingMessage(ctx context.Context, msg *api.Mess return } l.Debugw("sent response to node", "to", nodeAddr) - }() + }) return nil } diff --git a/core/services/gateway/handlers/capabilities/v2/http_handler.go b/core/services/gateway/handlers/capabilities/v2/http_handler.go index f2fc9dd87ba..ce21da9df2c 100644 --- a/core/services/gateway/handlers/capabilities/v2/http_handler.go +++ b/core/services/gateway/handlers/capabilities/v2/http_handler.go @@ -402,9 +402,7 @@ func (h *gatewayHandler) makeOutgoingRequest(ctx context.Context, resp *jsonrpc. sendResponseTimeout := time.Duration(defaultSendResponseTimeoutMs) * time.Millisecond // send response to node async - h.wg.Add(1) - go func() { - defer h.wg.Done() + h.wg.Go(func() { // not cancelled when parent is cancelled to ensure the goroutine can finish baseCtx := context.WithoutCancel(ctx) httpCtx, httpCancel := context.WithTimeout(baseCtx, timeout) @@ -431,7 +429,7 @@ func (h *gatewayHandler) makeOutgoingRequest(ctx context.Context, resp *jsonrpc. l.Errorw("error sending response to node", "err", err, "nodeAddr", nodeAddr, "requestID", requestID) h.metrics.IncrementActionCapabilityFailures(ctx, nodeAddr, h.lggr) } - }() + }) return nil } @@ -454,9 +452,7 @@ func (h *gatewayHandler) Start(ctx context.Context) error { if err != nil { return fmt.Errorf("failed to start HTTP auth handler: %w", err) } - h.wg.Add(1) - go func() { - defer h.wg.Done() + h.wg.Go(func() { ticker := time.NewTicker(time.Duration(h.config.CleanUpPeriodMs) * time.Millisecond) defer ticker.Stop() for { @@ -467,7 +463,7 @@ func (h *gatewayHandler) Start(ctx context.Context) error { return } } - }() + }) return nil }) } diff --git a/core/services/gateway/handlers/capabilities/v2/http_trigger_handler.go b/core/services/gateway/handlers/capabilities/v2/http_trigger_handler.go index 477085c7244..280966fa2df 100644 --- a/core/services/gateway/handlers/capabilities/v2/http_trigger_handler.go +++ b/core/services/gateway/handlers/capabilities/v2/http_trigger_handler.go @@ -472,9 +472,7 @@ func (h *httpTriggerHandler) HandleNodeTriggerResponse(ctx context.Context, resp func (h *httpTriggerHandler) Start(ctx context.Context) error { return h.StartOnce("HTTPTriggerHandler", func() error { h.lggr.Info("Starting HTTPTriggerHandler") - h.wg.Add(1) - go func() { - defer h.wg.Done() + h.wg.Go(func() { ticker := time.NewTicker(time.Duration(h.config.CleanUpPeriodMs) * time.Millisecond) defer ticker.Stop() for { @@ -485,7 +483,7 @@ func (h *httpTriggerHandler) Start(ctx context.Context) error { return } } - }() + }) return nil }) } diff --git a/core/services/gateway/handlers/capabilities/v2/response_cache.go b/core/services/gateway/handlers/capabilities/v2/response_cache.go index 7c34fc361e9..b5355b80db0 100644 --- a/core/services/gateway/handlers/capabilities/v2/response_cache.go +++ b/core/services/gateway/handlers/capabilities/v2/response_cache.go @@ -80,7 +80,7 @@ func (rc *responseCache) Fetch(ctx context.Context, req gateway.OutboundHTTPRequ // Cache check + store happen inside the flight so the key isn't released // until the result is cached, closing the race window between singleflight // completion and cache write. - result, _, _ := rc.flight.Do(cacheKey, func() (interface{}, error) { + result, _, _ := rc.flight.Do(cacheKey, func() (any, error) { // Re-check cache: a previous flight may have just stored the result. rc.cacheMu.RLock() cachedResp, exists := rc.cache[cacheKey] diff --git a/core/services/gateway/handlers/capabilities/v2/response_cache_test.go b/core/services/gateway/handlers/capabilities/v2/response_cache_test.go index 7a9b42aa3de..703ead8a386 100644 --- a/core/services/gateway/handlers/capabilities/v2/response_cache_test.go +++ b/core/services/gateway/handlers/capabilities/v2/response_cache_test.go @@ -332,7 +332,7 @@ func TestFetch_ConcurrentDifferentKeys_RunInParallel(t *testing.T) { wg.Add(n) start := time.Now() - for i := 0; i < n; i++ { + for i := range n { go func(idx int) { defer wg.Done() req := createTestRequest("GET", fmt.Sprintf("https://example.com/parallel/%d", idx)) @@ -369,7 +369,7 @@ func TestFetch_ConcurrentSameKey_Deduplicated(t *testing.T) { var wg sync.WaitGroup wg.Add(n) - for i := 0; i < n; i++ { + for range n { go func() { defer wg.Done() fetchFn := func() gateway_common.OutboundHTTPResponse { @@ -467,7 +467,7 @@ func TestFetch_PanicInFetchFn_PropagatedToAllWaiters(t *testing.T) { var wg sync.WaitGroup wg.Add(n) - for i := 0; i < n; i++ { + for range n { go func() { defer wg.Done() defer func() { diff --git a/core/services/gateway/handlers/capabilities/v2/workflow_metadata_handler.go b/core/services/gateway/handlers/capabilities/v2/workflow_metadata_handler.go index c3cffa3804c..ce7e2fb59da 100644 --- a/core/services/gateway/handlers/capabilities/v2/workflow_metadata_handler.go +++ b/core/services/gateway/handlers/capabilities/v2/workflow_metadata_handler.go @@ -251,9 +251,7 @@ func (h *WorkflowMetadataHandler) Start(ctx context.Context) error { } func (h *WorkflowMetadataHandler) runTicker(period time.Duration, fn func(ctx context.Context)) { - h.wg.Add(1) - go func() { - defer h.wg.Done() + h.wg.Go(func() { ctx, cancel := h.stopCh.NewCtx() defer cancel() ticker := time.NewTicker(period) @@ -266,7 +264,7 @@ func (h *WorkflowMetadataHandler) runTicker(period time.Duration, fn func(ctx co return } } - }() + }) } func (h *WorkflowMetadataHandler) validateAuthMetadata(metadata gateway.WorkflowMetadata) error { diff --git a/core/services/gateway/handlers/confidentialrelay/handler_test.go b/core/services/gateway/handlers/confidentialrelay/handler_test.go index 105c53e18b1..d2a13c52cd3 100644 --- a/core/services/gateway/handlers/confidentialrelay/handler_test.go +++ b/core/services/gateway/handlers/confidentialrelay/handler_test.go @@ -187,9 +187,7 @@ func TestConfidentialRelayHandler_ForwardsBundleAtQuorum(t *testing.T) { result := relaytypes.CapabilityResponseResult{Payload: "result"} var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.NoError, resp.ErrorCode) @@ -199,7 +197,7 @@ func TestConfidentialRelayHandler_ForwardsBundleAtQuorum(t *testing.T) { var bundle relaytypes.SignedCapabilityResponseBundle assert.NoError(t, json.Unmarshal(*jsonResp.Result, &bundle)) assert.Len(t, bundle.Responses, 3, "the gateway forwards every collected signed response") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), req, cb) require.NoError(t, err) @@ -434,9 +432,7 @@ func TestConfidentialRelayHandler_ForwardsAllDivergentResponses(t *testing.T) { } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.NoError, resp.ErrorCode) @@ -445,7 +441,7 @@ func TestConfidentialRelayHandler_ForwardsAllDivergentResponses(t *testing.T) { var bundle relaytypes.SignedCapabilityResponseBundle assert.NoError(t, json.Unmarshal(*jsonResp.Result, &bundle)) assert.Len(t, bundle.Responses, 3, "divergent and matching responses are all forwarded untouched") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), req, cb) require.NoError(t, err) @@ -475,13 +471,11 @@ func TestConfidentialRelayHandler_BundlerErrorReturnsFatal(t *testing.T) { } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.FatalError, resp.ErrorCode) - }() + }) require.NoError(t, h.HandleJSONRPCUserMessage(t.Context(), req, cb)) result := relaytypes.CapabilityResponseResult{Payload: "x"} @@ -548,13 +542,11 @@ func TestConfidentialRelayHandler_TimeoutBelowQuorumFloorReturnsTimeout(t *testi } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.RequestTimeoutError, resp.ErrorCode) - }() + }) require.NoError(t, h.HandleJSONRPCUserMessage(t.Context(), req, cb)) result := relaytypes.CapabilityResponseResult{Payload: "x"} @@ -580,13 +572,11 @@ func TestConfidentialRelayHandler_TimeoutNoResponses(t *testing.T) { } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.RequestTimeoutError, resp.ErrorCode) - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), req, cb) require.NoError(t, err) @@ -736,9 +726,7 @@ func TestConfidentialRelayHandler_AllNodesFanOutFail(t *testing.T) { } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.FatalError, resp.ErrorCode) @@ -746,7 +734,7 @@ func TestConfidentialRelayHandler_AllNodesFanOutFail(t *testing.T) { err = json.Unmarshal(resp.RawResponse, &jsonResp) assert.NoError(t, err) assert.Contains(t, jsonResp.Error.Message, "failed to forward user request to nodes") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), req, cb) require.NoError(t, err) @@ -807,9 +795,7 @@ func TestConfidentialRelayHandler_FanOutFailsWhenQuorumBecomesImpossible(t *test } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := cb.Wait(t.Context()) assert.NoError(t, err) assert.Equal(t, api.FatalError, resp.ErrorCode) @@ -817,7 +803,7 @@ func TestConfidentialRelayHandler_FanOutFailsWhenQuorumBecomesImpossible(t *test err = json.Unmarshal(resp.RawResponse, &jsonResp) assert.NoError(t, err) assert.Contains(t, jsonResp.Error.Message, "failed to forward user request to nodes") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), req, cb) require.NoError(t, err) diff --git a/core/services/gateway/handlers/functions/allowlist/allowlist.go b/core/services/gateway/handlers/functions/allowlist/allowlist.go index e3ba7a109c5..5c58df3afae 100644 --- a/core/services/gateway/handlers/functions/allowlist/allowlist.go +++ b/core/services/gateway/handlers/functions/allowlist/allowlist.go @@ -4,6 +4,7 @@ import ( "context" "encoding/hex" "fmt" + "maps" "math/big" "regexp" "sync" @@ -144,9 +145,7 @@ func (a *onchainAllowlist) Start(ctx context.Context) error { if err != nil { return fmt.Errorf("update frequency: %w", err) } - a.closeWait.Add(1) - go func() { - defer a.closeWait.Done() + a.closeWait.Go(func() { // update immediately after start to populate the allowlist without waiting UpdateFrequencySec seconds updateOnce() ticker := time.NewTicker(updateFrequency) @@ -159,7 +158,7 @@ func (a *onchainAllowlist) Start(ctx context.Context) error { updateOnce() } } - }() + }) return nil }) } @@ -345,9 +344,7 @@ func (a *onchainAllowlist) updateAllowedSendersBatch( } snapshot := make(map[common.Address]struct{}, len(currentAllowedSenderList)) - for k, v := range currentAllowedSenderList { - snapshot[k] = v - } + maps.Copy(snapshot, currentAllowedSenderList) a.allowlist.Store(&snapshot) a.lggr.Infow("allowlist updated in batches successfully", "len", len(currentAllowedSenderList)) diff --git a/core/services/gateway/handlers/vault/aggregator_test.go b/core/services/gateway/handlers/vault/aggregator_test.go index d70c609004e..36943a53a20 100644 --- a/core/services/gateway/handlers/vault/aggregator_test.go +++ b/core/services/gateway/handlers/vault/aggregator_test.go @@ -236,10 +236,7 @@ func TestValidateUsingQuorum_tiedMajoritiesPickDigestDeterministically(t *testin require.NoError(t, err) require.NotEqual(t, digestA, digestB) - wantWinner := digestA - if digestB < digestA { - wantWinner = digestB - } + wantWinner := min(digestB, digestA) for range 300 { m := map[string]jsonrpc.Response[json.RawMessage]{ @@ -320,7 +317,7 @@ func makeDONWithNodesForTest(t *testing.T, name string, id uint32, f uint8, memb t.Helper() nodes := make([]capabilities.Node, nodeCount) members := make([]p2ptypes.PeerID, nodeCount) - for i := 0; i < nodeCount; i++ { + for i := range nodeCount { pid := p2ptypes.PeerID{} pid[0] = memberOffset + byte(i) pid[1] = byte(i) diff --git a/core/services/gateway/handlers/vault/handler_test.go b/core/services/gateway/handlers/vault/handler_test.go index cd281055a10..3280c942b7a 100644 --- a/core/services/gateway/handlers/vault/handler_test.go +++ b/core/services/gateway/handlers/vault/handler_test.go @@ -230,9 +230,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { ID: expectedRequestID, Result: (*json.RawMessage)(&resultBytes), } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err2 := callback.Wait(t.Context()) assert.NoError(t, err2) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -242,7 +240,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Len(t, secretsResponse.Result.Responses, 1, "Should have one encrypted secret in response") assert.Equal(t, createSecretsRequest.EncryptedSecrets[0].Id.Key, secretsResponse.Result.Responses[0].Id.Key, "Secret ID should match") assert.True(t, secretsResponse.Result.Responses[0].Success, "Success should be true") - }() + }) err = h.HandleJSONRPCUserMessage(t.Context(), validJSONRequest, callback) require.NoError(t, err) @@ -472,9 +470,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: (*json.RawMessage)(&emptyParams), } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err2 := callback.Wait(t.Context()) assert.NoError(t, err2) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -483,7 +479,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, validJSONRequest.ID, secretsResponse.ID, "Request ID should match") assert.Contains(t, secretsResponse.Error.Message, "encrypted secret must not be nil at index 1") assert.Equal(t, api.ToJSONRPCErrorCode(api.InvalidParamsError), secretsResponse.Error.Code, "Error code should match") - }() + }) err = h.HandleJSONRPCUserMessage(t.Context(), validJSONRequest, callback) require.NoError(t, err) @@ -516,9 +512,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: (*json.RawMessage)(&emptyParams), } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err2 := callback.Wait(t.Context()) assert.NoError(t, err2) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -527,7 +521,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, validJSONRequest.ID, secretsResponse.ID, "Request ID should match") assert.Contains(t, secretsResponse.Error.Message, "key cannot be empty") assert.Equal(t, api.ToJSONRPCErrorCode(api.InvalidParamsError), secretsResponse.Error.Code, "Error code should match") - }() + }) err = h.HandleJSONRPCUserMessage(t.Context(), validJSONRequest, callback) require.NoError(t, err) @@ -578,9 +572,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { resultBytes, err = json.Marshal(responseData) require.NoError(t, err) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err2 := callback.Wait(t.Context()) assert.NoError(t, err2) var secretsResponse jsonrpc.Response[vaultcommon.DeleteSecretsResponse] @@ -588,7 +580,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.NoError(t, err2) assert.Equal(t, validJSONRequest.ID, secretsResponse.ID, "Request ID should match") assert.True(t, proto.Equal(secretsResponse.Result, responseData), "Response data should match") - }() + }) err = h.HandleJSONRPCUserMessage(t.Context(), validJSONRequest, callback) require.NoError(t, err) @@ -618,9 +610,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: (*json.RawMessage)(&reqDataBytes), } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err2 := callback.Wait(t.Context()) assert.NoError(t, err2) var secretsResponse jsonrpc.Response[vaultcommon.DeleteSecretsResponse] @@ -629,7 +619,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, validJSONRequest.ID, secretsResponse.ID, "Request ID should match") assert.Contains(t, secretsResponse.Error.Message, "secret ID must not be nil at index 1") assert.Equal(t, api.ToJSONRPCErrorCode(api.InvalidParamsError), secretsResponse.Error.Code, "Error code should match") - }() + }) err = h.HandleJSONRPCUserMessage(t.Context(), validJSONRequest, callback) require.NoError(t, err) @@ -777,9 +767,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { }, } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err2 := callback.Wait(t.Context()) assert.NoError(t, err2) var secretsResponse jsonrpc.Response[vaultcommon.ListSecretIdentifiersResponse] @@ -787,7 +775,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.NoError(t, err2) assert.Equal(t, validJSONRequest.ID, secretsResponse.ID, "Request ID should match") assert.Equal(t, response.Error, secretsResponse.Error, "Response error should match") - }() + }) err = h.HandleJSONRPCUserMessage(t.Context(), validJSONRequest, callback) require.NoError(t, err) @@ -808,9 +796,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: (*json.RawMessage)(¶ms), } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := callback.Wait(t.Context()) assert.NoError(t, err) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -819,7 +805,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, unsupportedMethodRequest.ID, secretsResponse.ID, "Request ID should match") assert.Contains(t, secretsResponse.Error.Message, "unsupported method(vault.unsupported.method)") assert.Equal(t, api.ToJSONRPCErrorCode(api.UnsupportedMethodError), secretsResponse.Error.Code, "Error code should match") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), unsupportedMethodRequest, callback) require.NoError(t, err) @@ -838,9 +824,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: &json.RawMessage{}, } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := callback.Wait(t.Context()) assert.NoError(t, err) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -849,7 +833,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, emptyParamsRequest.ID, secretsResponse.ID, "Request ID should match") assert.Contains(t, secretsResponse.Error.Message, "invalid params error: failed to validate create secrets request") assert.Equal(t, api.ToJSONRPCErrorCode(api.InvalidParamsError), secretsResponse.Error.Code, "Error code should match") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), emptyParamsRequest, callback) require.NoError(t, err) @@ -869,9 +853,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: &invalidParams, } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := callback.Wait(t.Context()) assert.NoError(t, err) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -880,7 +862,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, invalidParamsRequest.ID, secretsResponse.ID, "Request ID should match") assert.Equal(t, "invalid params error: failed to validate create secrets request: request batch must contain at least 1 item", secretsResponse.Error.Message, "Error message should match") assert.Equal(t, api.ToJSONRPCErrorCode(api.InvalidParamsError), secretsResponse.Error.Code, "Error code should match") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), invalidParamsRequest, callback) require.NoError(t, err) @@ -938,9 +920,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { Params: (*json.RawMessage)(¶ms), } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { resp, err := callback.Wait(t.Context()) assert.NoError(t, err) var secretsResponse jsonrpc.Response[vaultcommon.CreateSecretsResponse] @@ -949,7 +929,7 @@ func TestVaultHandler_HandleJSONRPCUserMessage(t *testing.T) { assert.Equal(t, jsonRequest.ID, secretsResponse.ID, "Request ID should match") assert.Contains(t, secretsResponse.Error.Message, "invalid params error: failed to validate create secrets request", "Error message should match") assert.Equal(t, api.ToJSONRPCErrorCode(api.InvalidParamsError), secretsResponse.Error.Code, "Error code should match") - }() + }) err := h.HandleJSONRPCUserMessage(t.Context(), jsonRequest, callback) require.NoError(t, err) diff --git a/core/services/job/runner_integration_test.go b/core/services/job/runner_integration_test.go index ba46bba2188..388a9459e3f 100644 --- a/core/services/job/runner_integration_test.go +++ b/core/services/job/runner_integration_test.go @@ -59,7 +59,7 @@ func TestRunner(t *testing.T) { 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.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} kb, err := keyStore.OCR().Create(ctx) require.NoError(t, err) @@ -69,7 +69,7 @@ func TestRunner(t *testing.T) { c.OCR.TransmitterAddress = &taddress c.OCR2.DatabaseTimeout = commonconfig.MustNewDuration(time.Second) c.OCR2.ContractTransmitterTransmitTimeout = commonconfig.MustNewDuration(time.Second) - c.Insecure.OCRDevelopmentMode = ptr(true) + c.Insecure.OCRDevelopmentMode = new(true) }) ethClient := cltest.NewEthMocksWithStartupAssertions(t) @@ -566,9 +566,9 @@ answer1 [type=median index=0]; for _, tc := range testCases { config = configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - c.OCR.CaptureEATelemetry = ptr(tc.specCaptureEATelemetry) + c.OCR.CaptureEATelemetry = new(tc.specCaptureEATelemetry) }) legacyChains2 := evmtest.NewLegacyChains(t, evmtest.TestChainOpts{ @@ -791,7 +791,6 @@ func TestRunner_WebhookJobRemoved(t *testing.T) { app := cltest.NewApplicationWithConfig(t, cfg, ethClient) require.NoError(t, app.Start(testutils.Context(t))) - var ( eiName = "substrate-ei" eiSpec = map[string]any{"foo": "bar"} @@ -849,5 +848,3 @@ observationSource = """ cltest.DeleteJobViaWeb(t, app, job.ID) } - -func ptr[T any](t T) *T { return &t } diff --git a/core/services/llo/telem/sampling.go b/core/services/llo/telem/sampling.go index 29136fe6c19..ce2604248df 100644 --- a/core/services/llo/telem/sampling.go +++ b/core/services/llo/telem/sampling.go @@ -87,9 +87,7 @@ func (s *sampler) StartPruningLoop(ctx context.Context, wg *sync.WaitGroup) { return } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { t := time.NewTicker(s.prunePeriod) defer t.Stop() @@ -101,7 +99,7 @@ func (s *sampler) StartPruningLoop(ctx context.Context, wg *sync.WaitGroup) { return } } - }() + }) } // pruneStorage removes all records which are older than a predefined period (s.prunePeriod). diff --git a/core/services/llo/telem/sampling_test.go b/core/services/llo/telem/sampling_test.go index 491367526e4..e5fe1812311 100644 --- a/core/services/llo/telem/sampling_test.go +++ b/core/services/llo/telem/sampling_test.go @@ -116,8 +116,7 @@ func TestSample(t *testing.T) { t.Parallel() lggr := logger.TestSugared(t) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() samplr := newSampler(lggr, true) samplr.StartPruningLoop(ctx, &sync.WaitGroup{}) @@ -146,8 +145,7 @@ func TestPruningLoop(t *testing.T) { t.Parallel() lggr := logger.TestSugared(t) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() samplr := newSampler(lggr, true) // We need a prune time of at least one second in order to detect outdated entries. diff --git a/core/services/llo/telem/telemetry.go b/core/services/llo/telem/telemetry.go index db91065a6d1..b956e9126e7 100644 --- a/core/services/llo/telem/telemetry.go +++ b/core/services/llo/telem/telemetry.go @@ -227,9 +227,7 @@ func (t *telemeter) start(_ context.Context) error { for { select { case tcc := <-t.chch: - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case p, ok := <-tcc.in: @@ -242,7 +240,7 @@ func (t *telemeter) start(_ context.Context) error { return } } - }() + }) case p := <-t.chTelemetryPipeline: t.prepareV3PremiumLegacyTelemetry(p) case rt := <-t.chOutcomeTelemetry: diff --git a/core/services/llo/telem/telemetry_test.go b/core/services/llo/telem/telemetry_test.go index 863c5b82870..682c80374a9 100644 --- a/core/services/llo/telem/telemetry_test.go +++ b/core/services/llo/telem/telemetry_test.go @@ -304,13 +304,13 @@ func Test_Telemeter_observationScopedTelemetry(t *testing.T) { Name: "test-bridge-1", RequestData: []byte(`foo`), ResponseData: []byte(`bar`), - ResponseError: ptr("test error"), + ResponseError: new("test error"), ResponseStatusCode: 200, RequestStartTimestamp: time.Unix(1, 1), RequestFinishTimestamp: time.Unix(2, 1), LocalCacheHit: true, SpecID: 3, - StreamID: ptr(uint32(135)), + StreamID: new(uint32(135)), DotID: "ds1", } tm.TrackSeqNr(opts.ConfigDigest(), opts.SeqNr()) @@ -357,7 +357,7 @@ func Test_Telemeter_observationScopedTelemetry(t *testing.T) { StreamValueType: 1, StreamValueBinary: []byte{0x01, 0x02, 0x03}, StreamValueText: "stream value text", - ObservationError: ptr("test error"), + ObservationError: new("test error"), ObservationTimestamp: time.Unix(1, 1).UnixNano(), ObservationFinishedAt: time.Unix(2, 1).UnixNano(), SeqNr: 42, @@ -783,7 +783,7 @@ func Test_Telemeter_reportTelemetry(t *testing.T) { tm.TrackSeqNr(opts.ConfigDigest(), opts.SeqNr()) receivedChannels := make([]uint32, 0, 3) - for i := 0; i < 3; i++ { + for range 3 { tLog := <-m.chTypedLogs assert.Equal(t, synchronization.LLOReport, tLog.telemType) decoded := &llocommon.LLOReportTelemetry{} @@ -852,9 +852,9 @@ func Test_Telemeter_outcomeTelemetry_samplingAtFlushTime(t *testing.T) { require.NotNil(t, ch) transmittingSeqNrs := make([]uint64, 0, secondsCovered) - for s := 0; s < secondsCovered; s++ { + for s := range secondsCovered { secStart := time.Unix(baseObservationUnix+int64(s), 0).UnixNano() - for i := 0; i < outcomesPerSecond; i++ { + for i := range outcomesPerSecond { seqNr := baseSeqNr + uint64(s*outcomesPerSecond+i) // Spread observation timestamps within the same wall-clock // second (different nanos, same second bucket). @@ -885,7 +885,7 @@ func Test_Telemeter_outcomeTelemetry_samplingAtFlushTime(t *testing.T) { // We expect one outcome telemetry per wall-clock second (sampler // admits the first survivor per second bucket). received := make([]uint64, 0, secondsCovered) - for i := 0; i < secondsCovered; i++ { + for i := range secondsCovered { select { case tLog := <-m.chTypedLogs: assert.Equal(t, synchronization.LLOOutcome, tLog.telemType) @@ -925,9 +925,9 @@ func Test_Telemeter_outcomeTelemetry_samplingAtFlushTime(t *testing.T) { require.NotNil(t, ch) transmittingSeqNrs := make([]uint64, 0, secondsCovered) - for s := 0; s < secondsCovered; s++ { + for s := range secondsCovered { secStart := time.Unix(baseObservationUnix+int64(s), 0).UnixNano() - for i := 0; i < outcomesPerSecond; i++ { + for i := range outcomesPerSecond { seqNr := baseSeqNr + uint64(s*outcomesPerSecond+i) obsTs := uint64(secStart + int64(i)*int64(10*time.Millisecond)) ch <- &llocommon.LLOOutcomeTelemetry{ @@ -953,7 +953,7 @@ func Test_Telemeter_outcomeTelemetry_samplingAtFlushTime(t *testing.T) { // Without sampling, every transmit produces telemetry — one per second // (since only one seqNr per second transmits). - for i := 0; i < secondsCovered; i++ { + for i := range secondsCovered { select { case tLog := <-m.chTypedLogs: assert.Equal(t, synchronization.LLOOutcome, tLog.telemType) @@ -1011,9 +1011,9 @@ func Test_Telemeter_reportTelemetry_samplingAtFlushTime(t *testing.T) { transmittingSeqNrs := make([]uint64, 0, secondsCovered) expectedBufferEntries := 0 - for s := 0; s < secondsCovered; s++ { + for s := range secondsCovered { secStart := time.Unix(baseObservationUnix+int64(s), 0).UnixNano() - for i := 0; i < seqNrsPerSecond; i++ { + for i := range seqNrsPerSecond { seqNr := baseSeqNr + uint64(s*seqNrsPerSecond+i) obsTs := uint64(secStart + int64(i)*int64(10*time.Millisecond)) // Each seqNr emits a report per channel — mimics the @@ -1051,7 +1051,7 @@ func Test_Telemeter_reportTelemetry_samplingAtFlushTime(t *testing.T) { // first survivor per (channelId, second) fingerprint). expected := secondsCovered * len(channels) seen := make(map[uint32]int) - for i := 0; i < expected; i++ { + for i := range expected { select { case tLog := <-m.chTypedLogs: assert.Equal(t, synchronization.LLOReport, tLog.telemType) @@ -1093,9 +1093,9 @@ func Test_Telemeter_reportTelemetry_samplingAtFlushTime(t *testing.T) { transmittingSeqNrs := make([]uint64, 0, secondsCovered) expectedBufferEntries := 0 - for s := 0; s < secondsCovered; s++ { + for s := range secondsCovered { secStart := time.Unix(baseObservationUnix+int64(s), 0).UnixNano() - for i := 0; i < seqNrsPerSecond; i++ { + for i := range seqNrsPerSecond { seqNr := baseSeqNr + uint64(s*seqNrsPerSecond+i) obsTs := uint64(secStart + int64(i)*int64(10*time.Millisecond)) for _, channelID := range channels { @@ -1128,7 +1128,7 @@ func Test_Telemeter_reportTelemetry_samplingAtFlushTime(t *testing.T) { // Without sampling, every report at a transmitting seqNr flushes. // One transmitting seqNr per second × len(channels) reports per seqNr. expected := secondsCovered * len(channels) - for i := 0; i < expected; i++ { + for i := range expected { select { case tLog := <-m.chTypedLogs: assert.Equal(t, synchronization.LLOReport, tLog.telemType) @@ -1185,7 +1185,7 @@ func Test_Telemeter_reportTelemetry_samplingAtFlushTime(t *testing.T) { tm.TrackSeqNr(cd, opts.SeqNr()) received := make(map[uint32]struct{}) - for i := 0; i < 3; i++ { + for i := range 3 { select { case tLog := <-m.chTypedLogs: decoded := &llocommon.LLOReportTelemetry{} @@ -1199,5 +1199,3 @@ func Test_Telemeter_reportTelemetry_samplingAtFlushTime(t *testing.T) { "each per-channel report should be admitted (distinct sampler fingerprints)") }) } - -func ptr[T any](t T) *T { return &t } diff --git a/core/services/nodestatusreporter/jobspec/job_spec_reporter.go b/core/services/nodestatusreporter/jobspec/job_spec_reporter.go index 79ec4ffb53c..9ee6b91b8de 100644 --- a/core/services/nodestatusreporter/jobspec/job_spec_reporter.go +++ b/core/services/nodestatusreporter/jobspec/job_spec_reporter.go @@ -10,7 +10,6 @@ import ( "time" "github.com/google/uuid" - "google.golang.org/protobuf/proto" "github.com/smartcontractkit/chainlink-common/pkg/beholder" "github.com/smartcontractkit/chainlink-common/pkg/services" @@ -171,11 +170,11 @@ func (s *Service) buildEvent(ctx context.Context, jb job.Job, trigger events.Emi } if jb.GasLimit.Valid { - event.GasLimit = proto.Uint32(jb.GasLimit.Uint32) + event.GasLimit = new(jb.GasLimit.Uint32) } if jb.StreamID != nil { sid := *jb.StreamID - event.StreamId = proto.Uint32(sid) + event.StreamId = new(sid) } if jb.PipelineSpec != nil { @@ -313,13 +312,13 @@ func buildOCR2OracleSpecInfo(spec *job.OCR2OracleSpec) (*events.OCR2OracleSpecIn } if spec.FeedID != nil { - info.FeedId = proto.String(spec.FeedID.Hex()) + info.FeedId = new(spec.FeedID.Hex()) } if spec.TransmitterID.Valid { - info.TransmitterId = proto.String(spec.TransmitterID.String) + info.TransmitterId = new(spec.TransmitterID.String) } if spec.OCRKeyBundleID.Valid { - info.OcrKeyBundleId = proto.String(spec.OCRKeyBundleID.String) + info.OcrKeyBundleId = new(spec.OCRKeyBundleID.String) } if spec.Relay == "evm" { @@ -359,22 +358,22 @@ func buildEVMRelayConfig(relayConfigJSON []byte, chainID, transmitterID string) SendingKeys: cfg.SendingKeys, } if cfg.FromBlock != nil { - evmProto.FromBlock = proto.Uint64(*cfg.FromBlock) + evmProto.FromBlock = new(*cfg.FromBlock) } if cfg.EnableDualTransmission != nil { - evmProto.EnableDualTransmission = proto.Bool(*cfg.EnableDualTransmission) + evmProto.EnableDualTransmission = new(*cfg.EnableDualTransmission) } if cfg.EnableTriggerCapability != nil { - evmProto.EnableTriggerCapability = proto.Bool(*cfg.EnableTriggerCapability) + evmProto.EnableTriggerCapability = new(*cfg.EnableTriggerCapability) } if cfg.LLODonID != nil { - evmProto.LloDonId = proto.Uint64(*cfg.LLODonID) + evmProto.LloDonId = new(*cfg.LLODonID) } if cfg.FeedID != nil { - evmProto.FeedId = proto.String(*cfg.FeedID) + evmProto.FeedId = new(*cfg.FeedID) } if cfg.ProviderType != nil { - evmProto.ProviderType = proto.String(*cfg.ProviderType) + evmProto.ProviderType = new(*cfg.ProviderType) } return evmProto, nil } diff --git a/core/services/ocr2/plugins/vault/plugin.go b/core/services/ocr2/plugins/vault/plugin.go index 6b41caa8571..a90743aaae9 100644 --- a/core/services/ocr2/plugins/vault/plugin.go +++ b/core/services/ocr2/plugins/vault/plugin.go @@ -1329,7 +1329,7 @@ func userFacingError(err error, fallback string) string { return fallback } -func logUserErrorAware(l logger.Logger, msg string, err error, keysAndValues ...interface{}) { +func logUserErrorAware(l logger.Logger, msg string, err error, keysAndValues ...any) { keysAndValues = append(keysAndValues, "error", err) lggr := l.Helper(1) if errors.Is(err, &userError{}) { diff --git a/core/services/ocr2/plugins/vault/plugin_test.go b/core/services/ocr2/plugins/vault/plugin_test.go index 058489bd6ee..6f6dac8f324 100644 --- a/core/services/ocr2/plugins/vault/plugin_test.go +++ b/core/services/ocr2/plugins/vault/plugin_test.go @@ -7,6 +7,7 @@ import ( "encoding/hex" "errors" "fmt" + "maps" "slices" "strings" "sync" @@ -552,9 +553,7 @@ func assertPendingQueueItemsContain(t *testing.T, gotItems [][]byte, expected ma t.Helper() remaining := make(map[string]proto.Message, len(expected)) - for id, payload := range expected { - remaining[id] = payload - } + maps.Copy(remaining, expected) var total int for _, got := range gotItems { @@ -6287,7 +6286,7 @@ func TestPlugin_ValidateObservation_GetSecretsRequest(t *testing.T) { EncryptedDecryptionKeyShares: []*vaultcommon.EncryptedShares{ { EncryptionKey: pks, - Shares: []string{strings.Repeat("1", 1000)}, + Shares: []string{strings.Repeat("1", 1000)}, }, }, }, @@ -7840,7 +7839,7 @@ func TestPlugin_broadcastBlobPayloads(t *testing.T) { payloads := make([][]byte, maxConcurrentBlobBroadcasts*2+1) ids := make([][]string, len(payloads)) for i := range payloads { - payloads[i] = []byte(fmt.Sprintf("payload-%d", i)) + payloads[i] = fmt.Appendf(nil, "payload-%d", i) ids[i] = []string{fmt.Sprintf("req-%d", i)} } @@ -7886,7 +7885,7 @@ func TestPlugin_broadcastBlobPayloads(t *testing.T) { done <- broadcastResult{payloads: result, err: err} }() - for i := 0; i < maxConcurrentBlobBroadcasts; i++ { + for i := range maxConcurrentBlobBroadcasts { select { case <-started: case <-time.After(time.Second): diff --git a/core/services/ocrcommon/peer_wrapper_test.go b/core/services/ocrcommon/peer_wrapper_test.go index 0be021a8335..8270c9e9443 100644 --- a/core/services/ocrcommon/peer_wrapper_test.go +++ b/core/services/ocrcommon/peer_wrapper_test.go @@ -32,7 +32,7 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { t.Run("with no p2p keys returns error", func(t *testing.T) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) + c.P2P.V2.Enabled = new(true) }) keyStore := cltest.NewKeyStore(t, db) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), db, logger.TestLogger(t)) @@ -46,9 +46,9 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { require.NoError(t, err) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - c.P2P.PeerID = ptr(k.PeerID()) + c.P2P.PeerID = new(k.PeerID()) }) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), db, logger.TestLogger(t)) @@ -59,8 +59,8 @@ 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)) + c.P2P.V2.Enabled = new(true) + c.P2P.PeerID = new(p2pkey.PeerID(peerID)) }) keyStore := cltest.NewKeyStore(t, db) @@ -79,9 +79,9 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { require.NoError(t, err) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - c.P2P.PeerID = ptr(k2.PeerID()) + c.P2P.PeerID = new(k2.PeerID()) }) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), db, logger.TestLogger(t)) @@ -93,9 +93,9 @@ 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.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - c.P2P.PeerID = ptr(p2pkey.PeerID(peerID)) + c.P2P.PeerID = new(p2pkey.PeerID(peerID)) }) keyStore := cltest.NewKeyStore(t, db) @@ -119,16 +119,16 @@ func Test_SingletonPeerWrapper_Close(t *testing.T) { require.NoError(t, err) 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.Enabled = new(true) + c.P2P.PeerID = new(k.PeerID()) c.P2P.V2.DeltaDial = commonconfig.MustNewDuration(100 * time.Millisecond) c.P2P.V2.DeltaReconcile = commonconfig.MustNewDuration(1 * time.Second) p2paddresses := []string{ fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t)), } - c.P2P.V2.ListenAddresses = ptr(p2paddresses) - c.P2P.V2.AnnounceAddresses = ptr(p2paddresses) + c.P2P.V2.ListenAddresses = new(p2paddresses) + c.P2P.V2.AnnounceAddresses = new(p2paddresses) }) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), db, logger.TestLogger(t)) @@ -144,5 +144,3 @@ func Test_SingletonPeerWrapper_Close(t *testing.T) { require.True(t, pw.IsStarted(), "Should have started successfully") require.NoError(t, pw.Close()) } - -func ptr[T any](t T) *T { return &t } diff --git a/core/services/p2p/shared_peer_test.go b/core/services/p2p/shared_peer_test.go index 93eab232316..9ab11ddac94 100644 --- a/core/services/p2p/shared_peer_test.go +++ b/core/services/p2p/shared_peer_test.go @@ -32,9 +32,9 @@ func TestDon2DonSharedPeer_WithRealSingletonPeerWrapper(t *testing.T) { require.NoError(t, err) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.P2P.V2.Enabled = ptr(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} - c.P2P.PeerID = ptr(k.PeerID()) + c.P2P.PeerID = new(k.PeerID()) }) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), db, logger.TestLogger(t)) @@ -164,5 +164,3 @@ func (m *mockStream) Close() error { close(m.msgCh) return nil } - -func ptr[T any](t T) *T { return &t } diff --git a/core/services/pg/lease_lock.go b/core/services/pg/lease_lock.go index f566a91546d..3113d7e378d 100644 --- a/core/services/pg/lease_lock.go +++ b/core/services/pg/lease_lock.go @@ -13,6 +13,7 @@ import ( "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" + "github.com/smartcontractkit/chainlink-common/pkg/timeutil" "github.com/smartcontractkit/chainlink-common/pkg/utils" "github.com/smartcontractkit/chainlink/v2/core/logger" ) @@ -133,7 +134,7 @@ func (l *leaseLock) TakeAndHold(ctx context.Context) (err error) { err = stderrors.Join(err, l.conn.Close()) } return err - case <-time.After(utils.WithJitter(l.cfg.LeaseRefreshInterval)): + case <-time.After(timeutil.JitterPct(0.1).Apply(l.cfg.LeaseRefreshInterval)): } } l.logger.Debug("Got exclusive lease on database") diff --git a/core/services/pipeline/common.go b/core/services/pipeline/common.go index 7d7dcb13c19..df85533b3f7 100644 --- a/core/services/pipeline/common.go +++ b/core/services/pipeline/common.go @@ -26,24 +26,24 @@ import ( ) const ( - BlockHeaderFeederJobType string = "blockheaderfeeder" - BlockhashStoreJobType string = "blockhashstore" - BootstrapJobType string = "bootstrap" - CRESettings string = "cresettings" - CronJobType string = "cron" - CCIPJobType string = "ccip" - CCVCommitteeVerifierJobType string = "ccvcommitteeverifier" - CCVExecutorJobType string = "ccvexecutor" - DirectRequestJobType string = "directrequest" - FluxMonitorJobType string = "fluxmonitor" - GatewayJobType string = "gateway" - OffchainReporting2JobType string = "offchainreporting2" - OffchainReportingJobType string = "offchainreporting" - StreamJobType string = "stream" - VRFJobType string = "vrf" - WebhookJobType string = "webhook" - WorkflowJobType string = "workflow" - StandardCapabilitiesJobType string = "standardcapabilities" + BlockHeaderFeederJobType string = "blockheaderfeeder" + BlockhashStoreJobType string = "blockhashstore" + BootstrapJobType string = "bootstrap" + CRESettings string = "cresettings" + CronJobType string = "cron" + CCIPJobType string = "ccip" + CCVCommitteeVerifierJobType string = "ccvcommitteeverifier" + CCVExecutorJobType string = "ccvexecutor" + DirectRequestJobType string = "directrequest" + FluxMonitorJobType string = "fluxmonitor" + GatewayJobType string = "gateway" + OffchainReporting2JobType string = "offchainreporting2" + OffchainReportingJobType string = "offchainreporting" + StreamJobType string = "stream" + VRFJobType string = "vrf" + WebhookJobType string = "webhook" + WorkflowJobType string = "workflow" + StandardCapabilitiesJobType string = "standardcapabilities" ) type ( @@ -141,7 +141,10 @@ type Result struct { // OutputDB dumps a single result output for a pipeline_run or pipeline_task_run func (result Result) OutputDB() jsonserializable.JSONSerializable { - return jsonserializable.JSONSerializable{Val: result.Value, Valid: !(result.Value == nil || (reflect.ValueOf(result.Value).Kind() == reflect.Ptr && reflect.ValueOf(result.Value).IsNil()))} + return jsonserializable.JSONSerializable{ + Val: result.Value, + Valid: result.Value != nil && (reflect.ValueOf(result.Value).Kind() != reflect.Pointer || !reflect.ValueOf(result.Value).IsNil()), + } } // ErrorDB dumps a single result error for a pipeline_task_run @@ -349,11 +352,11 @@ const ( ) var ( - stringType = reflect.TypeOf("") - bytesType = reflect.TypeOf([]byte(nil)) - bytes20Type = reflect.TypeOf([20]byte{}) - int32Type = reflect.TypeOf(int32(0)) - nullUint32Type = reflect.TypeOf(cnull.Uint32{}) + stringType = reflect.TypeFor[string]() + bytesType = reflect.TypeFor[[]byte]() + bytes20Type = reflect.TypeFor[[20]byte]() + int32Type = reflect.TypeFor[int32]() + nullUint32Type = reflect.TypeFor[cnull.Uint32]() ) func UnmarshalTaskFromMap(taskType TaskType, taskMap any, ID int, dotID string) (_ Task, err error) { diff --git a/core/services/pipeline/common_eth.go b/core/services/pipeline/common_eth.go index 00c8fabfa72..57339d8dcf8 100644 --- a/core/services/pipeline/common_eth.go +++ b/core/services/pipeline/common_eth.go @@ -325,7 +325,7 @@ func convertToETHABIInteger(val any, abiType abi.Type) (any, error) { // could hold it. Unsure of why this decision was taken. // See https://github.com/ethereum/go-ethereum/blob/master/accounts/abi/reflect.go#L61 for // the relevant code. - if ty == reflect.TypeOf(&big.Int{}) { + if ty == reflect.TypeFor[*big.Int]() { return i, nil } return nil, fmt.Errorf("unknown Go type %+v for abi type %+v", ty.String(), abiType) diff --git a/core/services/pipeline/common_eth_test.go b/core/services/pipeline/common_eth_test.go index e34dc8ca035..d8ca3fff46c 100644 --- a/core/services/pipeline/common_eth_test.go +++ b/core/services/pipeline/common_eth_test.go @@ -139,7 +139,7 @@ func Test_convertToETHABIBytes_Errors(t *testing.T) { {"0xasdfasdfasdfasdfasdfsadfasdfasdfasdfasdf", "invalid hex"}, } { t.Run(fmt.Sprintf("%T,%s", tt.val, tt.errStr), func(t *testing.T) { - a := reflect.TypeOf([20]byte{}) + a := reflect.TypeFor[[20]byte]() b := reflect.ValueOf(tt.val) _, err := convertToETHABIBytes(a, b, 20) require.Error(t, err) diff --git a/core/services/pipeline/common_test.go b/core/services/pipeline/common_test.go index e3bbadfc137..7907c089b99 100644 --- a/core/services/pipeline/common_test.go +++ b/core/services/pipeline/common_test.go @@ -247,13 +247,13 @@ func TestSelectGasLimit(t *testing.T) { t.Parallel() gcfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].GasEstimator.LimitDefault = ptr(uint64(999)) + c.EVM[0].GasEstimator.LimitDefault = new(uint64(999)) c.EVM[0].GasEstimator.LimitJobType = toml.GasLimitJobType{ - DR: ptr(uint32(100)), - VRF: ptr(uint32(101)), - FM: ptr(uint32(102)), - OCR: ptr(uint32(103)), - OCR2: ptr(uint32(105)), + DR: new(uint32(100)), + VRF: new(uint32(101)), + FM: new(uint32(102)), + OCR: new(uint32(103)), + OCR2: new(uint32(105)), } }) cfg := evmtest.NewChainScopedConfig(t, gcfg) diff --git a/core/services/pipeline/runner.go b/core/services/pipeline/runner.go index 35d675f7e58..50ae2d7ac8e 100644 --- a/core/services/pipeline/runner.go +++ b/core/services/pipeline/runner.go @@ -801,18 +801,14 @@ func (r *runner) scheduleUnfinishedRuns() { var wgRunsDone sync.WaitGroup err := r.orm.GetUnfinishedRuns(ctx, now, func(run Run) error { - wgRunsDone.Add(1) - - go func() { - defer wgRunsDone.Done() - + wgRunsDone.Go(func() { _, err := r.Run(ctx, &run, false, nil) if ctx.Err() != nil { return } else if err != nil { r.lggr.Errorw("Pipeline run init job resumption failed", "err", err) } - }() + }) return nil }) diff --git a/core/services/pipeline/task.divide_test.go b/core/services/pipeline/task.divide_test.go index 648f2c84b70..1e841a68b98 100644 --- a/core/services/pipeline/task.divide_test.go +++ b/core/services/pipeline/task.divide_test.go @@ -229,7 +229,7 @@ ds1 -> div_by_ds2 -> multiply; finalResult := trrs[3] require.NoError(t, finalResult.Result.Error) - require.Equal(t, reflect.TypeOf(decimal.Decimal{}), reflect.TypeOf(finalResult.Result.Value)) + require.Equal(t, reflect.TypeFor[decimal.Decimal](), reflect.TypeOf(finalResult.Result.Value)) assert.Equal(t, "1000012.34", finalResult.Result.Value.(decimal.Decimal).String()) } diff --git a/core/services/pipeline/task.eth_tx.go b/core/services/pipeline/task.eth_tx.go index f996daecaa9..29df2e44211 100644 --- a/core/services/pipeline/task.eth_tx.go +++ b/core/services/pipeline/task.eth_tx.go @@ -190,7 +190,7 @@ func decodeMeta(metaMap MapParam) (*txmgr.TxMeta, error) { case int32Type: i, err2 := strconv.ParseInt(data.(string), 10, 32) return int32(i), err2 - case reflect.TypeOf(common.Hash{}): + case reflect.TypeFor[common.Hash](): hb, err := hex.DecodeString(data.(string)) if err != nil { return nil, err @@ -221,7 +221,7 @@ func decodeTransmitChecker(checkerMap MapParam) (txmgr.TransmitCheckerSpec, erro switch from { case stringType: switch to { - case reflect.TypeOf(common.Address{}): + case reflect.TypeFor[common.Address](): ab, err := hex.DecodeString(data.(string)) if err != nil { return nil, err diff --git a/core/services/pipeline/task.eth_tx_test.go b/core/services/pipeline/task.eth_tx_test.go index 6b5fe14eb60..ba59796441b 100644 --- a/core/services/pipeline/task.eth_tx_test.go +++ b/core/services/pipeline/task.eth_tx_test.go @@ -613,4 +613,5 @@ func TestETHTxTask(t *testing.T) { } } -func ptr[T any](t T) *T { return &t } +//go:fix inline +func ptr[T any](t T) *T { return new(t) } diff --git a/core/services/registrysyncer/syncer.go b/core/services/registrysyncer/syncer.go index 8289645a0cf..6372c8ae7ef 100644 --- a/core/services/registrysyncer/syncer.go +++ b/core/services/registrysyncer/syncer.go @@ -136,16 +136,12 @@ func newReader(ctx context.Context, lggr logger.Logger, relayer ContractReaderFa func (s *registrySyncer) Start(ctx context.Context) error { return s.StartOnce("RegistrySyncer", func() error { - s.wg.Add(1) - go func() { - defer s.wg.Done() + s.wg.Go(func() { s.syncLoop() - }() - s.wg.Add(1) - go func() { - defer s.wg.Done() + }) + s.wg.Go(func() { s.updateStateLoop() - }() + }) return nil }) } diff --git a/core/services/registrysyncer/v2/syncer.go b/core/services/registrysyncer/v2/syncer.go index c4b30e7e285..0c3544dd68d 100644 --- a/core/services/registrysyncer/v2/syncer.go +++ b/core/services/registrysyncer/v2/syncer.go @@ -160,16 +160,12 @@ func buildV2ContractReaderConfig() config.ChainReaderConfig { func (s *registrySyncer) Start(ctx context.Context) error { return s.StartOnce("RegistrySyncer", func() error { - s.wg.Add(1) - go func() { - defer s.wg.Done() + s.wg.Go(func() { s.syncLoop() - }() - s.wg.Add(1) - go func() { - defer s.wg.Done() + }) + s.wg.Go(func() { s.updateStateLoop() - }() + }) return nil }) } diff --git a/core/services/relay/evm/capabilities/testutils/signing_keystore.go b/core/services/relay/evm/capabilities/testutils/signing_keystore.go index cd394c16a80..cce37623bc5 100644 --- a/core/services/relay/evm/capabilities/testutils/signing_keystore.go +++ b/core/services/relay/evm/capabilities/testutils/signing_keystore.go @@ -4,6 +4,7 @@ import ( "context" "crypto/ecdsa" "errors" + "slices" "github.com/ethereum/go-ethereum/common" @@ -40,10 +41,8 @@ func NewSigningKeystore(addressToKey map[string]*ecdsa.PrivateKey, addresses []e } func (s *SigningKeystore) CheckEnabled(ctx context.Context, address common.Address) error { - for _, addr := range s.addresses { - if addr == address { - return nil - } + if slices.Contains(s.addresses, address) { + return nil } return errors.New("not enabled") } diff --git a/core/services/relay/evm/chain_components_test.go b/core/services/relay/evm/chain_components_test.go index 8fed72f1ae8..e51875a51a7 100644 --- a/core/services/relay/evm/chain_components_test.go +++ b/core/services/relay/evm/chain_components_test.go @@ -167,7 +167,7 @@ func TestContractReaderEventsInitValidation(t *testing.T) { GenericDataWordDetails: map[string]commonevm.DataWordDetail{ "DW": { Name: "someDW", - Index: ptr(0), + Index: new(0), }, }, }, @@ -195,7 +195,7 @@ func TestContractReaderEventsInitValidation(t *testing.T) { GenericDataWordDetails: map[string]commonevm.DataWordDetail{ "DW": { Name: "someDW", - Index: ptr(0), + Index: new(0), Type: "abcdefg", }, }, @@ -489,7 +489,7 @@ func (h *helper) TXM(t *testing.T, client client.Client) evmtxmgr.TxManager { clconfig := configtest.NewGeneralConfigSimulated(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Database.Listener.FallbackPollInterval = commonconfig.MustNewDuration(100 * time.Millisecond) - c.EVM[0].GasEstimator.EIP1559DynamicFees = ptr(true) + c.EVM[0].GasEstimator.EIP1559DynamicFees = new(true) }) clconfig.EVMConfigs()[0].GasEstimator.PriceMax = assets.GWei(100) @@ -516,5 +516,3 @@ func (h *helper) TXM(t *testing.T, client client.Client) evmtxmgr.TxManager { h.txm = chain.TxManager() return h.txm } - -func ptr[T any](v T) *T { return &v } diff --git a/core/services/relay/evm/evmtesting/bindings_test_adapter.go b/core/services/relay/evm/evmtesting/bindings_test_adapter.go index 863dbf0b6a3..0c6ff71cc1f 100644 --- a/core/services/relay/evm/evmtesting/bindings_test_adapter.go +++ b/core/services/relay/evm/evmtesting/bindings_test_adapter.go @@ -269,11 +269,11 @@ func (b *bindingChainWriterProxy) GetTransactionStatus(ctx context.Context, tran } func removeAddressFromReadIdentifier(s string) string { - index := strings.Index(s, "-") - if index == -1 { + _, after, ok := strings.Cut(s, "-") + if !ok { return s } - return s[index+1:] + return after } func (b *bindingsMapping) createDelegates() { @@ -295,7 +295,7 @@ func (b *bindingsMapping) createDelegates() { } func (b *bindingsMapping) createDelegateForMethodTakingLatestParams() *Delegate { - delegate := Delegate{inputType: reflect.TypeOf(bindings.GetElementAtIndexInput{})} + delegate := Delegate{inputType: reflect.TypeFor[bindings.GetElementAtIndexInput]()} delegate.delegateFunc = func(ctx context.Context, readyKey string, input *any, level primitives.ConfidenceLevel) (any, error) { methodInvocation := func(ctx context.Context, readKey string, input *bindings.GetElementAtIndexInput, level primitives.ConfidenceLevel) (any, error) { chainReaderTester := b.GetChainReaderTester(readKey) @@ -319,7 +319,7 @@ func (b *bindingsMapping) createDelegateForMethodReturningAlterableUint64() *Del } func (b *bindingsMapping) createDelegateForMethodReturningSeenStruct() *Delegate { - delegate := Delegate{inputType: reflect.TypeOf(bindings.ReturnSeenInput{})} + delegate := Delegate{inputType: reflect.TypeFor[bindings.ReturnSeenInput]()} delegate.delegateFunc = func(ctx context.Context, readyKey string, input *any, level primitives.ConfidenceLevel) (any, error) { methodInvocation := func(ctx context.Context, readKey string, input *bindings.ReturnSeenInput, level primitives.ConfidenceLevel) (any, error) { chainReaderTester := b.GetChainReaderTester(readKey) @@ -445,7 +445,7 @@ func (d Delegate) apply(ctx context.Context, readKey string, input any, confiden // Utility function to converted original types from and to bindings expected types. func convertStruct(src any, dst any) error { - if reflect.TypeOf(src).Kind() == reflect.Ptr && reflect.TypeOf(dst).Kind() == reflect.Ptr && reflect.TypeOf(src).Elem() == reflect.TypeOf(interfacetests.LatestParams{}) && reflect.TypeOf(dst).Elem() == reflect.TypeOf(bindings.GetElementAtIndexInput{}) { + if reflect.TypeOf(src).Kind() == reflect.Pointer && reflect.TypeOf(dst).Kind() == reflect.Pointer && reflect.TypeOf(src).Elem() == reflect.TypeFor[interfacetests.LatestParams]() && reflect.TypeOf(dst).Elem() == reflect.TypeFor[bindings.GetElementAtIndexInput]() { value := src.(*interfacetests.LatestParams).I dst.(*bindings.GetElementAtIndexInput).I = big.NewInt(int64(value)) return nil @@ -459,7 +459,7 @@ func convertStruct(src any, dst any) error { return err } switch { - case reflect.TypeOf(dst).Elem() == reflect.TypeOf(interfacetests.TestStructWithExtraField{}): + case reflect.TypeOf(dst).Elem() == reflect.TypeFor[interfacetests.TestStructWithExtraField](): destTestStruct := dst.(*interfacetests.TestStructWithExtraField) if destTestStruct != nil { auxTestStruct := &interfacetests.TestStruct{} @@ -474,7 +474,7 @@ func convertStruct(src any, dst any) error { destTestStruct.NestedDynamicStruct.FixedBytes = sourceTestStruct.NestedDynamicStruct.FixedBytes destTestStruct.ExtraField = interfacetests.AnyExtraValue } - case reflect.TypeOf(dst).Elem() == reflect.TypeOf(interfacetests.TestStruct{}): + case reflect.TypeOf(dst).Elem() == reflect.TypeFor[interfacetests.TestStruct](): destTestStruct := dst.(*interfacetests.TestStruct) if destTestStruct != nil { sourceTestStruct := src.(bindings.TestStruct) @@ -484,7 +484,7 @@ func convertStruct(src any, dst any) error { destTestStruct.NestedDynamicStruct.Inner.I = int(sourceTestStruct.NestedDynamicStruct.Inner.IntVal) destTestStruct.NestedDynamicStruct.FixedBytes = sourceTestStruct.NestedDynamicStruct.FixedBytes } - case reflect.TypeOf(src) == reflect.TypeOf(interfacetests.TestStruct{}) && reflect.TypeOf(dst) == reflect.TypeOf(&bindings.AddTestStructInput{}): + case reflect.TypeOf(src) == reflect.TypeFor[interfacetests.TestStruct]() && reflect.TypeOf(dst) == reflect.TypeFor[*bindings.AddTestStructInput](): destTestStruct := dst.(*bindings.AddTestStructInput) if destTestStruct != nil { sourceTestStruct := src.(interfacetests.TestStruct) @@ -494,7 +494,7 @@ func convertStruct(src any, dst any) error { destTestStruct.NestedDynamicStruct.Inner.IntVal = int64(sourceTestStruct.NestedDynamicStruct.Inner.I) destTestStruct.NestedDynamicStruct.FixedBytes = sourceTestStruct.NestedDynamicStruct.FixedBytes } - case reflect.TypeOf(src) == reflect.TypeOf(interfacetests.TestStruct{}) && reflect.TypeOf(dst) == reflect.TypeOf(&bindings.ReturnSeenInput{}): + case reflect.TypeOf(src) == reflect.TypeFor[interfacetests.TestStruct]() && reflect.TypeOf(dst) == reflect.TypeFor[*bindings.ReturnSeenInput](): destTestStruct := dst.(*bindings.ReturnSeenInput) if destTestStruct != nil { sourceTestStruct := src.(interfacetests.TestStruct) @@ -520,10 +520,10 @@ func createDecoder(dst any) (*mapstructure.Decoder, error) { } func stringToByteArrayHook(from reflect.Type, to reflect.Type, data any) (any, error) { - if from.Kind() == reflect.String && to == reflect.TypeOf([]byte{}) { + if from.Kind() == reflect.String && to == reflect.TypeFor[[]byte]() { return evmcodec.EVMAddressModifier{}.DecodeAddress(data.(string)) } - if from == reflect.TypeOf([]byte{}) && to.Kind() == reflect.String { + if from == reflect.TypeFor[[]byte]() && to.Kind() == reflect.String { return evmcodec.EVMAddressModifier{}.EncodeAddress(data.([]byte)) } return data, nil diff --git a/core/services/ring/plugin_test.go b/core/services/ring/plugin_test.go index 414c46aa2bb..bc7a7f14ce0 100644 --- a/core/services/ring/plugin_test.go +++ b/core/services/ring/plugin_test.go @@ -468,7 +468,7 @@ func TestPlugin_NoHealthyShardsFallbackToShardZero(t *testing.T) { // The pending allocation "workflow-123" should be included in observation now := time.Now() aos := make([]types.AttributedObservation, 3) - for i := 0; i < 3; i++ { + for i := range 3 { pbObs := &ringpb.Observation{ ShardStatus: toShardStatus(map[uint32]bool{0: false, 1: false, 2: false}), WorkflowIds: []string{"workflow-123"}, diff --git a/core/services/ring/store.go b/core/services/ring/store.go index ca9109097b4..c91a6b08cf0 100644 --- a/core/services/ring/store.go +++ b/core/services/ring/store.go @@ -197,9 +197,7 @@ func (s *Store) SetShardHealth(shardID uint32, healthy bool) { func (s *Store) SetAllShardHealth(health map[uint32]bool) { s.mu.Lock() s.shardHealth = make(map[uint32]bool) - for k, v := range health { - s.shardHealth[k] = v - } + maps.Copy(s.shardHealth, health) // Uninitialized store must wait for OCR consensus before serving requests if s.currentState == nil { diff --git a/core/services/ring/store_test.go b/core/services/ring/store_test.go index b36014bce91..8aee83171be 100644 --- a/core/services/ring/store_test.go +++ b/core/services/ring/store_test.go @@ -145,7 +145,7 @@ func TestStore_DistributionAcrossShards(t *testing.T) { // Generate many workflows and check distribution totalWorkflows := 100 distribution := make(map[uint32]int) - for i := 0; i < totalWorkflows; i++ { + for i := range totalWorkflows { wfID := "workflow-" + string(rune(i)) shard, err := store.GetShardForWorkflow(ctx, wfID) require.NoError(t, err) @@ -226,7 +226,7 @@ func TestStore_GetShardForWorkflow_ContextCancelledDuringSend(t *testing.T) { }) // Fill up the allocRequests channel - for i := 0; i < AllocationRequestChannelCapacity; i++ { + for range AllocationRequestChannelCapacity { store.allocRequests <- AllocationRequest{WorkflowID: "filler"} } diff --git a/core/services/shardorchestrator/shard_orchestrator.go b/core/services/shardorchestrator/shard_orchestrator.go index 4cda14a3b54..c9b41016a66 100644 --- a/core/services/shardorchestrator/shard_orchestrator.go +++ b/core/services/shardorchestrator/shard_orchestrator.go @@ -60,11 +60,9 @@ func (o *orchestrator) Start(ctx context.Context) error { o.lggr.Infow("Starting ShardOrchestrator service", "grpcAddr", o.grpcAddr) // Start gRPC server in a goroutine - o.wg.Add(1) - go func() { - defer o.wg.Done() + o.wg.Go(func() { o.runGRPCServer(ctx) - }() + }) o.lggr.Infow("ShardOrchestrator service started", "grpcAddr", o.grpcAddr) return nil diff --git a/core/services/standardcapabilities/standard_capabilities.go b/core/services/standardcapabilities/standard_capabilities.go index 3d7e7f8032c..d84fd7e3b38 100644 --- a/core/services/standardcapabilities/standard_capabilities.go +++ b/core/services/standardcapabilities/standard_capabilities.go @@ -102,9 +102,7 @@ func (s *StandardCapabilities) Start(ctx context.Context) error { return fmt.Errorf("error starting standard capabilities service: %w", err) } - s.wg.Add(1) - go func() { - defer s.wg.Done() + s.wg.Go(func() { defer close(s.readyChan) if s.startTimeout == 0 { @@ -144,7 +142,7 @@ func (s *StandardCapabilities) Start(ctx context.Context) error { } s.log.Info("Started standard capabilities", "command", s.command, "capabilities", capabilityInfos) - }() + }) return nil }) diff --git a/core/services/streams/delegate_test.go b/core/services/streams/delegate_test.go index 4d14c31b11b..63de50d845e 100644 --- a/core/services/streams/delegate_test.go +++ b/core/services/streams/delegate_test.go @@ -39,7 +39,7 @@ func Test_Delegate(t *testing.T) { _, err := d.ServicesForSpec(testutils.Context(t), jb) require.NoError(t, err) }) - jb.StreamID = ptr(uint32(42)) + jb.StreamID = new(uint32(42)) t.Run("returns services", func(t *testing.T) { srvs, err := d.ServicesForSpec(testutils.Context(t), jb) require.NoError(t, err) @@ -179,4 +179,3 @@ answer1 [type=median index=0]; }) } } -func ptr[T any](t T) *T { return &t } diff --git a/core/services/streams/stream_registry_test.go b/core/services/streams/stream_registry_test.go index e20b29e9262..4e7d0798f8f 100644 --- a/core/services/streams/stream_registry_test.go +++ b/core/services/streams/stream_registry_test.go @@ -99,7 +99,7 @@ result1 [type=memo value="900.0022"]; require.EqualError(t, err, "cannot register job with ID: 100; it is already registered") // errors when attempt to register a new job with duplicates stream IDs within ig - err = sr.Register(job.Job{ID: 101, StreamID: ptr(StreamID(100)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` + err = sr.Register(job.Job{ID: 101, StreamID: new(StreamID(100)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` result1 [type=memo value="900.0022" streamID=100]; `}}, nil) require.EqualError(t, err, "cannot register job with ID: 101; invalid stream IDs: duplicate stream ID: 100") @@ -110,7 +110,7 @@ result1 [type=memo value="900.0022" streamID=100]; require.EqualError(t, err, "cannot register job with ID: 101; unparseable pipeline: UnmarshalTaskFromMap: unknown task type: \"\"") // errors when attempt to re-register a stream with an existing streamID at top-level - err = sr.Register(job.Job{ID: 101, StreamID: ptr(StreamID(3)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` + err = sr.Register(job.Job{ID: 101, StreamID: new(StreamID(3)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` result1 [type=memo value="900.0022"]; multiply2 [type=multiply times=1 streamID=4 index=0]; // force conversion to decimal result2 [type=bridge name="foo-bridge" requestData="{\"data\":{\"data\":\"foo\"}}"]; @@ -126,7 +126,7 @@ result3 -> result3_parse -> multiply3; require.EqualError(t, err, "cannot register job with ID: 101; stream id 3 is already registered") // errors when attempt to re-register a stream with an existing streamID in DAG - err = sr.Register(job.Job{ID: 101, StreamID: ptr(StreamID(4)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` + err = sr.Register(job.Job{ID: 101, StreamID: new(StreamID(4)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` result1 [type=memo value="900.0022"]; multiply2 [type=multiply times=1 streamID=1 index=0]; // force conversion to decimal result2 [type=bridge name="foo-bridge" requestData="{\"data\":{\"data\":\"foo\"}}"]; @@ -142,7 +142,7 @@ result3 -> result3_parse -> multiply3; require.EqualError(t, err, "cannot register job with ID: 101; stream id 1 is already registered") // registers new job with all new stream IDs - err = sr.Register(job.Job{ID: 101, StreamID: ptr(StreamID(4)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` + err = sr.Register(job.Job{ID: 101, StreamID: new(StreamID(4)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` result1 [type=memo value="900.0022"]; multiply2 [type=multiply times=1 streamID=5 index=0]; // force conversion to decimal result2 [type=bridge name="foo-bridge" requestData="{\"data\":{\"data\":\"foo\"}}"]; @@ -182,7 +182,7 @@ result3 -> result3_parse -> multiply3; t.Run("Unregister", func(t *testing.T) { sr := newRegistry(lggr, runner) - err := sr.Register(job.Job{ID: 100, StreamID: ptr(StreamID(1)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` + err := sr.Register(job.Job{ID: 100, StreamID: new(StreamID(1)), Type: job.Stream, PipelineSpec: &pipeline.Spec{ID: 33, DotDagSource: ` result1 [type=memo value="900.0022" streamID=2]; `}}, nil) require.NoError(t, err) diff --git a/core/services/streams/stream_test.go b/core/services/streams/stream_test.go index 48b762d7ca9..4312e3bf2d9 100644 --- a/core/services/streams/stream_test.go +++ b/core/services/streams/stream_test.go @@ -62,12 +62,12 @@ func Test_Stream(t *testing.T) { ctx := testutils.Context(t) t.Run("errors with empty pipeline", func(t *testing.T) { - jbInvalid := job.Job{StreamID: ptr(StreamID(123)), PipelineSpec: &pipeline.Spec{DotDagSource: ``}} + jbInvalid := job.Job{StreamID: new(StreamID(123)), PipelineSpec: &pipeline.Spec{DotDagSource: ``}} _, err := newMultiStreamPipeline(lggr, jbInvalid, runner, nil) require.EqualError(t, err, "unparseable pipeline: empty pipeline") }) - jb := job.Job{StreamID: ptr(StreamID(123)), PipelineSpec: &pipeline.Spec{DotDagSource: ` + jb := job.Job{StreamID: new(StreamID(123)), PipelineSpec: &pipeline.Spec{DotDagSource: ` succeed [type=memo value=42 streamID=124]; succeed; `}} diff --git a/core/services/synchronization/chip_ingress_batch_client_test.go b/core/services/synchronization/chip_ingress_batch_client_test.go index 3c982e6574e..3be9babeae1 100644 --- a/core/services/synchronization/chip_ingress_batch_client_test.go +++ b/core/services/synchronization/chip_ingress_batch_client_test.go @@ -125,7 +125,7 @@ func TestChipIngressBatchClient_MultipleBatches(t *testing.T) { testCtx := testutils.Context(t) // Send multiple messages to trigger multiple batches - for i := 0; i < 10; i++ { + for i := range 10 { chipIngressClient.Send(testCtx, telemPayload) if i%3 == 0 { time.Sleep(sendInterval * 2) // Allow batch to be sent @@ -246,7 +246,7 @@ func TestChipIngressBatchClient_WorkerReuse(t *testing.T) { testCtx := testutils.Context(t) // Send multiple messages with same contract and type - should reuse worker - for i := 0; i < 5; i++ { + for range 5 { chipIngressClient.Send(testCtx, telemPayload) } diff --git a/core/services/synchronization/chip_ingress_batch_worker_test.go b/core/services/synchronization/chip_ingress_batch_worker_test.go index 2825877cb8e..8dc68ad5fbd 100644 --- a/core/services/synchronization/chip_ingress_batch_worker_test.go +++ b/core/services/synchronization/chip_ingress_batch_worker_test.go @@ -72,7 +72,7 @@ func TestChipIngressBatchWorker_BuildCloudEventBatch(t *testing.T) { } // enqueue more payloads than maxBatchSize to ensure batching occurs - for i := 0; i < 5; i++ { + for range 5 { chTelemetry <- payload } diff --git a/core/services/telemetry/chip_ingress_test.go b/core/services/telemetry/chip_ingress_test.go index 6470a21956d..47086556ac0 100644 --- a/core/services/telemetry/chip_ingress_test.go +++ b/core/services/telemetry/chip_ingress_test.go @@ -437,7 +437,7 @@ func TestChipIngressAgent_InterfaceCompliance(t *testing.T) { require.NoError(t, err) // Verify it can be assigned to the interface - var _ interface{} = adapter + var _ any = adapter // Call the interface method mockTelemService.On("Send", mock.Anything, mock.Anything) diff --git a/core/utils/finite_ticker.go b/core/utils/finite_ticker.go index d1e437f08f1..bb2eee948f0 100644 --- a/core/utils/finite_ticker.go +++ b/core/utils/finite_ticker.go @@ -10,10 +10,8 @@ func FiniteTicker(period time.Duration, onTick func()) func() { tick := time.NewTicker(period) chStop := make(chan struct{}) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { select { case <-tick.C: @@ -22,7 +20,7 @@ func FiniteTicker(period time.Duration, onTick func()) func() { return } } - }() + }) // NOTE: tick.Stop does not close the ticker channel, // so we still need another way of returning (chStop). diff --git a/core/utils/utils.go b/core/utils/utils.go index a6abee89b44..003e8bfb7a0 100644 --- a/core/utils/utils.go +++ b/core/utils/utils.go @@ -6,11 +6,13 @@ import ( "context" "crypto/ed25519" "crypto/rand" + "crypto/sha3" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" + "hash" "math" mrand "math/rand" "slices" @@ -24,7 +26,6 @@ import ( pkgerrors "github.com/pkg/errors" "github.com/robfig/cron/v3" "golang.org/x/crypto/bcrypt" - "golang.org/x/crypto/sha3" ragep2ptypes "github.com/smartcontractkit/libocr/ragep2p/types" @@ -135,7 +136,7 @@ func CheckPasswordHash(password, hash string) bool { // Sha256 returns a hexadecimal encoded string of a hashed input func Sha256(in string) (string, error) { - hasher := sha3.New256() + hasher := hash.Hash(sha3.New256()) _, err := hasher.Write([]byte(in)) if err != nil { return "", pkgerrors.Wrap(err, "sha256 write error") diff --git a/core/web/chains_controller_test.go b/core/web/chains_controller_test.go index 93c78a2f6be..ea2f383b646 100644 --- a/core/web/chains_controller_test.go +++ b/core/web/chains_controller_test.go @@ -39,17 +39,17 @@ func Test_EVMChainsController_Show(t *testing.T) { name: "success", want: &toml.EVMConfig{ ChainID: validID, - Enabled: ptr(true), + Enabled: new(true), Chain: toml.Defaults(nil, &toml.Chain{ GasEstimator: toml.GasEstimator{ - EIP1559DynamicFees: ptr(true), + EIP1559DynamicFees: new(true), BlockHistory: toml.BlockHistoryEstimator{ - BlockHistorySize: ptr[uint16](50), + BlockHistorySize: new(uint16(50)), }, }, - RPCBlockQueryDelay: ptr[uint16](23), - MinIncomingConfirmations: ptr[uint32](12), - LinkContractAddress: ptr(types.EIP55AddressFromAddress(testutils.NewAddress())), + RPCBlockQueryDelay: new(uint16(23)), + MinIncomingConfirmations: new(uint32(12)), + LinkContractAddress: new(types.EIP55AddressFromAddress(testutils.NewAddress())), }), }, wantStatusCode: http.StatusOK, @@ -115,27 +115,27 @@ func Test_EVMChainsController_Index(t *testing.T) { { ChainID: sqlutil.New(chainIDs[1]), Chain: toml.Defaults(nil, &toml.Chain{ - RPCBlockQueryDelay: ptr[uint16](13), + RPCBlockQueryDelay: new(uint16(13)), GasEstimator: toml.GasEstimator{ - EIP1559DynamicFees: ptr(true), + EIP1559DynamicFees: new(true), BlockHistory: toml.BlockHistoryEstimator{ - BlockHistorySize: ptr[uint16](1), + BlockHistorySize: new(uint16(1)), }, }, - MinIncomingConfirmations: ptr[uint32](120), + MinIncomingConfirmations: new(uint32(120)), }), }, { ChainID: sqlutil.New(chainIDs[2]), Chain: toml.Defaults(nil, &toml.Chain{ - RPCBlockQueryDelay: ptr[uint16](5), + RPCBlockQueryDelay: new(uint16(5)), GasEstimator: toml.GasEstimator{ - EIP1559DynamicFees: ptr(false), + EIP1559DynamicFees: new(false), BlockHistory: toml.BlockHistoryEstimator{ - BlockHistorySize: ptr[uint16](2), + BlockHistorySize: new(uint16(2)), }, }, - MinIncomingConfirmations: ptr[uint32](30), + MinIncomingConfirmations: new(uint32(30)), }), }, } @@ -221,4 +221,5 @@ func setupEVMChainsControllerTest(t *testing.T, cfg chainlink.GeneralConfig) *Te } } -func ptr[T any](t T) *T { return &t } +//go:fix inline +func ptr[T any](t T) *T { return new(t) } diff --git a/core/web/cors_test.go b/core/web/cors_test.go index c08e11bc125..d4e837bd336 100644 --- a/core/web/cors_test.go +++ b/core/web/cors_test.go @@ -13,7 +13,7 @@ func TestCors_DefaultOrigins(t *testing.T) { t.Parallel() config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.WebServer.AllowOrigins = ptr("http://localhost:3000,http://localhost:6689") + c.WebServer.AllowOrigins = new("http://localhost:3000,http://localhost:6689") }) tests := []struct { @@ -56,7 +56,7 @@ func TestCors_OverrideOrigins(t *testing.T) { for _, test := range tests { t.Run(test.origin, func(t *testing.T) { config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.WebServer.AllowOrigins = ptr(test.allow) + c.WebServer.AllowOrigins = new(test.allow) }) app := cltest.NewApplicationWithConfig(t, config) diff --git a/core/web/eth_keys_controller_test.go b/core/web/eth_keys_controller_test.go index a898d12d2dd..1eadf390f0d 100644 --- a/core/web/eth_keys_controller_test.go +++ b/core/web/eth_keys_controller_test.go @@ -32,8 +32,8 @@ func TestETHKeysController_Index_Success(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -82,8 +82,8 @@ func TestETHKeysController_Index_Errors(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -119,7 +119,7 @@ func TestETHKeysController_Index_Disabled(t *testing.T) { ethClient := cltest.NewEthMocksWithStartupAssertions(t) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].Enabled = ptr(false) + c.EVM[0].Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -152,9 +152,9 @@ func TestETHKeysController_Index_NotDev(t *testing.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) - c.EVM[0].GasEstimator.Mode = ptr("FixedPrice") + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) + c.EVM[0].GasEstimator.Mode = new("FixedPrice") }) ethClient.On("BalanceAt", mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(256), nil).Once() @@ -205,7 +205,7 @@ func TestETHKeysController_CreateSuccess(t *testing.T) { t.Parallel() config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) ethClient := clienttest.NewClientWithDefaultChainID(t) app := cltest.NewApplicationWithConfigAndKey(t, config, ethClient) @@ -248,8 +248,8 @@ func TestETHKeysController_ChainSuccess_UpdateNonce(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) @@ -289,8 +289,8 @@ func TestETHKeysController_ChainSuccess_Disable(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -333,8 +333,8 @@ func TestETHKeysController_ChainSuccess_Enable(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -378,8 +378,8 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Maybe() cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -450,8 +450,8 @@ func TestETHKeysController_ChainFailure_InvalidAbandon(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -483,8 +483,8 @@ func TestETHKeysController_ChainFailure_InvalidEnabled(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -516,8 +516,8 @@ func TestETHKeysController_ChainFailure_InvalidAddress(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -545,8 +545,8 @@ func TestETHKeysController_ChainFailure_MissingAddress(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -574,8 +574,8 @@ func TestETHKeysController_ChainFailure_InvalidChainID(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -603,8 +603,8 @@ func TestETHKeysController_ChainFailure_MissingChainID(t *testing.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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) @@ -634,8 +634,8 @@ func TestETHKeysController_DeleteSuccess(t *testing.T) { 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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) @@ -684,8 +684,8 @@ func TestETHKeysController_DeleteFailure_InvalidAddress(t *testing.T) { 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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) @@ -706,8 +706,8 @@ func TestETHKeysController_DeleteFailure_KeyMissing(t *testing.T) { 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) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfig(t, cfg, ethClient) require.NoError(t, app.KeyStore.Unlock(ctx, cltest.Password)) diff --git a/core/web/evm_forwarders_controller_test.go b/core/web/evm_forwarders_controller_test.go index 36b48ee6968..2441d8b1f43 100644 --- a/core/web/evm_forwarders_controller_test.go +++ b/core/web/evm_forwarders_controller_test.go @@ -48,7 +48,7 @@ func Test_EVMForwardersController_Track(t *testing.T) { chainId := sqlutil.New(testutils.NewRandomEVMChainID()) controller := setupEVMForwardersControllerTest(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM = toml.EVMConfigs{ - {ChainID: chainId, Enabled: ptr(true), Chain: toml.Defaults(chainId)}, + {ChainID: chainId, Enabled: new(true), Chain: toml.Defaults(chainId)}, } }) @@ -85,7 +85,7 @@ func Test_EVMForwardersController_Index(t *testing.T) { chainId := sqlutil.New(testutils.NewRandomEVMChainID()) controller := setupEVMForwardersControllerTest(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.EVM = toml.EVMConfigs{ - {ChainID: chainId, Enabled: ptr(true), Chain: toml.Defaults(chainId)}, + {ChainID: chainId, Enabled: new(true), Chain: toml.Defaults(chainId)}, } }) diff --git a/core/web/evm_transfer_controller_test.go b/core/web/evm_transfer_controller_test.go index 677588c2100..44ecfb255a1 100644 --- a/core/web/evm_transfer_controller_test.go +++ b/core/web/evm_transfer_controller_test.go @@ -247,7 +247,7 @@ func TestTransfersController_CreateSuccess_From_BalanceMonitorDisabled(t *testin ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil).Once() config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfigAndKey(t, config, ethClient, key) @@ -409,8 +409,8 @@ func TestTransfersController_CreateSuccess_eip1559(t *testing.T) { ethClient.On("NonceAt", mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil) config := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.EVM[0].GasEstimator.EIP1559DynamicFees = ptr(true) - c.EVM[0].GasEstimator.Mode = ptr("FixedPrice") + c.EVM[0].GasEstimator.EIP1559DynamicFees = new(true) + c.EVM[0].GasEstimator.Mode = new("FixedPrice") c.EVM[0].ChainID = (*sqlutil.Big)(testutils.FixtureChainID) // NOTE: FallbackPollInterval is used in this test to quickly create TxAttempts // Testing triggers requires committing transactions and does not work with transactional tests diff --git a/core/web/external_initiators_controller_test.go b/core/web/external_initiators_controller_test.go index 384fd3a3fd7..6513ce40027 100644 --- a/core/web/external_initiators_controller_test.go +++ b/core/web/external_initiators_controller_test.go @@ -69,7 +69,7 @@ func TestExternalInitiatorsController_Index(t *testing.T) { app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) })) require.NoError(t, app.Start(testutils.Context(t))) @@ -135,7 +135,7 @@ func TestExternalInitiatorsController_Create_success(t *testing.T) { app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) })) require.NoError(t, app.Start(testutils.Context(t))) @@ -162,7 +162,7 @@ func TestExternalInitiatorsController_Create_without_URL(t *testing.T) { app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) })) require.NoError(t, app.Start(testutils.Context(t))) @@ -189,7 +189,7 @@ func TestExternalInitiatorsController_Create_invalid(t *testing.T) { app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) })) require.NoError(t, app.Start(testutils.Context(t))) @@ -207,7 +207,7 @@ func TestExternalInitiatorsController_Delete(t *testing.T) { app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) })) require.NoError(t, app.Start(testutils.Context(t))) @@ -229,7 +229,7 @@ func TestExternalInitiatorsController_DeleteNotFound(t *testing.T) { app := cltest.NewApplicationWithConfig(t, configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.JobPipeline.ExternalInitiatorsEnabled = ptr(true) + c.JobPipeline.ExternalInitiatorsEnabled = new(true) })) require.NoError(t, app.Start(testutils.Context(t))) diff --git a/core/web/jobs_controller_test.go b/core/web/jobs_controller_test.go index 7ce8f6a3228..2c0e8b07b56 100644 --- a/core/web/jobs_controller_test.go +++ b/core/web/jobs_controller_test.go @@ -491,8 +491,8 @@ 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) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID }) @@ -557,8 +557,8 @@ func TestJobsController_Update_HappyPath(t *testing.T) { func TestJobsController_Update_NonExistentID(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) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID }) @@ -635,8 +635,8 @@ func setupBridges(t *testing.T, ds sqlutil.DataSource) (b1, b2 string) { func setupJobsControllerTests(t *testing.T) (ta *cltest.TestApplication, cc cltest.HTTPClientCleaner) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.OCR.Enabled = ptr(true) - c.P2P.V2.Enabled = ptr(true) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID }) @@ -670,8 +670,8 @@ func setupEthClientForControllerTests(t *testing.T) *clienttest.Client { func setupJobSpecsControllerTestsWithJobs(t *testing.T) (*cltest.TestApplication, cltest.HTTPClientCleaner, job.Job, int32, job.Job, int32) { 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) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID }) diff --git a/core/web/log_controller_test.go b/core/web/log_controller_test.go index 53900297c6d..fee067f130f 100644 --- a/core/web/log_controller_test.go +++ b/core/web/log_controller_test.go @@ -35,7 +35,7 @@ func TestLogController_GetLogConfig(t *testing.T) { cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { c.Log.Level = ptr(toml.LogLevel(zapcore.WarnLevel)) - c.Database.LogQueries = ptr(true) + c.Database.LogQueries = new(true) }) app := cltest.NewApplicationWithConfig(t, cfg) diff --git a/core/web/loop_registry_test.go b/core/web/loop_registry_test.go index e8ae4c09459..0a0c52f3db0 100644 --- a/core/web/loop_registry_test.go +++ b/core/web/loop_registry_test.go @@ -60,8 +60,8 @@ 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) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID }) diff --git a/core/web/pipeline_runs_controller_test.go b/core/web/pipeline_runs_controller_test.go index 9676117c356..c6a31ee2e81 100644 --- a/core/web/pipeline_runs_controller_test.go +++ b/core/web/pipeline_runs_controller_test.go @@ -180,12 +180,12 @@ func setupPipelineRunsControllerTests(t *testing.T) (cltest.HTTPClientCleaner, i ethClient := cltest.NewEthMocksWithStartupAssertions(t) ethClient.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Maybe().Return(nil, nil) cfg := configtest.NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { - c.OCR.Enabled = ptr(true) - c.P2P.V2.Enabled = ptr(true) + c.OCR.Enabled = new(true) + c.P2P.V2.Enabled = new(true) c.P2P.V2.ListenAddresses = &[]string{fmt.Sprintf("127.0.0.1:%d", freeport.GetOne(t))} c.P2P.PeerID = &cltest.DefaultP2PPeerID - c.EVM[0].NonceAutoSync = ptr(false) - c.EVM[0].BalanceMonitor.Enabled = ptr(false) + c.EVM[0].NonceAutoSync = new(false) + c.EVM[0].BalanceMonitor.Enabled = new(false) }) app := cltest.NewApplicationWithConfigAndKey(t, cfg, ethClient, cltest.DefaultP2PKey) require.NoError(t, app.Start(ctx)) diff --git a/tools/ci-testshard/main_test.go b/tools/ci-testshard/main_test.go index 5f820d85ddb..3ee665ec6e6 100644 --- a/tools/ci-testshard/main_test.go +++ b/tools/ci-testshard/main_test.go @@ -53,7 +53,7 @@ func TestListReturnsPartitionWithoutOverlap(t *testing.T) { input := "pkg/a\npkg/b\npkg/c\npkg/d\n" seen := make(map[string]struct{}) - for shardIndex := 0; shardIndex < 4; shardIndex++ { + for shardIndex := range 4 { packages := runListForTest(t, input, 4, shardIndex) for _, pkg := range packages { if _, exists := seen[pkg]; exists { @@ -96,7 +96,7 @@ func TestListProducesDeterministicOutput(t *testing.T) { func TestListCanProduceEmptyShard(t *testing.T) { input := "pkg/a\npkg/b\n" foundEmpty := false - for shardIndex := 0; shardIndex < 10; shardIndex++ { + for shardIndex := range 10 { if output := runListOutputForTest(t, input, 10, shardIndex); output == "" { foundEmpty = true break @@ -119,7 +119,7 @@ func TestListAndVerifyAgreeOnPartition(t *testing.T) { input := strings.Join(inputPackages, "\n") + "\n" seen := make(map[string]struct{}, len(inputPackages)) - for shardIndex := 0; shardIndex < 4; shardIndex++ { + for shardIndex := range 4 { for _, pkg := range runListForTest(t, input, 4, shardIndex) { if _, exists := seen[pkg]; exists { t.Fatalf("package %s appeared in multiple shards", pkg) @@ -232,7 +232,7 @@ func TestExtraPositionalArgsFail(t *testing.T) { func TestLargePackageListParses(t *testing.T) { var builder strings.Builder - for i := 0; i < 500; i++ { + for i := range 500 { fmt.Fprintf(&builder, "pkg/%03d\n", i) } diff --git a/tools/plugout/main.go b/tools/plugout/main.go index ce9de884522..67768ea7508 100644 --- a/tools/plugout/main.go +++ b/tools/plugout/main.go @@ -9,6 +9,7 @@ import ( "os/exec" "path/filepath" "regexp" + "slices" "sort" "strings" @@ -234,12 +235,7 @@ func discoverPluginVersions(path string) (map[string]string, error) { } func contains(slice []string, item string) bool { - for _, v := range slice { - if v == item { - return true - } - } - return false + return slices.Contains(slice, item) } // moduleSubdir returns the path within the repo after the "host/org/repo" prefix.