diff --git a/docs/env.md b/docs/env.md index 34f1f62ae..1eb886976 100644 --- a/docs/env.md +++ b/docs/env.md @@ -32,6 +32,7 @@ Environmental variables are also tracked in `ENVIRONMENT_VARIABLES` within `src/ - `TRUST_PROXY`: Controls how the client IP (used for per-IP rate limiting and the deny list) is derived from the `X-Forwarded-For` header, using [Express `trust proxy`](https://expressjs.com/en/guide/behind-proxies.html) semantics. **Default: `false`** — the header is ignored and the real socket peer is used, so a client cannot spoof its address. Only enable it when the node sits behind a trusted reverse proxy: set the number of trusted proxy hops in front of the node (e.g. `1`), a preset (`loopback`, `linklocal`, `uniquelocal`), or a comma-separated list of trusted proxy IPs/subnets. A bare `TRUST_PROXY=true` is **rejected at startup**, because it trusts the whole chain and makes the client-claimed left-most `X-Forwarded-For` address the request IP — re-opening the spoof. With any over-broad value (e.g. trusting a proxy that appends rather than overwrites the header) clients can spoof their IP again, so prefer the minimal hop count that matches your deployment. **When `TRUST_PROXY` is set, the reverse proxy must be the only route to the node.** Express trusts the configured number of hops counting back from the connection, so a client that reaches the node on a shorter path than expected (e.g. by connecting directly to the HTTP port) can still supply the trusted address. Bind the HTTP API to loopback or an internal network and expose it publicly only through the proxy (see `docs/dockerDeployment.md`). - `MAX_CHECKSUM_LENGTH`: Define the maximum length for a file if checksum is required (Mb). Example: `10` - `IS_BOOTSTRAP`: Is this node to be used as bootstrap node or not. Default is `false`. +- `IS_ENTERPRISE`: Run as an Ocean Enterprise node. Compute payments (escrow locks/claims, the escrow address reported in status) and escrow event indexing use the `EnterpriseEscrow` contract instead of `Escrow`, falling back to `Escrow` on chains where `EnterpriseEscrow` is not deployed. Default is `false`. - `AUTHORIZED_PUBLISHERS`: Authorized list of publishers. If present, Node will only index assets published by the accounts in the list. Example: `"[\"0x967da4048cD07aB37855c090aAF366e4ce1b9F48\",\"0x388C818CA8B9251b393131C08a736A67ccB19297\"]"` - `AUTHORIZED_PUBLISHERS_LIST`: AccessList contract addresses (per chain). If present, Node will only index assets published by the accounts present on the given access lists. Example: `"{ \"8996\": [\"0x967da4048cD07aB37855c090aAF366e4ce1b9F48\",\"0x388C818CA8B9251b393131C08a736A67ccB19297\"] }"` - `VALIDATE_UNSIGNED_DDO`: If set to `false`, the node will not validate unsigned DDOs and will request a signed message with the publisher address, nonce and signature. Default is `true`. Example: `false` diff --git a/src/@types/OceanNode.ts b/src/@types/OceanNode.ts index 9923e90fa..b99957d0c 100644 --- a/src/@types/OceanNode.ts +++ b/src/@types/OceanNode.ts @@ -219,6 +219,9 @@ export interface OceanNodeConfig { // fileInfo path, counted in a separate bucket from the global rate limit. 0 = disabled. fileInfoRateLimit?: number isBootstrap?: boolean + // Ocean Enterprise node: switches enterprise-only behaviour (e.g. EnterpriseEscrow instead + // of Escrow for compute payments and escrow event indexing) + isEnterprise?: boolean validateUnsignedDDO?: boolean jwtSecret?: string httpCertPath?: string diff --git a/src/OceanNode.ts b/src/OceanNode.ts index 26950a713..ed9855f82 100644 --- a/src/OceanNode.ts +++ b/src/OceanNode.ts @@ -93,7 +93,8 @@ export class OceanNode { this.config.claimDurationTimeout, this.blockchainRegistry, this.config.subsidyProviders, - this.config.escrowEmptyTx + this.config.escrowEmptyTx, + this.config.isEnterprise ) if (this.config.persistentStorage?.enabled) { OCEAN_NODE_LOGGER.info( @@ -302,7 +303,8 @@ export class OceanNode { this.config.claimDurationTimeout, this.blockchainRegistry, this.config.subsidyProviders, - this.config.escrowEmptyTx + this.config.escrowEmptyTx, + this.config.isEnterprise ) } } diff --git a/src/components/Indexer/ChainIndexer.ts b/src/components/Indexer/ChainIndexer.ts index 66751ceb2..b8c5f7d0c 100644 --- a/src/components/Indexer/ChainIndexer.ts +++ b/src/components/Indexer/ChainIndexer.ts @@ -292,7 +292,8 @@ export class ChainIndexer { provider, this.blockchain.getSupportedChain(), startBlock, - blocksToProcess + blocksToProcess, + this.config.isEnterprise ), 'retrieveChunkEvents' ) diff --git a/src/components/Indexer/processors/EscrowEventProcessor.ts b/src/components/Indexer/processors/EscrowEventProcessor.ts index 483c19d58..146682e41 100644 --- a/src/components/Indexer/processors/EscrowEventProcessor.ts +++ b/src/components/Indexer/processors/EscrowEventProcessor.ts @@ -1,7 +1,7 @@ import { ethers, Signer, FallbackProvider, Interface } from 'ethers' import { INDEXER_LOGGER } from '../../../utils/logging/common.js' import { BaseEventProcessor } from './BaseProcessor.js' -import { getContractAddress } from '../utils.js' +import { getEscrowAddressForChain } from '../../../utils/address.js' import { EVENTS } from '../../../utils/constants.js' import { EscrowEvent } from '../../../@types/Escrow.js' import { OceanNodeConfig } from '../../../@types/OceanNode.js' @@ -17,7 +17,8 @@ export class EscrowEventProcessor extends BaseEventProcessor { constructor(chainId: number, config: OceanNodeConfig) { super(chainId, config) - this.escrowAddress = getContractAddress(chainId, 'Escrow') + // Escrow or EnterpriseEscrow (identical events), whichever this node pays through + this.escrowAddress = getEscrowAddressForChain(chainId, config?.isEnterprise) } async processEvent( diff --git a/src/components/Indexer/utils.ts b/src/components/Indexer/utils.ts index 2f3651dbc..7a59a07c5 100644 --- a/src/components/Indexer/utils.ts +++ b/src/components/Indexer/utils.ts @@ -6,7 +6,10 @@ import { NetworkEvent } from '../../@types/blockchain.js' import { INDEXER_LOGGER } from '../../utils/logging/common.js' import { errorSummary, redactUrls } from '../../utils/logging/redact.js' import ERC20Template from '@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json' with { type: 'json' } -import { getOceanArtifactsAdressesByChainId } from '../../utils/address.js' +import { + getEscrowAddressForChain, + getOceanArtifactsAdressesByChainId +} from '../../utils/address.js' import { CommandStatus, JobStatus } from '../../@types/commands.js' import { create256Hash } from '../../utils/crypt.js' import Dispenser from '@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json' with { type: 'json' } @@ -105,7 +108,8 @@ export const retrieveChunkEvents = async ( provider: FallbackProvider, network: number, lastIndexedBlock: number, - count: number + count: number, + isEnterprise: boolean = false ): Promise => { const startIndex = lastIndexedBlock + 1 const toBlock = lastIndexedBlock + count @@ -120,10 +124,11 @@ export const retrieveChunkEvents = async ( }) ] - // Only query escrow events from the known Escrow contract address. When it is not - // deployed on this chain the escrow processor would drop every event anyway, so we - // skip the query entirely (this also avoids logging unrelated Deposit/Withdraw txs). - const escrowAddress = getContractAddress(network, 'Escrow') + // Only query escrow events from the known Escrow contract address (EnterpriseEscrow on + // enterprise nodes). When it is not deployed on this chain the escrow processor would + // drop every event anyway, so we skip the query entirely (this also avoids logging + // unrelated Deposit/Withdraw txs). + const escrowAddress = getEscrowAddressForChain(network, isEnterprise) if (escrowAddress) { queries.push( provider.getLogs({ diff --git a/src/components/core/admin/pushConfigHandler.ts b/src/components/core/admin/pushConfigHandler.ts index f95bb1b20..06f86f7f0 100644 --- a/src/components/core/admin/pushConfigHandler.ts +++ b/src/components/core/admin/pushConfigHandler.ts @@ -28,7 +28,15 @@ export class PushConfigHandler extends AdminCommandHandler { const currentConfig = this.getOceanNode().getConfig() const mergedConfig = { ...currentConfig, ...command.config } - OceanNodeConfigSchema.parse(mergedConfig) + const parsedConfig = OceanNodeConfigSchema.parse(mergedConfig) + // isEnterprise picks the escrow contract. Core would switch on reload, but the running + // indexers keep tracking the old one, and jobs locked on it would be claimed on the new + // one, so it only changes with a restart. + if (Boolean(parsedConfig.isEnterprise) !== Boolean(currentConfig.isEnterprise)) { + return buildInvalidRequestMessage( + 'isEnterprise cannot be changed at runtime; update the config and restart the node' + ) + } } catch (error) { if (error.name === 'ZodError') { const issues = error.issues @@ -56,6 +64,7 @@ export class PushConfigHandler extends AdminCommandHandler { const currentConfig = JSON.parse(configContent) const mergedConfig = { ...currentConfig, ...task.config } + mergedConfig.isEnterprise = this.getOceanNode().getConfig().isEnterprise // a client that echoed an older pushConfig response back may have saved `over` - a // copy of the raw private key - into the file; this write drops it delete mergedConfig.over diff --git a/src/components/core/utils/escrow.ts b/src/components/core/utils/escrow.ts index f401f30a5..5c9f15810 100644 --- a/src/components/core/utils/escrow.ts +++ b/src/components/core/utils/escrow.ts @@ -2,7 +2,7 @@ import { Blockchain, getDatatokenDecimals } from '../../../utils/blockchain.js' import { ethers, parseUnits, formatUnits, BigNumberish } from 'ethers' import EscrowJson from '@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json' with { type: 'json' } import { EscrowAuthorization, EscrowLock } from '../../../@types/Escrow.js' -import { getOceanArtifactsAdressesByChainId } from '../../../utils/address.js' +import { getEscrowAddressForChain } from '../../../utils/address.js' import { RPCS } from '../../../@types/blockchain.js' import { AccessListContract } from '../../../@types/OceanNode.js' import { JobType, ZERO_PAYMENT_TX, isZeroPaymentTx } from '../../../utils/constants.js' @@ -30,19 +30,23 @@ export class Escrow { private escrowEmptyTx: boolean /** Cache for token decimals to avoid repeated blockchain calls */ private decimalsCache: Map = new Map() + /** Enterprise nodes pay/claim through EnterpriseEscrow instead of Escrow. */ + private isEnterprise: boolean constructor( supportedNetworks: RPCS, claimDurationTimeout: number, blockchainRegistry: BlockchainRegistry, subsidyProviders: AccessListContract | null = null, - escrowEmptyTx: boolean = false + escrowEmptyTx: boolean = false, + isEnterprise: boolean = false ) { this.networks = supportedNetworks this.claimDurationTimeout = claimDurationTimeout this.blockchainRegistry = blockchainRegistry this.subsidyProviders = subsidyProviders this.escrowEmptyTx = escrowEmptyTx + this.isEnterprise = isEnterprise } /** @@ -54,9 +58,7 @@ export class Escrow { } getEscrowContractAddressForChain(chainId: number): string | null { - const addresses = getOceanArtifactsAdressesByChainId(chainId) - if (addresses && addresses.Escrow) return addresses.Escrow - return null + return getEscrowAddressForChain(chainId, this.isEnterprise) } getMinLockTime(maxJobDuration: number) { diff --git a/src/test/unit/config.test.ts b/src/test/unit/config.test.ts index ba08b7538..a95920b1c 100644 --- a/src/test/unit/config.test.ts +++ b/src/test/unit/config.test.ts @@ -486,6 +486,49 @@ describe('Should validate SUBSIDY_PROVIDER_FILTER configuration', () => { }) }) +describe('Should validate IS_ENTERPRISE configuration', () => { + const DB_ENV_VARS = [ENVIRONMENT_VARIABLES.DB_TYPE, ENVIRONMENT_VARIABLES.DB_URL] + const DB_ENV_VALUES = ['typesense', 'http://localhost:8108/?apiKey=xyz'] + + // IS_ENTERPRISE is always overridden, so a value inherited from the test process can not + // leak in: undefined is stored as the string 'undefined', which the config builder treats + // as unset + async function configWith( + isEnterprise?: string + ): Promise<{ config?: OceanNodeConfig; error?: Error }> { + const overrides = buildEnvOverrideConfig( + [...DB_ENV_VARS, ENVIRONMENT_VARIABLES.IS_ENTERPRISE], + [...DB_ENV_VALUES, isEnterprise] + ) + try { + await setupEnvironment(TEST_ENV_CONFIG_PATH, overrides) + return { config: await getConfiguration(true) } + } catch (error) { + return { error } + } finally { + await tearDownEnvironment(overrides) + } + } + + it('defaults to false when unset', async () => { + const { config: conf, error } = await configWith() + expect(error).to.be.equal(undefined) + expect(conf.isEnterprise).to.be.equal(false) + }) + + it('parses "true" as true', async () => { + const { config: conf, error } = await configWith('true') + expect(error).to.be.equal(undefined) + expect(conf.isEnterprise).to.be.equal(true) + }) + + after(() => { + delete process.env.CONFIG_PATH + delete process.env.PRIVATE_KEY + delete process.env[ENVIRONMENT_VARIABLES.IS_ENTERPRISE.name] + }) +}) + describe('Should validate persistent storage bucket sharing configuration', () => { const PERSISTENT_STORAGE_JSON = JSON.stringify({ enabled: true, diff --git a/src/test/unit/escrowAddress.test.ts b/src/test/unit/escrowAddress.test.ts new file mode 100644 index 000000000..6d34f298f --- /dev/null +++ b/src/test/unit/escrowAddress.test.ts @@ -0,0 +1,93 @@ +import { expect } from 'chai' +import { ethers } from 'ethers' +import { getEscrowAddressForChain } from '../../utils/address.js' +import { Escrow } from '../../components/core/utils/escrow.js' +import { retrieveChunkEvents } from '../../components/Indexer/utils.js' +// processor.js first: importing a processor module directly trips the processors' import cycle +import '../../components/Indexer/processor.js' +import { EscrowEventProcessor } from '../../components/Indexer/processors/EscrowEventProcessor.js' +import { OceanNodeConfig } from '../../@types/OceanNode.js' + +// Addresses from the bundled ocean-contracts address file. +// Optimism: both Escrow and EnterpriseEscrow are deployed. +const CHAIN_WITH_ENTERPRISE = 10 +const ESCROW_ON_OPTIMISM = '0x9497d1d64F2aFeBcd4f9916Eef3d9094E5Df962f' +const ENTERPRISE_ESCROW_ON_OPTIMISM = '0x7b0576CF01E868bce46cca91b2a8E674141b0355' +// Base: only Escrow is deployed. +const CHAIN_WITHOUT_ENTERPRISE = 8453 +const ESCROW_ON_BASE = '0x09c9a4010E106b9673DcD58AB021a2C84457f323' +const UNKNOWN_CHAIN = 999999999 + +describe('Escrow contract selection (IS_ENTERPRISE)', () => { + describe('getEscrowAddressForChain', () => { + it('returns Escrow when not enterprise, even where EnterpriseEscrow is deployed', () => { + expect(getEscrowAddressForChain(CHAIN_WITH_ENTERPRISE)).to.equal(ESCROW_ON_OPTIMISM) + expect(getEscrowAddressForChain(CHAIN_WITH_ENTERPRISE, false)).to.equal( + ESCROW_ON_OPTIMISM + ) + }) + + it('returns EnterpriseEscrow for an enterprise node', () => { + expect(getEscrowAddressForChain(CHAIN_WITH_ENTERPRISE, true)).to.equal( + ENTERPRISE_ESCROW_ON_OPTIMISM + ) + }) + + it('falls back to Escrow for an enterprise node where EnterpriseEscrow is missing', () => { + expect(getEscrowAddressForChain(CHAIN_WITHOUT_ENTERPRISE, true)).to.equal( + ESCROW_ON_BASE + ) + }) + + it('returns null on a chain without any escrow', () => { + expect(getEscrowAddressForChain(UNKNOWN_CHAIN)).to.equal(null) + expect(getEscrowAddressForChain(UNKNOWN_CHAIN, true)).to.equal(null) + }) + }) + + it('core Escrow pays through the contract matching the toggle', () => { + const community = new Escrow({} as any, 3600, {} as any, null) + const enterprise = new Escrow({} as any, 3600, {} as any, null, false, true) + expect(community.getEscrowContractAddressForChain(CHAIN_WITH_ENTERPRISE)).to.equal( + ESCROW_ON_OPTIMISM + ) + expect(enterprise.getEscrowContractAddressForChain(CHAIN_WITH_ENTERPRISE)).to.equal( + ENTERPRISE_ESCROW_ON_OPTIMISM + ) + }) + + it('indexer escrow processor tracks the same contract as core Escrow', () => { + const processorAddress = (isEnterprise: boolean) => + ( + new EscrowEventProcessor(CHAIN_WITH_ENTERPRISE, { + isEnterprise + } as OceanNodeConfig) as any + ).escrowAddress + expect(processorAddress(false)).to.equal(ESCROW_ON_OPTIMISM) + expect(processorAddress(true)).to.equal(ENTERPRISE_ESCROW_ON_OPTIMISM) + }) + + it('indexer chunk query address-filters escrow events on EnterpriseEscrow', async () => { + const calls: any[] = [] + const provider = { + getLogs: (filter: any): Promise => { + calls.push(filter) + return Promise.resolve([]) + } + } + await retrieveChunkEvents(null as any, provider as any, CHAIN_WITH_ENTERPRISE, 0, 10) + await retrieveChunkEvents( + null as any, + provider as any, + CHAIN_WITH_ENTERPRISE, + 0, + 10, + true + ) + const escrowFilters = calls.filter((c) => c.address !== undefined) + expect(escrowFilters.map((c) => c.address)).to.deep.equal([ + ESCROW_ON_OPTIMISM, + ENTERPRISE_ESCROW_ON_OPTIMISM + ]) + }) +}) diff --git a/src/test/unit/pushConfigPrivateKey.test.ts b/src/test/unit/pushConfigPrivateKey.test.ts index f0dd7252d..b7d029d0e 100644 --- a/src/test/unit/pushConfigPrivateKey.test.ts +++ b/src/test/unit/pushConfigPrivateKey.test.ts @@ -141,3 +141,30 @@ describe('pushConfig / fetchConfig never return the private key', () => { expect(answer.keys.privateKey).to.equal(HIDDEN) }) }) + +describe('pushConfig rejects runtime isEnterprise changes', () => { + let node: OceanNode + + before(async () => { + const config = await getConfiguration(true) + node = fakeOceanNode({ ...config, isEnterprise: false }) + }) + + it('rejects switching isEnterprise', async () => { + const response = await new PushConfigHandler(node).handle({ + ...signedCommand(PROTOCOL_COMMANDS.PUSH_CONFIG), + config: { isEnterprise: true } + }) + expect(response.status.httpStatus).to.equal(400) + expect(response.status.error).to.include('isEnterprise cannot be changed at runtime') + expect(node.getConfig().isEnterprise).to.equal(false) + }) + + it('accepts isEnterprise when it is unchanged', async () => { + const validation = await new PushConfigHandler(node).validate({ + ...signedCommand(PROTOCOL_COMMANDS.PUSH_CONFIG), + config: { isEnterprise: 'false' } + }) + expect(validation.valid).to.equal(true) + }) +}) diff --git a/src/utils/address.ts b/src/utils/address.ts index 140bf4876..b5e0ec62c 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -67,6 +67,32 @@ export function getOceanTokenAddressForChain(chainId: number): string | null { return null } +/** + * Escrow contract the node pays/claims through and whose events the indexer tracks. + * Enterprise nodes use EnterpriseEscrow (same events/ABI as Escrow, plus the enterprise + * network fee), falling back to Escrow on chains where EnterpriseEscrow is not deployed. + * Core and Indexer must resolve it through here so they never disagree. + * @returns address as found in the address file, or null + */ +export function getEscrowAddressForChain( + chainId: number, + isEnterprise: boolean = false +): string | null { + const addresses = getOceanArtifactsAdressesByChainId(chainId) + if (!addresses) return null + if (isEnterprise) { + if (addresses.EnterpriseEscrow) return addresses.EnterpriseEscrow + if (addresses.Escrow) { + CORE_LOGGER.throttled( + `enterpriseEscrow:${chainId}`, + LOG_LEVELS_STR.LEVEL_WARN, + `EnterpriseEscrow is not deployed on chain ${chainId}; enterprise node falls back to Escrow` + ) + } + } + return addresses.Escrow || null +} + // default token addresses per chain export const OCEAN_ARTIFACTS_ADDRESSES_PER_CHAIN = addresses export const DEVELOPMENT_CHAIN_ID = 8996 diff --git a/src/utils/config/constants.ts b/src/utils/config/constants.ts index 74af7c4eb..e44a3298b 100644 --- a/src/utils/config/constants.ts +++ b/src/utils/config/constants.ts @@ -25,6 +25,7 @@ export const ENV_TO_CONFIG_MAPPING = { FILEINFO_ALLOWED_HEADERS: 'fileInfoAllowedHeaders', FILEINFO_MAX_REQ_PER_MINUTE: 'fileInfoRateLimit', IS_BOOTSTRAP: 'isBootstrap', + IS_ENTERPRISE: 'isEnterprise', ESCROW_CLAIM_TIMEOUT: 'claimDurationTimeout', ESCROW_EMPTY_TX: 'escrowEmptyTx', VALIDATE_UNSIGNED_DDO: 'validateUnsignedDDO', diff --git a/src/utils/config/schemas.ts b/src/utils/config/schemas.ts index 029e74b79..e9bbdf3d2 100644 --- a/src/utils/config/schemas.ts +++ b/src/utils/config/schemas.ts @@ -1748,6 +1748,7 @@ export const OceanNodeConfigSchema = z // (separate bucket). 0 = disabled. A negative/non-numeric value fails validation. fileInfoRateLimit: z.coerce.number().int().min(0).optional().default(0), isBootstrap: booleanFromString.optional().default(false), + isEnterprise: booleanFromString.optional().default(false), validateUnsignedDDO: booleanFromString.optional().default(true), jwtSecret: z.string(), httpCertPath: z.string().optional(), diff --git a/src/utils/constants.ts b/src/utils/constants.ts index ea96561fd..c1b4a5c75 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -779,6 +779,11 @@ export const ENVIRONMENT_VARIABLES: Record = { value: process.env.IS_BOOTSTRAP, required: false }, + IS_ENTERPRISE: { + name: 'IS_ENTERPRISE', + value: process.env.IS_ENTERPRISE, + required: false + }, ESCROW_EMPTY_TX: { name: 'ESCROW_EMPTY_TX', value: process.env.ESCROW_EMPTY_TX,