Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/env.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
3 changes: 3 additions & 0 deletions src/@types/OceanNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions src/OceanNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ export class OceanNode {
this.config.claimDurationTimeout,
this.blockchainRegistry,
this.config.subsidyProviders,
this.config.escrowEmptyTx
this.config.escrowEmptyTx,
this.config.isEnterprise
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
if (this.config.persistentStorage?.enabled) {
OCEAN_NODE_LOGGER.info(
Expand Down Expand Up @@ -302,7 +303,8 @@ export class OceanNode {
this.config.claimDurationTimeout,
this.blockchainRegistry,
this.config.subsidyProviders,
this.config.escrowEmptyTx
this.config.escrowEmptyTx,
this.config.isEnterprise
Comment thread
dnsi0 marked this conversation as resolved.
Resolved
)
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/components/Indexer/ChainIndexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,8 @@ export class ChainIndexer {
provider,
this.blockchain.getSupportedChain(),
startBlock,
blocksToProcess
blocksToProcess,
this.config.isEnterprise
),
'retrieveChunkEvents'
)
Expand Down
5 changes: 3 additions & 2 deletions src/components/Indexer/processors/EscrowEventProcessor.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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(
Expand Down
17 changes: 11 additions & 6 deletions src/components/Indexer/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' }
Expand Down Expand Up @@ -105,7 +108,8 @@ export const retrieveChunkEvents = async (
provider: FallbackProvider,
network: number,
lastIndexedBlock: number,
count: number
count: number,
isEnterprise: boolean = false
): Promise<ethers.Log[]> => {
const startIndex = lastIndexedBlock + 1
const toBlock = lastIndexedBlock + count
Expand All @@ -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({
Expand Down
11 changes: 10 additions & 1 deletion src/components/core/admin/pushConfigHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Comment thread
dnsi0 marked this conversation as resolved.
Resolved
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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 7 additions & 5 deletions src/components/core/utils/escrow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -30,19 +30,23 @@ export class Escrow {
private escrowEmptyTx: boolean
/** Cache for token decimals to avoid repeated blockchain calls */
private decimalsCache: Map<string, number> = 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
}

/**
Expand All @@ -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) {
Expand Down
43 changes: 43 additions & 0 deletions src/test/unit/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment thread
dnsi0 marked this conversation as resolved.
Resolved
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,
Expand Down
93 changes: 93 additions & 0 deletions src/test/unit/escrowAddress.test.ts
Original file line number Diff line number Diff line change
@@ -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<ethers.Log[]> => {
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
])
})
})
27 changes: 27 additions & 0 deletions src/test/unit/pushConfigPrivateKey.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
26 changes: 26 additions & 0 deletions src/utils/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/utils/config/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions src/utils/config/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Loading
Loading