diff --git a/core/capabilities/localcapmgr/offchain_cutover_test.go b/core/capabilities/localcapmgr/offchain_cutover_test.go index b8f5183e5be..49acabdc88b 100644 --- a/core/capabilities/localcapmgr/offchain_cutover_test.go +++ b/core/capabilities/localcapmgr/offchain_cutover_test.go @@ -226,6 +226,25 @@ func TestReconcile_EffectiveSpecConfigPrecedence(t *testing.T) { })) assert.Empty(t, rec.all()) }) + + t.Run("gate on: capability only in the offchain payload is not launched", func(t *testing.T) { + t.Parallel() + // The payload configures consensus on DON 7, but the on-chain registry only has cron there. + // The on-chain registry (plus the allowlist) decides what runs; the payload supplies config. + gc := globalconfig.New() + storeOffchain(t, gc, 1, map[uint32]map[string]*capabilitiespb.CapabilityConfig{ + 7: { + "cron@1.0.0": specConfigCap(t, map[string]any{"interval": "30"}), + "consensus@1.0.0": specConfigCap(t, map[string]any{"k": "v"}), + }, + }) + m, rec := newCutoverManager(t, localCfg(), gc, true) + require.NoError(t, m.reconcile(t.Context(), []registry.DON{ + onchainDONWith(7, map[string]registry.CapabilityConfiguration{"cron@1.0.0": onchain}), + })) + assert.Equal(t, map[string]any{"interval": "30"}, rec.configFor(t, "cron@1.0.0", 7)) + assert.Len(t, rec.all(), 1) + }) } // TestReconcile_OCR3StaysOnchain asserts that with the gate on, the OCR3 config handed to the diff --git a/core/services/standardcapabilities/delegate.go b/core/services/standardcapabilities/delegate.go index 8b23fd6cf96..fbd94677383 100644 --- a/core/services/standardcapabilities/delegate.go +++ b/core/services/standardcapabilities/delegate.go @@ -3,9 +3,11 @@ package standardcapabilities import ( "context" "crypto" + "encoding/json" "fmt" "path/filepath" "strconv" + "strings" "time" "github.com/google/uuid" @@ -311,6 +313,13 @@ func (d *Delegate) NewServices( } } + // Registry-launched EVM capabilities share one spec_config across the DON, so the per-node + // nodeAddress monitoring label is filled in here from this node's OCR3 transmitter. + configJSON, err = withEVMNodeAddress(configJSON, capabilityID, transmitter) + if err != nil { + return nil, fmt.Errorf("failed to set EVM nodeAddress: %w", err) + } + // Always resolve the oracle factory config to fill in any missing fields // (contract address, chain ID, key bundle, transmitter, signing strategy). // Job spec values take precedence; empty fields are resolved from the @@ -413,6 +422,38 @@ func (d *Delegate) NewServices( return []job.ServiceCtx{standardCapability}, nil } +// withEVMNodeAddress sets "nodeAddress" in an EVM capability's config JSON to transmitter when the +// config does not already provide one. It is a no-op for other capabilities, an empty transmitter, +// empty config, or an explicitly configured nodeAddress. Other keys are preserved untouched. +func withEVMNodeAddress(configJSON, capabilityID, transmitter string) (string, error) { + const key = "nodeAddress" + if !strings.HasPrefix(capabilityID, "evm:") || transmitter == "" { + return configJSON, nil + } + + cfg := map[string]json.RawMessage{} + if strings.TrimSpace(configJSON) != "" { + if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil { + return "", fmt.Errorf("config is not a JSON object: %w", err) + } + } + var existing string + if raw, ok := cfg[key]; ok && json.Unmarshal(raw, &existing) == nil && existing != "" { + return configJSON, nil + } + + addr, err := json.Marshal(transmitter) + if err != nil { + return "", err + } + cfg[key] = addr + out, err := json.Marshal(cfg) + if err != nil { + return "", err + } + return string(out), nil +} + func (d *Delegate) newServicesV2(ctx context.Context, log logger.Logger, command, app, configJSON string, capabilityDonID uint32) ([]job.ServiceCtx, error) { // The capability ID depends on the capability, not on how it runs, so look it up by app name. capabilityID := conversions.GetCapabilityIDFromCommand(app, configJSON) diff --git a/core/services/standardcapabilities/delegate_test.go b/core/services/standardcapabilities/delegate_test.go index 09b6475a8a9..b69ab3fe3ea 100644 --- a/core/services/standardcapabilities/delegate_test.go +++ b/core/services/standardcapabilities/delegate_test.go @@ -345,3 +345,48 @@ func (s *stubLocalCapabilities) RegistryBasedLaunchAllowlist() []string { return func (s *stubLocalCapabilities) IsAllowlisted(capabilityID string) bool { return s.allowlisted[capabilityID] } + +func TestWithEVMNodeAddress(t *testing.T) { + t.Parallel() + const evmID = "evm:ChainSelector:1@1.0.0" + + t.Run("fills nodeAddress when absent and keeps other keys", func(t *testing.T) { + t.Parallel() + out, err := withEVMNodeAddress(`{"chainId":1337,"network":"evm"}`, evmID, "0xabc") + require.NoError(t, err) + assert.JSONEq(t, `{"chainId":1337,"network":"evm","nodeAddress":"0xabc"}`, out) + }) + t.Run("fills nodeAddress when empty", func(t *testing.T) { + t.Parallel() + out, err := withEVMNodeAddress(`{"nodeAddress":""}`, evmID, "0xabc") + require.NoError(t, err) + assert.JSONEq(t, `{"nodeAddress":"0xabc"}`, out) + }) + t.Run("keeps configured nodeAddress", func(t *testing.T) { + t.Parallel() + in := `{"nodeAddress":"0xconfigured"}` + out, err := withEVMNodeAddress(in, evmID, "0xabc") + require.NoError(t, err) + assert.Equal(t, in, out) + }) + t.Run("empty config becomes an object", func(t *testing.T) { + t.Parallel() + out, err := withEVMNodeAddress("", evmID, "0xabc") + require.NoError(t, err) + assert.JSONEq(t, `{"nodeAddress":"0xabc"}`, out) + }) + t.Run("no-op for non-EVM capabilities and empty transmitter", func(t *testing.T) { + t.Parallel() + out, err := withEVMNodeAddress(`{"a":1}`, "aptos:ChainSelector:1@1.0.0", "0xabc") + require.NoError(t, err) + assert.Equal(t, `{"a":1}`, out) + out, err = withEVMNodeAddress(`{"a":1}`, evmID, "") + require.NoError(t, err) + assert.Equal(t, `{"a":1}`, out) + }) + t.Run("rejects non-object config", func(t *testing.T) { + t.Parallel() + _, err := withEVMNodeAddress(`[1]`, evmID, "0xabc") + require.Error(t, err) + }) +} diff --git a/system-tests/lib/cre/don/config/config.go b/system-tests/lib/cre/don/config/config.go index 6ccf8c0805b..9a96eef6a8f 100644 --- a/system-tests/lib/cre/don/config/config.go +++ b/system-tests/lib/cre/don/config/config.go @@ -5,6 +5,7 @@ import ( "fmt" "maps" "math/big" + "regexp" "slices" "strconv" "strings" @@ -31,6 +32,7 @@ import ( aptoschain "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains/aptos" "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains/solana" stellchain "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains/stellar" + "github.com/smartcontractkit/chainlink/system-tests/lib/cre/flags" "github.com/smartcontractkit/chainlink/system-tests/lib/infra" coretoml "github.com/smartcontractkit/chainlink/v2/core/config/toml" corechainlink "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" @@ -475,6 +477,13 @@ func addWorkerNodeConfig( } } + // EVM, Aptos and Stellar chain capabilities are launched from their registry spec_config, not job specs. + for _, id := range chainCapabilityAllowlistEntries(donMetadata, commonInputs) { + if !slices.Contains(existingConfig.Capabilities.Local.RegistryBasedLaunchAllowlist, id) { + existingConfig.Capabilities.Local.RegistryBasedLaunchAllowlist = append(existingConfig.Capabilities.Local.RegistryBasedLaunchAllowlist, id) + } + } + for _, evmChain := range commonInputs.evmChains { appendEVMChain(&existingConfig.EVM, evmChain) } @@ -666,8 +675,9 @@ type versionedAddress struct { } type aptosChain struct { - ChainID string - NodeURL string + ChainID string + ChainSelector uint64 + NodeURL string } type commonInputs struct { @@ -800,9 +810,10 @@ func findOneSolanaChain(input cre.GenerateConfigsInput) (*solanaChain, error) { const stellarMaxResourceFeeStroops = int64(10_000_000) type stellarChain struct { - Name string - ChainID string - NodeURL string + Name string + ChainID string + ChainSelector uint64 + NodeURL string } func findOneStellarChain(input cre.GenerateConfigsInput) (*stellarChain, error) { @@ -830,15 +841,49 @@ func findOneStellarChain(input cre.GenerateConfigsInput) (*stellarChain, error) } stChain = &stellarChain{ - Name: fmt.Sprintf("node-%d", stBc.ChainSelector()), - ChainID: stBc.StellarChainID(), // string network id with a corresponding chain selector - NodeURL: nodeURL, + Name: fmt.Sprintf("node-%d", stBc.ChainSelector()), + ChainID: stBc.StellarChainID(), // string network id with a corresponding chain selector + ChainSelector: stBc.ChainSelector(), + NodeURL: nodeURL, } } return stChain, nil } +// chainCapabilityAllowlistEntries returns the RegistryBasedLaunchAllowlist patterns for the chain +// capabilities enabled on the DON. EVM is allowlisted by family; Aptos and Stellar per chain. +// Solana stays on job specs. +func chainCapabilityAllowlistEntries(donMetadata *cre.DonMetadata, inputs *commonInputs) []string { + entries := make([]string, 0) + + for _, evmChain := range inputs.evmChains { + if flags.HasFlagForChain(donMetadata.Flags, cre.EVMCapability, evmChain.ChainID) { + entries = append(entries, "^evm:ChainSelector:") + break + } + } + + for _, ac := range inputs.aptosChains { + chainID, err := strconv.ParseUint(ac.ChainID, 10, 64) + if err != nil || !flags.HasFlagForChain(donMetadata.Flags, cre.AptosCapability, chainID) { + continue + } + entries = append(entries, exactCapabilityIDPattern("aptos:ChainSelector:"+strconv.FormatUint(ac.ChainSelector, 10)+"@1.0.0")) + } + + if donMetadata.HasFlag(cre.StellarCapability) && inputs.stellarChain != nil { + entries = append(entries, exactCapabilityIDPattern("stellar:ChainSelector:"+strconv.FormatUint(inputs.stellarChain.ChainSelector, 10)+"@1.0.0")) + } + + return entries +} + +// exactCapabilityIDPattern anchors a capability ID so the allowlist (a regex) matches only it. +func exactCapabilityIDPattern(id string) string { + return "^" + regexp.QuoteMeta(id) + "$" +} + func findAptosChains(input cre.GenerateConfigsInput) ([]*aptosChain, error) { capabilityChainIDs := input.DonMetadata.MustNodeSet().ChainCapabilityChainIDs() out := make([]*aptosChain, 0) @@ -860,8 +905,9 @@ func findAptosChains(input cre.GenerateConfigsInput) ([]*aptosChain, error) { } out = append(out, &aptosChain{ - ChainID: strconv.FormatUint(bcOut.ChainID(), 10), - NodeURL: nodeURL, + ChainID: strconv.FormatUint(bcOut.ChainID(), 10), + ChainSelector: aptosBC.ChainSelector(), + NodeURL: nodeURL, }) } return out, nil diff --git a/system-tests/lib/cre/don/config/config_test.go b/system-tests/lib/cre/don/config/config_test.go index 6ceb85892e2..e47f937cb1f 100644 --- a/system-tests/lib/cre/don/config/config_test.go +++ b/system-tests/lib/cre/don/config/config_test.go @@ -1,6 +1,7 @@ package config import ( + "regexp" "strconv" "testing" @@ -183,6 +184,72 @@ func TestAddWorkerNodeConfig_HTTPRegistryLaunch(t *testing.T) { assert.Len(t, config.Capabilities.Local.RegistryBasedLaunchAllowlist, 3) } +func TestAddWorkerNodeConfig_ChainCapabilitiesRegistryLaunch(t *testing.T) { + t.Parallel() + don := capabilitiesDonMetadata() + don.Flags = append(don.Flags, cre.EVMCapability+"-1337", cre.AptosCapability+"-4", cre.StellarCapability) + don.RegistryBasedLaunchAllowlist = []string{"cron-trigger@1.0.0"} + inputs := capabilitiesCommonInputs("chip-router:50051") + inputs.evmChains = []*evmChain{{Name: "evm", ChainID: 1337}, {Name: "evm-other", ChainID: 2337}} + inputs.aptosChains = []*aptosChain{ + {ChainID: "4", ChainSelector: 4457093679053095497}, + {ChainID: "8", ChainSelector: 999}, // chain without the capability enabled + } + inputs.stellarChain = &stellarChain{Name: "stellar", ChainID: "net", ChainSelector: 7777} + node := &cre.NodeMetadata{Index: 0, Roles: []string{cre.WorkerNode}} + + config, err := addWorkerNodeConfig(corechainlink.Config{}, nil, testPeeringData(), inputs, don, node) + require.NoError(t, err) + assert.Equal(t, []string{ + "cron-trigger@1.0.0", + "^evm:ChainSelector:", + `^aptos:ChainSelector:4457093679053095497@1\.0\.0$`, + `^stellar:ChainSelector:7777@1\.0\.0$`, + }, config.Capabilities.Local.RegistryBasedLaunchAllowlist) + + // Reapplying configuration must not duplicate registry launch entries. + config, err = addWorkerNodeConfig(config, nil, testPeeringData(), inputs, don, node) + require.NoError(t, err) + assert.Len(t, config.Capabilities.Local.RegistryBasedLaunchAllowlist, 4) +} + +func TestAddWorkerNodeConfig_ChainCapabilitiesNotAllowlistedWithoutFlags(t *testing.T) { + t.Parallel() + inputs := capabilitiesCommonInputs("chip-router:50051") + inputs.evmChains = []*evmChain{{Name: "evm", ChainID: 1337}} + inputs.aptosChains = []*aptosChain{{ChainID: "4", ChainSelector: 1}} + inputs.stellarChain = &stellarChain{Name: "stellar", ChainID: "net", ChainSelector: 2} + + config, err := addWorkerNodeConfig(corechainlink.Config{}, nil, testPeeringData(), inputs, capabilitiesDonMetadata(), &cre.NodeMetadata{Index: 0, Roles: []string{cre.WorkerNode}}) + require.NoError(t, err) + assert.Empty(t, config.Capabilities.Local.RegistryBasedLaunchAllowlist) +} + +func TestChainCapabilityAllowlistMatchesCapabilityIDs(t *testing.T) { + t.Parallel() + don := capabilitiesDonMetadata() + don.Flags = append(don.Flags, cre.EVMCapability+"-1337", cre.AptosCapability+"-4", cre.StellarCapability) + inputs := capabilitiesCommonInputs("chip-router:50051") + inputs.evmChains = []*evmChain{{ChainID: 1337}} + inputs.aptosChains = []*aptosChain{{ChainID: "4", ChainSelector: 11}} + inputs.stellarChain = &stellarChain{ChainSelector: 22} + + matches := func(id string) bool { + for _, p := range chainCapabilityAllowlistEntries(don, inputs) { + if regexp.MustCompile(p).MatchString(id) { + return true + } + } + return false + } + assert.True(t, matches("evm:ChainSelector:12345@1.0.0")) + assert.True(t, matches("aptos:ChainSelector:11@1.0.0")) + assert.True(t, matches("stellar:ChainSelector:22@1.0.0")) + assert.False(t, matches("aptos:ChainSelector:111@1.0.0"), "must not match another selector sharing a prefix") + assert.False(t, matches("aptos:ChainSelector:11@1.0.1")) + assert.False(t, matches("solana:ChainSelector:11@1.0.0"), "solana stays on job specs") +} + // TestAddWorkerNodeConfig_ConsensusQueueRegistryLaunch asserts a DON with the consensus-queue flag gets it on the // registry launch allowlist exactly once, next to the topology's own entries. func TestAddWorkerNodeConfig_ConsensusQueueRegistryLaunch(t *testing.T) { diff --git a/system-tests/lib/cre/features/aptos/aptos.go b/system-tests/lib/cre/features/aptos/aptos.go index 70f1d121578..5edfc2e7b23 100644 --- a/system-tests/lib/cre/features/aptos/aptos.go +++ b/system-tests/lib/cre/features/aptos/aptos.go @@ -4,11 +4,9 @@ import ( "context" "fmt" "strconv" - "strings" "time" "github.com/Masterminds/semver/v3" - pkgerrors "github.com/pkg/errors" "github.com/rs/zerolog" chainselectors "github.com/smartcontractkit/chain-selectors" @@ -19,7 +17,6 @@ import ( keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" "github.com/smartcontractkit/chainlink/system-tests/lib/cre" crecontracts "github.com/smartcontractkit/chainlink/system-tests/lib/cre/contracts" - crejobs "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs" creblockchains "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains" ) @@ -92,7 +89,7 @@ func (a *Aptos) PreEnvStartup( return nil, fmt.Errorf("failed to collect Aptos worker transmitters for DON %q from metadata: %w", don.Name, err) } - caps, capabilityToOCR3Config, capabilityLabels, err := buildCapabilityRegistrations(don, creEnv.Blockchains, enabledChainIDs, p2pToTransmitterMap) + caps, capabilityToOCR3Config, capabilityLabels, err := buildCapabilityRegistrations(don, creEnv.Blockchains, enabledChainIDs, p2pToTransmitterMap, forwardersByChainID) if err != nil { return nil, err } @@ -127,23 +124,9 @@ func (a *Aptos) PostEnvStartup( return nil } - err = configureForwarders(ctx, testLogger, don, creEnv, enabledChainIDs) - if err != nil { - return err - } - - specs, err := proposeAptosWorkerSpecs(ctx, don, dons, creEnv, nodeSet, enabledChainIDs) - if err != nil { - return err - } - if len(specs) == 0 { - return nil - } - err = crejobs.Approve(ctx, creEnv.CldfEnvironment.Offchain, dons, specs) - if err != nil { - return fmt.Errorf("failed to approve Aptos jobs: %w", err) - } - return nil + // The Aptos capability is launched by the node from its registry spec_config + // (see buildCapabilityRegistrations), so no worker job spec is proposed here. + return configureForwarders(ctx, testLogger, don, creEnv, enabledChainIDs) } func buildCapabilityRegistrations( @@ -151,6 +134,7 @@ func buildCapabilityRegistrations( blockchains []creblockchains.Blockchain, enabledChainIDs []uint64, p2pToTransmitterMap map[string]string, + forwardersByChainID map[uint64]string, ) ([]keystone_changeset.DONCapabilityWithConfig, map[string]*ocr3.OracleConfig, []string, error) { caps := make([]keystone_changeset.DONCapabilityWithConfig, 0, len(enabledChainIDs)) capabilityToOCR3Config := make(map[string]*ocr3.OracleConfig, len(enabledChainIDs)) @@ -171,6 +155,13 @@ func buildCapabilityRegistrations( if err != nil { return nil, nil, nil, fmt.Errorf("failed to build Aptos capability config for capability %s: %w", labelledName, err) } + forwarderAddress, ok := forwardersByChainID[chainID] + if !ok || forwarderAddress == "" { + return nil, nil, nil, fmt.Errorf("missing Aptos forwarder address for chain %d", chainID) + } + if err := setChainSpecConfig(capConfig, chainID, forwarderAddress, true); err != nil { + return nil, nil, nil, fmt.Errorf("failed to set Aptos chain spec config for capability %s: %w", labelledName, err) + } caps = append(caps, keystone_changeset.DONCapabilityWithConfig{ Capability: kcr.CapabilitiesRegistryCapability{ @@ -197,17 +188,6 @@ func nodeSetForDON(dons *cre.Dons, donName string) (cre.NodeSetWithCapabilityCon return nil, fmt.Errorf("could not find node set for Don named '%s'", donName) } -func bootstrapPeersForDons(dons *cre.Dons) ([]string, error) { - bootstrapNode, ok := dons.Bootstrap() - if !ok { - return nil, pkgerrors.New("bootstrap node not found; required for Aptos OCR bootstrap peers") - } - - return []string{ - fmt.Sprintf("%s@%s:%d", strings.TrimPrefix(bootstrapNode.Keys.PeerID(), "p2p_"), bootstrapNode.Host, cre.PeeringPort), - }, nil -} - var ( _ cre.Feature = (*Aptos)(nil) ) diff --git a/system-tests/lib/cre/features/aptos/aptos_config.go b/system-tests/lib/cre/features/aptos/aptos_config.go index 09e2bf4d9fd..ff70f22f42d 100644 --- a/system-tests/lib/cre/features/aptos/aptos_config.go +++ b/system-tests/lib/cre/features/aptos/aptos_config.go @@ -1,7 +1,6 @@ package aptos import ( - "encoding/json" "fmt" "strconv" "strings" @@ -33,23 +32,38 @@ func BuildCapabilityConfig(values map[string]any, p2pToTransmitterMap map[string return capConfig, nil } -func buildWorkerConfigJSON(chainID uint64, forwarderAddress string, settings methodConfigSettings, p2pToTransmitterMap map[string]string, isLocal bool) (string, error) { - cfg := map[string]any{ +// setChainSpecConfig adds the per-chain keys the Aptos capability needs to start from its +// registry spec_config alone (they used to be supplied by the worker job spec). The +// remaining keys (deltaStage, transmissionSchedule, p2pToTransmitterMap) are set by +// setRuntimeSpecConfig. +func setChainSpecConfig(capConfig *capabilitiespb.CapabilityConfig, chainID uint64, forwarderAddress string, isLocal bool) error { + if capConfig == nil { + return pkgerrors.New("capability config is nil") + } + + specConfig, err := values.FromMapValueProto(capConfig.SpecConfig) + if err != nil { + return fmt.Errorf("failed to decode existing spec config: %w", err) + } + if specConfig == nil { + specConfig = values.EmptyMap() + } + + for key, raw := range map[string]any{ "chainId": strconv.FormatUint(chainID, 10), "network": "aptos", "creForwarderAddress": forwarderAddress, "isLocal": isLocal, - "deltaStage": settings.DeltaStage, - } - if len(p2pToTransmitterMap) > 0 { - cfg[specConfigP2PMapKey] = p2pToTransmitterMap + } { + wrapped, wrapErr := values.Wrap(raw) + if wrapErr != nil { + return fmt.Errorf("failed to wrap spec config key %q: %w", key, wrapErr) + } + specConfig.Underlying[key] = wrapped } - raw, err := json.Marshal(cfg) - if err != nil { - return "", fmt.Errorf("failed to marshal Aptos worker config: %w", err) - } - return string(raw), nil + capConfig.SpecConfig = values.ProtoMap(specConfig) + return nil } func methodConfigs(settings methodConfigSettings) map[string]*capabilitiespb.CapabilityMethodConfig { diff --git a/system-tests/lib/cre/features/aptos/aptos_test.go b/system-tests/lib/cre/features/aptos/aptos_test.go index 2c1e810175e..08fcfd036b3 100644 --- a/system-tests/lib/cre/features/aptos/aptos_test.go +++ b/system-tests/lib/cre/features/aptos/aptos_test.go @@ -3,12 +3,10 @@ package aptos import ( "context" "encoding/hex" - "encoding/json" "math/big" "testing" "time" - "github.com/Masterminds/semver/v3" "github.com/pelletier/go-toml/v2" "github.com/rs/zerolog" "github.com/stretchr/testify/require" @@ -20,7 +18,6 @@ import ( "github.com/smartcontractkit/chainlink-testing-framework/framework/components/blockchain" "github.com/smartcontractkit/chainlink-testing-framework/framework/components/clnode" ns "github.com/smartcontractkit/chainlink-testing-framework/framework/components/simple_node_set" - keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" "github.com/smartcontractkit/chainlink/system-tests/lib/cre" "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/secrets" creblockchains "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains" @@ -138,23 +135,29 @@ func TestBuildCapabilityConfig_WithoutP2PMap_StillSetsRuntimeSpecConfig(t *testi require.Contains(t, specConfig.Underlying, specConfigDeltaStageKey) } -func TestBuildWorkerConfigJSON_IncludesLocalRuntimeValues(t *testing.T) { - configStr, err := buildWorkerConfigJSON( - 4, - "0x000000000000000000000000000000000000000000000000000000000000000a", - methodConfigSettings{DeltaStage: 2500 * time.Millisecond}, - map[string]string{"peer-a": "0x1"}, - true, - ) +const testForwarder = "0x000000000000000000000000000000000000000000000000000000000000000a" + +func TestSetChainSpecConfig_AddsChainKeysAndKeepsExisting(t *testing.T) { + t.Parallel() + + capConfig, err := BuildCapabilityConfig(nil, map[string]string{"peer-a": "0x1"}, true) require.NoError(t, err) - var got map[string]any - require.NoError(t, json.Unmarshal([]byte(configStr), &got)) + require.NoError(t, setChainSpecConfig(capConfig, 4, testForwarder, true)) + + specConfig, err := values.FromMapValueProto(capConfig.SpecConfig) + require.NoError(t, err) + unwrapped, err := specConfig.Unwrap() + require.NoError(t, err) + got, ok := unwrapped.(map[string]any) + require.True(t, ok) require.Equal(t, "4", got["chainId"]) require.Equal(t, "aptos", got["network"]) + require.Equal(t, testForwarder, got["creForwarderAddress"]) require.Equal(t, true, got["isLocal"]) - require.EqualValues(t, (2500 * time.Millisecond).Nanoseconds(), got["deltaStage"]) require.Equal(t, map[string]any{"peer-a": "0x1"}, got[specConfigP2PMapKey]) + require.Contains(t, got, specConfigDeltaStageKey) + require.Contains(t, got, specConfigScheduleKey) } func TestNormalizeTransmitter(t *testing.T) { @@ -347,6 +350,7 @@ func TestBuildCapabilityRegistrations_UsesCapRegOCRConfig(t *testing.T) { []creblockchains.Blockchain{testAptosBlockchain(4, 4457093679053095497)}, []uint64{4}, map[string]string{"peer-a": "0x1"}, + map[uint64]string{4: testForwarder}, ) require.NoError(t, err) require.Len(t, caps, 1) @@ -355,47 +359,36 @@ func TestBuildCapabilityRegistrations_UsesCapRegOCRConfig(t *testing.T) { require.Equal(t, CapabilityLabel(4457093679053095497), caps[0].Capability.LabelledName) require.Contains(t, capabilityToOCR3Config, capabilityLabels[0]) require.NotNil(t, capabilityToOCR3Config[capabilityLabels[0]]) -} -func TestNewAptosWorkerJobInput_UsesCapRegVersion(t *testing.T) { - creEnv := &cre.Environment{ - RegistryChainSelector: 111, - ContractVersions: map[cre.ContractType]*semver.Version{ - keystone_changeset.CapabilitiesRegistry.String(): semver.MustParse("2.0.0"), - }, - } - - input, err := newAptosWorkerJobInput( - creEnv, - "workflow-don", - "/usr/local/bin/aptos", - `{"chainId":"4"}`, - []string{"peer@127.0.0.1:6690"}, - 222, - 4, - ) + // The capability must be launchable from its registry spec_config alone. + specConfig, err := values.FromMapValueProto(caps[0].Config.SpecConfig) require.NoError(t, err) - require.Equal(t, "aptos-worker-4", input.JobName) - require.Equal(t, true, input.Inputs["useCapRegOCRConfig"]) - require.Equal(t, "2.0.0", input.Inputs["capRegVersion"]) - require.Equal(t, uint64(111), input.Inputs["chainSelectorEVM"]) - require.Equal(t, uint64(222), input.Inputs["chainSelectorAptos"]) - _, hasQualifier := input.Inputs["contractQualifier"] - require.False(t, hasQualifier) + unwrapped, err := specConfig.Unwrap() + require.NoError(t, err) + got, ok := unwrapped.(map[string]any) + require.True(t, ok) + require.Equal(t, "4", got["chainId"]) + require.Equal(t, "aptos", got["network"]) + require.Equal(t, testForwarder, got["creForwarderAddress"]) + require.Equal(t, true, got["isLocal"]) + require.Contains(t, got, specConfigP2PMapKey) } -func TestNewAptosWorkerJobInput_ErrorsWithoutCapRegVersion(t *testing.T) { - _, err := newAptosWorkerJobInput( - &cre.Environment{}, - "workflow-don", - "/usr/local/bin/aptos", - `{"chainId":"4"}`, - nil, - 222, - 4, +func TestBuildCapabilityRegistrations_ErrorsWithoutForwarder(t *testing.T) { + t.Parallel() + + don := testDonMetadataWithCapabilities(t, []string{"[Aptos]\n"}, []string{cre.AptosCapability + "-4"}, cre.CapabilityConfigs{ + cre.AptosCapability: {BinaryName: "aptos"}, + }) + + _, _, _, err := buildCapabilityRegistrations( + don, + []creblockchains.Blockchain{testAptosBlockchain(4, 4457093679053095497)}, + []uint64{4}, + map[string]string{"peer-a": "0x1"}, + map[uint64]string{}, ) - require.Error(t, err) - require.ErrorContains(t, err, "CapabilitiesRegistry version not found") + require.ErrorContains(t, err, "missing Aptos forwarder address") } func testDonMetadata(t *testing.T, nodeConfigs ...string) *cre.DonMetadata { diff --git a/system-tests/lib/cre/features/aptos/aptos_workers.go b/system-tests/lib/cre/features/aptos/aptos_workers.go index 7796108fef4..748e669909d 100644 --- a/system-tests/lib/cre/features/aptos/aptos_workers.go +++ b/system-tests/lib/cre/features/aptos/aptos_workers.go @@ -3,183 +3,16 @@ package aptos import ( "context" "encoding/hex" - "errors" "fmt" - "maps" - "strconv" "strings" - "dario.cat/mergo" pkgerrors "github.com/pkg/errors" - "golang.org/x/sync/errgroup" chainselectors "github.com/smartcontractkit/chain-selectors" - "github.com/smartcontractkit/chainlink/deployment/cre/jobs" - crejobops "github.com/smartcontractkit/chainlink/deployment/cre/jobs/operations" - jobtypes "github.com/smartcontractkit/chainlink/deployment/cre/jobs/types" - "github.com/smartcontractkit/chainlink/deployment/cre/pkg/offchain" - keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" "github.com/smartcontractkit/chainlink/system-tests/lib/cre" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs/standardcapability" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/jobhelpers" ) -func proposeAptosWorkerSpecs( - ctx context.Context, - don *cre.Don, - dons *cre.Dons, - creEnv *cre.Environment, - nodeSet cre.NodeSetWithCapabilityConfigs, - enabledChainIDs []uint64, -) (map[string][]string, error) { - bootstrapPeers, err := bootstrapPeersForDons(dons) - if err != nil { - return nil, err - } - - workerMetadata, err := don.Metadata().Workers() - if err != nil { - return nil, fmt.Errorf("failed to collect Aptos worker metadata for DON %q: %w", don.Name, err) - } - p2pToTransmitterMap, err := p2pToTransmitterMapForWorkers(workerMetadata) - if err != nil { - return nil, fmt.Errorf("failed to collect Aptos worker transmitters for DON %q: %w", don.Name, err) - } - - results := make([]map[string][]string, len(enabledChainIDs)) - group, _ := errgroup.WithContext(ctx) - group.SetLimit(jobhelpers.Parallelism(len(enabledChainIDs))) - - for i, chainID := range enabledChainIDs { - group.Go(func() error { - mergedSpecs, buildErr := proposeAptosWorkerSpecsForChain( - creEnv, - don.Name, - nodeSet, - flag, - chainID, - bootstrapPeers, - p2pToTransmitterMap, - ) - if buildErr != nil { - return buildErr - } - results[i] = maps.Clone(mergedSpecs) - return nil - }) - } - - waitErr := group.Wait() - if waitErr != nil { - return nil, waitErr - } - - specs, err := jobhelpers.MergeSpecsByIndex(results) - if err != nil { - return nil, err - } - return specs, nil -} - -func proposeAptosWorkerSpecsForChain( - creEnv *cre.Environment, - donName string, - nodeSet cre.NodeSetWithCapabilityConfigs, - flag string, - chainID uint64, - bootstrapPeers []string, - p2pToTransmitterMap map[string]string, -) (map[string][]string, error) { - aptosChain, err := findAptosChainByChainID(creEnv.Blockchains, chainID) - if err != nil { - return nil, err - } - - capabilityConfig, err := cre.ResolveCapabilityConfig(nodeSet, flag, cre.ChainCapabilityScope(chainID)) - if err != nil { - return nil, fmt.Errorf("could not resolve capability config for '%s' on chain %d: %w", flag, chainID, err) - } - command, err := standardcapability.GetCommand(capabilityConfig.BinaryName) - if err != nil { - return nil, pkgerrors.Wrap(err, "failed to get command for Aptos capability") - } - - forwarderAddress := mustForwarderAddress(creEnv.CldfEnvironment.DataStore, aptosChain.ChainSelector()) - methodSettings, err := resolveMethodConfigSettings(capabilityConfig.Values) - if err != nil { - return nil, fmt.Errorf("failed to resolve Aptos method config settings for chain %d: %w", chainID, err) - } - configStr, err := buildWorkerConfigJSON(chainID, forwarderAddress, methodSettings, p2pToTransmitterMap, true) - if err != nil { - return nil, fmt.Errorf("failed to build Aptos worker config: %w", err) - } - - workerInput, err := newAptosWorkerJobInput(creEnv, donName, command, configStr, bootstrapPeers, aptosChain.ChainSelector(), chainID) - if err != nil { - return nil, err - } - - proposer := jobs.ProposeJobSpec{} - verifyErr := proposer.VerifyPreconditions(*creEnv.CldfEnvironment, workerInput) - if verifyErr != nil { - return nil, fmt.Errorf("precondition verification failed for Aptos worker job: %w", verifyErr) - } - workerReport, err := proposer.Apply(*creEnv.CldfEnvironment, workerInput) - if err != nil { - return nil, fmt.Errorf("failed to propose Aptos worker job spec: %w", err) - } - - mergedSpecs := make(map[string][]string) - for _, report := range workerReport.Reports { - out, ok := report.Output.(crejobops.ProposeStandardCapabilityJobOutput) - if !ok { - return nil, fmt.Errorf("unable to cast to ProposeStandardCapabilityJobOutput, actual type: %T", report.Output) - } - if err := mergo.Merge(&mergedSpecs, out.Specs, mergo.WithAppendSlice); err != nil { - return nil, fmt.Errorf("failed to merge Aptos worker job specs: %w", err) - } - } - - return mergedSpecs, nil -} - -func newAptosWorkerJobInput( - creEnv *cre.Environment, - donName string, - command string, - configStr string, - bootstrapPeers []string, - aptosChainSelector uint64, - chainID uint64, -) (jobs.ProposeJobSpecInput, error) { - capRegVersion, ok := creEnv.ContractVersions[keystone_changeset.CapabilitiesRegistry.String()] - if !ok { - return jobs.ProposeJobSpecInput{}, errors.New("CapabilitiesRegistry version not found in contract versions") - } - - return jobs.ProposeJobSpecInput{ - Domain: offchain.ProductLabel, - Environment: creEnv.CldfEnvironment.Name, - DONName: donName, - JobName: "aptos-worker-" + strconv.FormatUint(chainID, 10), - ExtraLabels: map[string]string{cre.CapabilityLabelKey: flag}, - DONFilters: []offchain.TargetDONFilter{ - {Key: offchain.FilterKeyDONName, Value: donName}, - }, - Template: jobtypes.Aptos, - Inputs: jobtypes.JobSpecInput{ - "command": command, - "config": configStr, - "chainSelectorEVM": creEnv.RegistryChainSelector, - "chainSelectorAptos": aptosChainSelector, - "bootstrapPeers": bootstrapPeers, - "useCapRegOCRConfig": true, - "capRegVersion": capRegVersion.String(), - }, - }, nil -} - func donOraclePublicKeys(ctx context.Context, don *cre.Don) ([][]byte, error) { workers, err := don.Workers() if err != nil { diff --git a/system-tests/lib/cre/features/evm/v2/evm.go b/system-tests/lib/cre/features/evm/v2/evm.go index 3c7da2c9f5e..358d64c0c53 100644 --- a/system-tests/lib/cre/features/evm/v2/evm.go +++ b/system-tests/lib/cre/features/evm/v2/evm.go @@ -3,21 +3,19 @@ package v2 import ( "bytes" "context" + "encoding/json" "fmt" "maps" + "math" "slices" "sort" "strconv" - "strings" "text/template" "time" - "dario.cat/mergo" "github.com/Masterminds/semver/v3" - "github.com/google/uuid" "github.com/pkg/errors" "github.com/rs/zerolog" - "golang.org/x/sync/errgroup" "google.golang.org/protobuf/types/known/durationpb" chainselectors "github.com/smartcontractkit/chain-selectors" @@ -27,30 +25,24 @@ import ( cldf "github.com/smartcontractkit/chainlink-deployments-framework/deployment" "github.com/smartcontractkit/chainlink-deployments-framework/operations" kcr "github.com/smartcontractkit/chainlink-evm/gethwrappers/keystone/generated/capabilities_registry_1_1_0" + "github.com/smartcontractkit/chainlink-protos/cre/go/values" + valuespb "github.com/smartcontractkit/chainlink-protos/cre/go/values/pb" "github.com/smartcontractkit/chainlink-testing-framework/framework/components/blockchain" "github.com/smartcontractkit/chainlink/deployment/cre/forwarder" - cre_jobs "github.com/smartcontractkit/chainlink/deployment/cre/jobs" - cre_jobs_ops "github.com/smartcontractkit/chainlink/deployment/cre/jobs/operations" - cre_jobs_pkg "github.com/smartcontractkit/chainlink/deployment/cre/jobs/pkg" - job_types "github.com/smartcontractkit/chainlink/deployment/cre/jobs/types" "github.com/smartcontractkit/chainlink/deployment/cre/ocr3" - "github.com/smartcontractkit/chainlink/deployment/cre/pkg/offchain" keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" ks_contracts_op "github.com/smartcontractkit/chainlink/deployment/keystone/changeset/operations/contracts" libc "github.com/smartcontractkit/chainlink/system-tests/lib/conversions" "github.com/smartcontractkit/chainlink/system-tests/lib/cre" "github.com/smartcontractkit/chainlink/system-tests/lib/cre/contracts" credon "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs/standardcapability" "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre/features/jobhelpers" "github.com/smartcontractkit/chainlink/system-tests/lib/cre/flags" ) const ( flag = cre.EVMCapability - configTemplate = `{"chainId":{{printf "%d" .ChainID}}, "network":"{{.NetworkFamily}}", "logTriggerPollInterval":{{printf "%d" .LogTriggerPollInterval}}, "creForwarderAddress":"{{.CreForwarderAddress}}", "receiverGasMinimum":{{.ReceiverGasMinimum}}, "nodeAddress":"{{.NodeAddress}}", "deltaStage":{{printf "%d" .DeltaStage}}{{with .LogTriggerSendChannelBufferSize}},"logTriggerSendChannelBufferSize":{{printf "%d" .}}{{end}}{{with .LogTriggerLimitQueryLogSize}},"logTriggerLimitQueryLogSize":{{printf "%d" .}}{{end}}}` + specConfigTemplate = `{"chainId":{{printf "%d" .ChainID}}, "network":"{{.NetworkFamily}}", "logTriggerPollInterval":{{printf "%d" .LogTriggerPollInterval}}, "creForwarderAddress":"{{.CreForwarderAddress}}", "receiverGasMinimum":{{.ReceiverGasMinimum}}, "deltaStage":{{printf "%d" .DeltaStage}}{{with .LogTriggerSendChannelBufferSize}},"logTriggerSendChannelBufferSize":{{printf "%d" .}}{{end}}{{with .LogTriggerLimitQueryLogSize}},"logTriggerLimitQueryLogSize":{{printf "%d" .}}{{end}}}` registrationRefresh = 20 * time.Second registrationExpiry = 60 * time.Second deltaStage = 500*time.Millisecond + 1*time.Second // block time + 1 second delta @@ -109,6 +101,26 @@ func (o *EVM) PreEnvStartup( return nil, errors.Wrap(err, "there was an error getting EVM method configs") } + capabilityConfig, resolveErr := cre.ResolveCapabilityConfig(don.MustNodeSet(), flag, cre.ChainCapabilityScope(chainID)) + if resolveErr != nil { + return nil, fmt.Errorf("could not resolve capability config for '%s' on chain %d: %w", flag, chainID, resolveErr) + } + + creForwarderAddress, addrErr := creEnv.CldfEnvironment.DataStore.Addresses().Get(datastore.NewAddressRefKey( + selector, + datastore.ContractType(keystone_changeset.KeystoneForwarder.String()), + semver.MustParse("1.0.0"), + "", + )) + if addrErr != nil { + return nil, errors.Wrapf(addrErr, "failed to get CRE Forwarder address for chain %d", chainID) + } + + specConfig, specErr := buildSpecConfig(chainID, creForwarderAddress.Address, capabilityConfig.Values) + if specErr != nil { + return nil, errors.Wrapf(specErr, "failed to build EVM spec config for chain %d", chainID) + } + capabilities = append(capabilities, keystone_changeset.DONCapabilityWithConfig{ Capability: kcr.CapabilitiesRegistryCapability{ LabelledName: "evm" + ":ChainSelector:" + strconv.FormatUint(selector, 10), @@ -117,6 +129,7 @@ func (o *EVM) PreEnvStartup( Config: &capabilitiespb.CapabilityConfig{ MethodConfigs: evmMethodConfigs, LocalOnly: don.HasOnlyLocalCapabilities(), + SpecConfig: specConfig, }, UseCapRegOCRConfig: true, }) @@ -140,15 +153,8 @@ func (o *EVM) PostEnvStartup( dons *cre.Dons, creEnv *cre.Environment, ) error { - jobsErr := createJobs( - ctx, - don, - dons, - creEnv, - ) - if jobsErr != nil { - return jobsErr - } + // The EVM capability is launched by the node from its registry spec_config + // (see PreEnvStartup), so no worker job spec is proposed here. // configure EVM forwarders for DONs that run consensus consensusDons := dons.DonsWithFlags(cre.ConsensusCapability) @@ -188,253 +194,54 @@ func chainsWithEVMCapability(chains []blockchains.Blockchain, dons []*cre.Don) m return chainsWithEVMCapability } -func createJobs( - ctx context.Context, - don *cre.Don, - dons *cre.Dons, - creEnv *cre.Environment, -) error { - var nodeSet cre.NodeSetWithCapabilityConfigs - for _, ns := range dons.AsNodeSetWithChainCapabilities() { - if ns.GetName() == don.Name { - nodeSet = ns - break - } - } - if nodeSet == nil { - return fmt.Errorf("could not find node set for Don named '%s'", don.Name) - } - - bootstrap, isBootstrap := dons.Bootstrap() - if !isBootstrap { - return errors.New("could not find bootstrap node in topology, exactly one bootstrap node is required") - } - - workerNodes, wErr := don.Workers() - if wErr != nil { - return errors.Wrap(wErr, "failed to find worker nodes") +// buildSpecConfig renders the EVM capability's spec_config for one chain. Every node of the DON +// shares it, so it carries no per-node values: nodeAddress was only a monitoring label and is +// filled in by the node when absent. +func buildSpecConfig(chainID uint64, creForwarderAddress string, capabilityValues map[string]any) (*valuespb.Map, error) { + templateData, err := credon.ApplyRuntimeValues(maps.Clone(capabilityValues), buildRuntimeValues(chainID, "evm", creForwarderAddress)) + if err != nil { + return nil, errors.Wrap(err, "failed to apply runtime values") } - enabledChainIDs, err := nodeSet.GetEnabledChainIDsForCapability(flag) + tmpl, err := template.New("evmConfig").Parse(specConfigTemplate) if err != nil { - return fmt.Errorf("could not find enabled chainIDs for '%s' in don '%s': %w", flag, don.Name, err) + return nil, errors.Wrapf(err, "failed to parse %s spec config template", flag) } - registryChainID, rcErr := chainselectors.ChainIdFromSelector(creEnv.RegistryChainSelector) - if rcErr != nil { - return fmt.Errorf("failed to get chain ID from registry chain selector %d: %w", creEnv.RegistryChainSelector, rcErr) + var configBuffer bytes.Buffer + if execErr := tmpl.Execute(&configBuffer, templateData); execErr != nil { + return nil, errors.Wrapf(execErr, "failed to execute %s spec config template", flag) } + rendered := configBuffer.String() - type proposalWork struct { - chainID uint64 - chainIDStr string - chainSelector uint64 - capabilityConfig cre.CapabilityConfig - command string - workerNode *cre.Node + if validateErr := credon.ValidateTemplateSubstitution(rendered, flag); validateErr != nil { + return nil, fmt.Errorf("%s template validation failed: %w\nRendered template: %s", flag, validateErr, rendered) } - workItems := make([]proposalWork, 0, len(enabledChainIDs)*len(workerNodes)) - for _, chainID := range enabledChainIDs { - chainSelector, selErr := chainselectors.SelectorFromChainId(chainID) - if selErr != nil { - return errors.Wrapf(selErr, "failed to get chain selector from chainID %d", chainID) - } - chainIDStr := strconv.FormatUint(chainID, 10) - - capabilityConfig, resolveErr := cre.ResolveCapabilityConfig(nodeSet, flag, cre.ChainCapabilityScope(chainID)) - if resolveErr != nil { - return fmt.Errorf("could not resolve capability config for '%s' on chain %d: %w", flag, chainID, resolveErr) - } - - command, cErr := standardcapability.GetCommand(capabilityConfig.BinaryName) - if cErr != nil { - return errors.Wrap(cErr, "failed to get command for Read Contract capability") - } - - for _, workerNode := range workerNodes { - workItems = append(workItems, proposalWork{ - chainID: chainID, - chainIDStr: chainIDStr, - chainSelector: chainSelector, - capabilityConfig: capabilityConfig, - command: command, - workerNode: workerNode, - }) - } + var cfg map[string]any + if err = json.Unmarshal([]byte(rendered), &cfg); err != nil { + return nil, errors.Wrapf(err, "failed to decode rendered %s spec config", flag) } - - results := make([]map[string][]string, len(workItems)) - group, groupCtx := errgroup.WithContext(ctx) - group.SetLimit(jobhelpers.Parallelism(len(workItems))) - - for i, workItem := range workItems { - group.Go(func() error { - chainID := workItem.chainID - chainSelector := workItem.chainSelector - workerNode := workItem.workerNode - - evmKey, ok := workerNode.Keys.EVM[chainID] - if !ok { - return fmt.Errorf("failed to get EVM key (chainID %d, node index %d)", chainID, workerNode.Index) - } - nodeAddress := evmKey.PublicAddress.Hex() - - evmRegistryKey, ok := workerNode.Keys.EVM[registryChainID] - if !ok { - return fmt.Errorf("failed to get registry EVM key (chainID %d, node index %d) enabledChainIDs: %v", registryChainID, workerNode.Index, enabledChainIDs) - } - nodeRegistryAddress := evmRegistryKey.PublicAddress.Hex() - - creForwarderKey := datastore.NewAddressRefKey( - chainSelector, - datastore.ContractType(keystone_changeset.KeystoneForwarder.String()), - semver.MustParse("1.0.0"), - "", - ) - creForwarderAddress, cErr := creEnv.CldfEnvironment.DataStore.Addresses().Get(creForwarderKey) - if cErr != nil { - return errors.Wrap(cErr, "failed to get CRE Forwarder address") - } - - runtimeFallbacks := buildRuntimeValues(chainID, "evm", creForwarderAddress.Address, nodeAddress) - templateData := maps.Clone(workItem.capabilityConfig.Values) - - var aErr error - templateData, aErr = credon.ApplyRuntimeValues(templateData, runtimeFallbacks) - if aErr != nil { - return errors.Wrap(aErr, "failed to apply runtime values") - } - - tmpl, tErr := template.New("evmConfig").Parse(configTemplate) - if tErr != nil { - return errors.Wrapf(tErr, "failed to parse %s config template", flag) - } - - var configBuffer bytes.Buffer - if execErr := tmpl.Execute(&configBuffer, templateData); execErr != nil { - return errors.Wrapf(execErr, "failed to execute %s config template", flag) - } - - configStr := configBuffer.String() - - if validateErr := credon.ValidateTemplateSubstitution(configStr, flag); validateErr != nil { - return fmt.Errorf("%s template validation failed: %w\nRendered template: %s", flag, validateErr, configStr) - } - - evmKeyBundle, ok := workerNode.Keys.OCR2BundleIDs[chainselectors.FamilyEVM] // we can always expect evm bundle key id present since evm is the registry chain - if !ok { - return fmt.Errorf("failed to get key bundle id for evm family for node %s", workerNode.Name) - } - - bootstrapPeers := []string{fmt.Sprintf("%s@%s:%d", strings.TrimPrefix(bootstrap.Keys.PeerID(), "p2p_"), bootstrap.Host, cre.PeeringPort)} - - strategyName := "single-chain" - if len(workerNode.Keys.OCR2BundleIDs) > 1 { - strategyName = "multi-chain" - } - - capRegVersion, ok := creEnv.ContractVersions[keystone_changeset.CapabilitiesRegistry.String()] - if !ok { - return errors.New("CapabilitiesRegistry version not found in contract versions") - } - registryAddrRefKey := cre_jobs_pkg.GetCapRegAddressRefKey(creEnv.RegistryChainSelector, "", capRegVersion.String()) - registryContractAddrRef, err := creEnv.CldfEnvironment.DataStore.Addresses().Get(registryAddrRefKey) - if err != nil { - return fmt.Errorf("failed to get contract address for ref key %s: %w", registryAddrRefKey, err) - } - - workerInput := cre_jobs.ProposeJobSpecInput{ - Domain: offchain.ProductLabel, - Environment: creEnv.CldfEnvironment.Name, - DONName: don.Name, - JobName: fmt.Sprintf("evm-worker-%d", chainID), - ExtraLabels: map[string]string{cre.CapabilityLabelKey: flag}, - DONFilters: []offchain.TargetDONFilter{ - {Key: offchain.FilterKeyDONName, Value: don.Name}, - {Key: "p2p_id", Value: workerNode.Keys.PeerID()}, // required since each node requires a different config (it contains its own from address) - }, - Template: job_types.EVM, - Inputs: job_types.JobSpecInput{ - "command": workItem.command, - "config": configStr, - "oracleFactory": cre_jobs_pkg.OracleFactory{ - Enabled: true, - ChainID: workItem.chainIDStr, - BootstrapPeers: bootstrapPeers, - OCRContractAddress: registryContractAddrRef.Address, - OCRKeyBundleID: evmKeyBundle, - TransmitterID: nodeRegistryAddress, - OnchainSigningStrategy: cre_jobs_pkg.OnchainSigningStrategy{ - StrategyName: strategyName, - Config: workerNode.Keys.OCR2BundleIDs, - }, - }, - "useCapRegOCRConfig": true, - "capRegVersion": capRegVersion.String(), - }, - } - if creEnv.FreshExternalJobIDs { - workerInput.Inputs["externalJobID"] = uuid.NewString() - } - - workerVerErr := cre_jobs.ProposeJobSpec{}.VerifyPreconditions(*creEnv.CldfEnvironment, workerInput) - if workerVerErr != nil { - return fmt.Errorf("precondition verification failed for EVM worker job: %w", workerVerErr) - } - - workerReport, workerErr := cre_jobs.ProposeJobSpec{}.Apply(*creEnv.CldfEnvironment, workerInput) - if workerErr != nil { - return fmt.Errorf("failed to propose EVM worker job spec: %w", workerErr) - } - - specs := make(map[string][]string) - for _, r := range workerReport.Reports { - out, ok := r.Output.(cre_jobs_ops.ProposeStandardCapabilityJobOutput) - if !ok { - return fmt.Errorf("unable to cast to ProposeStandardCapabilityJobOutput, actual type: %T", r.Output) - } - mErr := mergo.Merge(&specs, out.Specs, mergo.WithAppendSlice) - if mErr != nil { - return fmt.Errorf("failed to merge worker job specs: %w", mErr) - } - } - - select { - case <-groupCtx.Done(): - return groupCtx.Err() - default: - } - - results[i] = specs - return nil - }) - } - - if wErr := group.Wait(); wErr != nil { - return wErr - } - - specs, mErr := jobhelpers.MergeSpecsByIndex(results) - if mErr != nil { - return mErr + for key, v := range cfg { + // encoding/json decodes every number as float64; keep integral ones integral. + if f, ok := v.(float64); ok && f == math.Trunc(f) { + cfg[key] = int64(f) + } } - approveErr := jobs.Approve(ctx, creEnv.CldfEnvironment.Offchain, dons, specs) - if approveErr != nil { - return fmt.Errorf("failed to approve EVM jobs: %w", approveErr) + wrapped, err := values.NewMap(cfg) + if err != nil { + return nil, errors.Wrapf(err, "failed to wrap %s spec config", flag) } - - return nil + return values.ProtoMap(wrapped), nil } // buildRuntimeValues creates runtime-generated values for any keys not specified in TOML -func buildRuntimeValues(chainID uint64, networkFamily, creForwarderAddress, nodeAddress string) map[string]any { +func buildRuntimeValues(chainID uint64, networkFamily, creForwarderAddress string) map[string]any { return map[string]any{ "ChainID": chainID, "NetworkFamily": networkFamily, "CreForwarderAddress": creForwarderAddress, - "NodeAddress": nodeAddress, "DeltaStage": deltaStage, } } diff --git a/system-tests/lib/cre/features/evm/v2/spec_config_test.go b/system-tests/lib/cre/features/evm/v2/spec_config_test.go new file mode 100644 index 00000000000..9619f6e164d --- /dev/null +++ b/system-tests/lib/cre/features/evm/v2/spec_config_test.go @@ -0,0 +1,45 @@ +package v2 + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-protos/cre/go/values" +) + +func TestBuildSpecConfig_SharedAcrossNodes(t *testing.T) { + t.Parallel() + + specConfig, err := buildSpecConfig(1337, "0xforwarder", map[string]any{ + "LogTriggerPollInterval": int64(1), + "ReceiverGasMinimum": int64(500), + "LogTriggerSendChannelBufferSize": int64(100), + }) + require.NoError(t, err) + + decoded, err := values.FromMapValueProto(specConfig) + require.NoError(t, err) + unwrapped, err := decoded.Unwrap() + require.NoError(t, err) + got, ok := unwrapped.(map[string]any) + require.True(t, ok) + + assert.Equal(t, int64(1337), got["chainId"]) + assert.Equal(t, "evm", got["network"]) + assert.Equal(t, "0xforwarder", got["creForwarderAddress"]) + assert.Equal(t, int64(500), got["receiverGasMinimum"]) + assert.Equal(t, int64(1), got["logTriggerPollInterval"]) + assert.Equal(t, int64(100), got["logTriggerSendChannelBufferSize"]) + assert.Equal(t, int64(deltaStage), got["deltaStage"]) + assert.NotContains(t, got, "nodeAddress", "per-node values must not be in the shared spec_config") + assert.NotContains(t, got, "logTriggerLimitQueryLogSize", "unset optional values must be omitted") +} + +func TestBuildSpecConfig_ErrorsOnMissingRequiredValue(t *testing.T) { + t.Parallel() + + _, err := buildSpecConfig(1337, "0xforwarder", map[string]any{}) + require.Error(t, err) +} diff --git a/system-tests/lib/cre/features/stellar/stellar.go b/system-tests/lib/cre/features/stellar/stellar.go index 705e7995aea..28ad3654578 100644 --- a/system-tests/lib/cre/features/stellar/stellar.go +++ b/system-tests/lib/cre/features/stellar/stellar.go @@ -15,7 +15,6 @@ import ( keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" "github.com/smartcontractkit/chainlink/system-tests/lib/cre" "github.com/smartcontractkit/chainlink/system-tests/lib/cre/contracts" - crejobs "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs" stellchain "github.com/smartcontractkit/chainlink/system-tests/lib/cre/environment/blockchains/stellar" ) @@ -56,6 +55,21 @@ func (s *Stellar) PreEnvStartup( return nil, fmt.Errorf("failed to resolve Stellar method config settings: %w", err) } + // The forwarder address is part of the capability's spec_config, so deploy it first. + if deployErr := deployStellarForwarders(ctx, testLogger, creEnv, stellarChain); deployErr != nil { + return nil, fmt.Errorf("failed to deploy stellar CRE forwarder: %w", deployErr) + } + + specConfig, err := buildSpecConfig( + stellarChain.StellarChainID(), + mustForwarderAddress(creEnv.CldfEnvironment.DataStore, stellarChain.ChainSelector()), + methodSettings, + don.HasFlag(cre.WorkflowDON), + ) + if err != nil { + return nil, fmt.Errorf("failed to build Stellar spec config: %w", err) + } + labelledName := CapabilityLabel(stellarChain.ChainSelector()) capabilities := []keystone_changeset.DONCapabilityWithConfig{{ Capability: kcr.CapabilitiesRegistryCapability{ @@ -66,14 +80,11 @@ func (s *Stellar) PreEnvStartup( Config: &capabilitiespb.CapabilityConfig{ MethodConfigs: methodConfigs(methodSettings), LocalOnly: don.HasOnlyLocalCapabilities(), + SpecConfig: specConfig, }, UseCapRegOCRConfig: true, }} - if deployErr := deployStellarForwarders(ctx, testLogger, creEnv, stellarChain); deployErr != nil { - return nil, fmt.Errorf("failed to deploy stellar CRE forwarder: %w", deployErr) - } - capabilityToExtraSignerFamilies := make(map[string][]string, len(capabilities)) ocrConfigs := map[string]*ocr3.OracleConfig{} for _, capability := range capabilities { @@ -100,11 +111,6 @@ func (s *Stellar) PostEnvStartup( return errors.New("no stellar blockchain found in environment") } - nodeSet, err := nodeSetForDON(dons, don.Name) - if err != nil { - return err - } - consensusDons := dons.DonsWithFlag(cre.ConsensusCapability) if len(consensusDons) == 0 { return errors.New("no consensus DON found in environment") @@ -118,18 +124,8 @@ func (s *Stellar) PostEnvStartup( return errors.Wrap(authErr, "failed to authorize stellar forwarder transmitters") } - specs, err := proposeStellarStandardCapabilityJobs(ctx, don, dons, creEnv, nodeSet) - if err != nil { - return errors.Wrap(err, "failed to propose Stellar standard capability job specs") - } - if len(specs) == 0 { - return nil - } - - if approveErr := crejobs.Approve(ctx, creEnv.CldfEnvironment.Offchain, dons, specs); approveErr != nil { - return fmt.Errorf("failed to approve Stellar jobs: %w", approveErr) - } - + // The Stellar capability is launched by the node from its registry spec_config + // (see PreEnvStartup), so no job spec is proposed here. return nil } diff --git a/system-tests/lib/cre/features/stellar/stellar_config.go b/system-tests/lib/cre/features/stellar/stellar_config.go index 3a379de6e5e..5d3cd7a0c1e 100644 --- a/system-tests/lib/cre/features/stellar/stellar_config.go +++ b/system-tests/lib/cre/features/stellar/stellar_config.go @@ -3,6 +3,7 @@ package stellar import ( "encoding/json" "fmt" + "math" "strconv" "strings" "time" @@ -10,6 +11,8 @@ import ( "google.golang.org/protobuf/types/known/durationpb" capabilitiespb "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" + "github.com/smartcontractkit/chainlink-protos/cre/go/values" + valuespb "github.com/smartcontractkit/chainlink-protos/cre/go/values/pb" "github.com/smartcontractkit/chainlink/deployment/cre/jobs" ) @@ -116,6 +119,38 @@ func buildJobConfigJSON( return string(raw), nil } +// buildSpecConfig returns the Stellar capability config as registry spec_config. It carries +// the same keys the worker job spec used to supply, so the node can launch the capability +// from the registry alone. +func buildSpecConfig( + chainID string, + forwarderAddress string, + settings methodConfigSettings, + isLocal bool, +) (*valuespb.Map, error) { + raw, err := buildJobConfigJSON(chainID, forwarderAddress, settings, isLocal) + if err != nil { + return nil, err + } + + var cfg map[string]any + if err = json.Unmarshal([]byte(raw), &cfg); err != nil { + return nil, fmt.Errorf("failed to decode Stellar config: %w", err) + } + for key, v := range cfg { + // encoding/json decodes every number as float64; keep integral ones integral. + if f, ok := v.(float64); ok && f == math.Trunc(f) { + cfg[key] = int64(f) + } + } + + wrapped, err := values.NewMap(cfg) + if err != nil { + return nil, fmt.Errorf("failed to wrap Stellar spec config: %w", err) + } + return values.ProtoMap(wrapped), nil +} + func durationValue(values map[string]any, key string) (time.Duration, bool, error) { raw, ok := values[key] if !ok { diff --git a/system-tests/lib/cre/features/stellar/stellar_config_test.go b/system-tests/lib/cre/features/stellar/stellar_config_test.go index 281e43b87e4..81659e960a3 100644 --- a/system-tests/lib/cre/features/stellar/stellar_config_test.go +++ b/system-tests/lib/cre/features/stellar/stellar_config_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" capabilitiespb "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" + "github.com/smartcontractkit/chainlink-protos/cre/go/values" ) func TestResolveMethodConfigSettings(t *testing.T) { @@ -111,3 +112,29 @@ func TestBuildWorkerConfigJSON(t *testing.T) { require.NoError(t, json.Unmarshal([]byte(rawLocal), &localCfg)) assert.Equal(t, true, localCfg["isLocal"]) } + +func TestBuildSpecConfig(t *testing.T) { + t.Parallel() + + settings := methodConfigSettings{RequestTimeout: 30 * time.Second, DeltaStage: 15 * time.Second} + const ( + chainID = "baefd734b8d3e48472cff83912375fedbc7573701912fe308af730180f97d74a" + forwarder = "CBQY7TRRXPAZBLCON2PJ6EEZ4OXUY2HYDRERFVIE4MSBDSB2NVNZG42V" + ) + + specConfig, err := buildSpecConfig(chainID, forwarder, settings, true) + require.NoError(t, err) + + decoded, err := values.FromMapValueProto(specConfig) + require.NoError(t, err) + unwrapped, err := decoded.Unwrap() + require.NoError(t, err) + got, ok := unwrapped.(map[string]any) + require.True(t, ok) + + assert.Equal(t, network, got["network"]) + assert.Equal(t, chainID, got["chainId"]) + assert.Equal(t, forwarder, got["creForwarderAddress"]) + assert.Equal(t, true, got["isLocal"]) + assert.Equal(t, settings.DeltaStage.Nanoseconds(), got["deltaStage"]) +} diff --git a/system-tests/lib/cre/features/stellar/stellar_jobs.go b/system-tests/lib/cre/features/stellar/stellar_jobs.go deleted file mode 100644 index 1f5bff320d2..00000000000 --- a/system-tests/lib/cre/features/stellar/stellar_jobs.go +++ /dev/null @@ -1,171 +0,0 @@ -package stellar - -import ( - "context" - "fmt" - "strconv" - "strings" - - "dario.cat/mergo" - pkgerrors "github.com/pkg/errors" - - cre_jobs "github.com/smartcontractkit/chainlink/deployment/cre/jobs" - cre_jobs_ops "github.com/smartcontractkit/chainlink/deployment/cre/jobs/operations" - job_types "github.com/smartcontractkit/chainlink/deployment/cre/jobs/types" - "github.com/smartcontractkit/chainlink/deployment/cre/pkg/offchain" - keystone_changeset "github.com/smartcontractkit/chainlink/deployment/keystone/changeset" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre" - "github.com/smartcontractkit/chainlink/system-tests/lib/cre/don/jobs/standardcapability" -) - -// proposeStellarStandardCapabilityJobs proposes the standard-capability job that -// runs the Stellar chain capability. -func proposeStellarStandardCapabilityJobs( - _ context.Context, - don *cre.Don, - dons *cre.Dons, - creEnv *cre.Environment, - nodeSet cre.NodeSetWithCapabilityConfigs, -) (map[string][]string, error) { - bootstrapPeers, err := bootstrapPeersForDons(dons) - if err != nil { - return nil, err - } - - stellarChain := extractStellarFromEnv(creEnv) - if stellarChain == nil { - return nil, pkgerrors.New("no stellar blockchain found in environment") - } - - return proposeStellarStandardCapabilityJobsForChain( - creEnv, - don.Name, - nodeSet, - stellarChain.StellarChainID(), - stellarChain.ChainSelector(), - bootstrapPeers, - don.HasFlag(cre.WorkflowDON), - ) -} - -func proposeStellarStandardCapabilityJobsForChain( - creEnv *cre.Environment, - donName string, - nodeSet cre.NodeSetWithCapabilityConfigs, - chainID string, - chainSelector uint64, - bootstrapPeers []string, - isLocal bool, -) (map[string][]string, error) { - capabilityConfig, err := cre.ResolveCapabilityConfig(nodeSet, flag, cre.CapabilityScope{}) - if err != nil { - return nil, fmt.Errorf("could not resolve capability config for '%s': %w", flag, err) - } - - command, err := standardcapability.GetCommand(capabilityConfig.BinaryName) - if err != nil { - return nil, pkgerrors.Wrap(err, "failed to get command for Stellar capability") - } - - methodSettings, err := resolveMethodConfigSettings(capabilityConfig.Values) - if err != nil { - return nil, fmt.Errorf("failed to resolve Stellar method config settings: %w", err) - } - - forwarderAddress := mustForwarderAddress(creEnv.CldfEnvironment.DataStore, chainSelector) - - configStr, err := buildJobConfigJSON(chainID, forwarderAddress, methodSettings, isLocal) - if err != nil { - return nil, fmt.Errorf("failed to build Stellar standard capability job config: %w", err) - } - - jobInput, err := newStellarStandardCapabilityJobInput( - creEnv, - donName, - command, - configStr, - bootstrapPeers, - chainSelector, - ) - if err != nil { - return nil, err - } - - proposer := cre_jobs.ProposeJobSpec{} - if verifyErr := proposer.VerifyPreconditions(*creEnv.CldfEnvironment, jobInput); verifyErr != nil { - return nil, fmt.Errorf("precondition verification failed for Stellar standard capability job: %w", verifyErr) - } - - jobReport, err := proposer.Apply(*creEnv.CldfEnvironment, jobInput) - if err != nil { - return nil, fmt.Errorf("failed to propose Stellar standard capability job spec: %w", err) - } - - mergedSpecs := make(map[string][]string) - for _, report := range jobReport.Reports { - out, ok := report.Output.(cre_jobs_ops.ProposeStandardCapabilityJobOutput) - if !ok { - return nil, fmt.Errorf("unable to cast to ProposeStandardCapabilityJobOutput, actual type: %T", report.Output) - } - if mergeErr := mergo.Merge(&mergedSpecs, out.Specs, mergo.WithAppendSlice); mergeErr != nil { - return nil, fmt.Errorf("failed to merge Stellar standard capability job specs: %w", mergeErr) - } - } - - return mergedSpecs, nil -} - -func newStellarStandardCapabilityJobInput( - creEnv *cre.Environment, - donName string, - command string, - configStr string, - bootstrapPeers []string, - stellarChainSelector uint64, -) (cre_jobs.ProposeJobSpecInput, error) { - capRegVersion, ok := creEnv.ContractVersions[keystone_changeset.CapabilitiesRegistry.String()] - if !ok { - return cre_jobs.ProposeJobSpecInput{}, pkgerrors.New("CapabilitiesRegistry version not found in contract versions") - } - - return cre_jobs.ProposeJobSpecInput{ - Domain: offchain.ProductLabel, - Environment: cre.EnvironmentName, - DONName: donName, - JobName: "stellar-worker-" + strconv.FormatUint(stellarChainSelector, 10), - ExtraLabels: map[string]string{cre.CapabilityLabelKey: flag}, - DONFilters: []offchain.TargetDONFilter{ - {Key: offchain.FilterKeyDONName, Value: donName}, - }, - Template: job_types.Stellar, - Inputs: job_types.JobSpecInput{ - "command": command, - "config": configStr, - "chainSelectorEVM": creEnv.RegistryChainSelector, - "chainSelectorStellar": stellarChainSelector, - "bootstrapPeers": bootstrapPeers, - "useCapRegOCRConfig": true, - "capRegVersion": capRegVersion.String(), - }, - }, nil -} - -func bootstrapPeersForDons(dons *cre.Dons) ([]string, error) { - bootstrapNode, ok := dons.Bootstrap() - if !ok { - return nil, pkgerrors.New("bootstrap node not found; required for Stellar OCR bootstrap peers") - } - - return []string{ - fmt.Sprintf("%s@%s:%d", strings.TrimPrefix(bootstrapNode.Keys.PeerID(), "p2p_"), bootstrapNode.Host, cre.PeeringPort), - }, nil -} - -func nodeSetForDON(dons *cre.Dons, donName string) (cre.NodeSetWithCapabilityConfigs, error) { - for _, ns := range dons.AsNodeSetWithChainCapabilities() { - if ns.GetName() == donName { - return ns, nil - } - } - return nil, fmt.Errorf("could not find node set for Don named '%s'", donName) -}