Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 3x 3x 3x 45x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | // SPDX-License-Identifier: Apache-2.0
import semver from'semver';
import shell from 'shelljs';
import { configDotenv } from 'dotenv';
import { readFileSync, writeFileSync } from 'fs';
import path, { join } from 'path';
import yaml from 'js-yaml';
import { LoggerService } from '../services/LoggerService';
import { ServiceLocator } from '../services/ServiceLocator';
import { IState } from './IState';
import { CLIService } from '../services/CLIService';
import { CLIOptions } from '../types/CLIOptions';
import { FileSystemUtils } from '../utils/FileSystemUtils';
import { IOBserver } from '../controller/IObserver';
import { EventType } from '../types/EventType';
import { ConfigurationData } from '../data/ConfigurationData';
import { Configuration } from '../types/NetworkConfiguration';
import originalNodeConfiguration from '../configuration/originalNodeConfiguration.json';
import { DockerService } from '../services/DockerService';
import {
APPLICATION_YML_RELATIVE_PATH,
CHECK_SUCCESS,
INIT_STATE_BOOTSTRAPPED_PROP_SET,
INIT_STATE_CONFIGURING_ENV_VARIABLES_FINISH,
INIT_STATE_INIT_MESSAGE,
INIT_STATE_MIRROR_PROP_SET,
INIT_STATE_NO_ENV_VAR_CONFIGURED,
INIT_STATE_NO_NODE_CONF_NEEDED,
INIT_STATE_RELAY_LIMITS_DISABLED,
INIT_STATE_START_DOCKER_CHECK,
INIT_STATE_STARTING_MESSAGE,
LOADING,
NECESSARY_PORTS,
NETWORK_NODE_CONFIG_DIR_PATH,
NGINX_CONFIG_RELATIVE_PATH,
OPTIONAL_PORTS
} from '../constants';
import os from 'os';
import packageJson from '../../package.json';
import { VerboseLevel } from '../types/VerboseLevel';
configDotenv({ path: path.resolve(__dirname, '../../.env') });
interface PackageMeta {
version: string;
}
const LOCAL_NODE_VERSION: string = (packageJson as PackageMeta).version;
/**
* Represents the initialization state of the application.
* This state is responsible for setting up the necessary environment variables,
* configuring node properties, and mirror node properties based on the selected configuration.
*/
export class InitState implements IState{
/**
* The logger service used for logging messages.
*/
private logger: LoggerService;
/**
* The observer for the InitState.
*/
private observer: IOBserver | undefined;
/**
* The CLI options for the initialization state.
*/
private cliOptions: CLIOptions;
/**
* Represents the Docker service used by the InitState class.
*/
private dockerService: DockerService;
/**
* The name of the state.
*/
private stateName: string;
/**
* Initializes a new instance of the InitState class.
*/
constructor() {
this.stateName = InitState.name;
this.logger = ServiceLocator.Current.get<LoggerService>(LoggerService.name);
this.cliOptions = ServiceLocator.Current.get<CLIService>(CLIService.name).getCurrentArgv();
this.dockerService = ServiceLocator.Current.get<DockerService>(DockerService.name);
this.logger.trace(INIT_STATE_INIT_MESSAGE, this.stateName);
}
/**
* Subscribes an observer to the state.
*
* @param {IOBserver} observer - The observer to subscribe.
*/
public subscribe(observer: IOBserver): void {
this.observer = observer;
}
/**
* Called when the state is started.
* @returns {Promise<void>} A promise that resolves when the state has started.
*/
public async onStart(): Promise<void> {
this.printLogoAndVersion();
this.logger.trace(INIT_STATE_STARTING_MESSAGE, this.stateName);
const configurationData = ConfigurationData.getInstance();
// Check if docker is running and it's the correct version
this.logger.info(INIT_STATE_START_DOCKER_CHECK, this.stateName);
const isCorrectDockerComposeVersion = await this.dockerService.isCorrectDockerComposeVersion();
const isDockerStarted = await this.dockerService.checkDocker();
const dockerHasEnoughResources = await this.dockerService.checkDockerResources(this.cliOptions.multiNode);
const areNodeAndNpmVersionsValid = this.checkNodeAndNpmVersions();
if (!(isCorrectDockerComposeVersion && isDockerStarted && dockerHasEnoughResources) && areNodeAndNpmVersionsValid) {
this.observer!.update(EventType.UnresolvableError);
return;
}
await this.dockerService.isPortInUse(NECESSARY_PORTS.concat(OPTIONAL_PORTS));
this.logger.info(`${LOADING} Setting configuration with latest images on host ${this.cliOptions.host} with dev mode turned ${this.cliOptions.devMode ? 'on' : 'off'} using ${this.cliOptions.fullMode? 'full': 'turbo'} mode in ${this.cliOptions.multiNode? 'multi' : 'single'} node configuration...`, this.stateName);
this.prepareWorkDirectory();
const workDirConfiguration = [
{ key: 'NETWORK_NODE_LOGS_ROOT_PATH', value: join(this.cliOptions.workDir, 'network-logs', 'node') },
{ key: 'APPLICATION_CONFIG_PATH', value: join(this.cliOptions.workDir, 'compose-network', 'network-node', 'data', 'config') },
{ key: 'MIRROR_NODE_CONFIG_PATH', value: this.cliOptions.workDir },
];
configurationData.envConfiguration = (configurationData.envConfiguration ?? []).concat(workDirConfiguration);
this.configureEnvVariables(configurationData.imageTagConfiguration, configurationData.envConfiguration);
this.configureNodeProperties(configurationData.nodeConfiguration?.properties);
this.configureMirrorNodeProperties();
await this.setupNginxProxyConfig();
this.observer!.update(EventType.Finish);
}
private checkNodeAndNpmVersions(): boolean {
const MIN_NODE_VERSION = '17.9.1';
const MIN_NPM_VERSION = '8.11.0';
const V_OR_NEW_LINE_REGEX = /v|\n/g;
const nodeVersion = shell.exec(`node -v `, { silent: true }).replace(V_OR_NEW_LINE_REGEX, '');
const npmVersion = shell.exec(`npm -v `, { silent: true }).replace(V_OR_NEW_LINE_REGEX, '');
const isNodeVersionValid = semver.gte(nodeVersion, MIN_NODE_VERSION);
const isNpmVersionValid = semver.gte(npmVersion, MIN_NPM_VERSION);
Iif (!isNodeVersionValid) {
this.logger.error(`Current node version is ${nodeVersion} but minimum required one is ${MIN_NODE_VERSION}`);
}
Iif (!isNpmVersionValid) {
this.logger.error(`Current npm version is ${npmVersion} but minimum required one is ${MIN_NPM_VERSION}`);
}
return isNodeVersionValid && isNpmVersionValid;
}
/**
* Prepares the work directory.
*
* This method logs the path to the work directory, creates ephemeral directories in the work directory, and defines the source paths for the config directory, the mirror node application YAML file, and the record parser.
* It creates a map of the source paths to the destination paths in the work directory and copies the files from the source paths to the destination paths.
*
* @private
* @returns {void}
*/
private prepareWorkDirectory() {
this.logger.trace(`${CHECK_SUCCESS} Local Node Working directory set to ${this.cliOptions.workDir}.`, this.stateName);
FileSystemUtils.createEphemeralDirectories(this.cliOptions.workDir);
const configDirSource = join(__dirname, `../../${NETWORK_NODE_CONFIG_DIR_PATH}`);
const configPathMirrorNodeSource = join(__dirname, `../../${APPLICATION_YML_RELATIVE_PATH}`);
const configFiles = {
[configDirSource]: `${this.cliOptions.workDir}/${NETWORK_NODE_CONFIG_DIR_PATH}`,
[configPathMirrorNodeSource]: `${this.cliOptions.workDir}/${APPLICATION_YML_RELATIVE_PATH}`,
};
FileSystemUtils.copyPaths(configFiles);
}
/**
* Configures the environment variables based on the selected configuration.
* @param {Array<Configuration>} imageTagConfiguration - The image tag configuration.
* @param {Array<Configuration> | undefined} envConfiguration - The environment variable configuration.
*/
private configureEnvVariables(imageTagConfiguration: Array<Configuration>, envConfiguration: Array<Configuration> | undefined): void {
imageTagConfiguration.forEach(variable => {
const { tag, node } = this.extractImageTag(variable);
this.logger.trace(`Environment variable ${node} will be set to ${tag}.`, this.stateName);
process.env[node] = tag;
});
if (!envConfiguration) {
this.logger.trace(INIT_STATE_NO_ENV_VAR_CONFIGURED, this.stateName);
return;
}
envConfiguration!.forEach(variable => {
process.env[variable.key] = variable.value;
this.logger.trace(`Environment variable ${variable.key} will be set to ${variable.value}.`, this.stateName);
});
const relayLimitsDisabled = !this.cliOptions.limits;
if (relayLimitsDisabled) {
process.env.RELAY_HBAR_RATE_LIMIT_TINYBAR = '0';
process.env.RELAY_HBAR_RATE_LIMIT_DURATION = '0';
process.env.RELAY_RATE_LIMIT_DISABLED = `${relayLimitsDisabled}`;
this.logger.info(INIT_STATE_RELAY_LIMITS_DISABLED, this.stateName);
}
this.logger.trace(INIT_STATE_CONFIGURING_ENV_VARIABLES_FINISH, this.stateName);
// workaround for broken Java (21 to 23) on Apple Silicon M3/M4 chipsets under MacOS Sequoia when running inside docker
// darwin release history can be found here https://en.wikipedia.org/wiki/Darwin_(operating_system)#Release_history
Iif (os.platform() === "darwin" && os.release().slice(0, 2) === "24") {
process.env.PLATFORM_JAVA_OPTS = "-XX:+UnlockExperimentalVMOptions -XX:UseSVE=0 -XX:+UseZGC -Xlog:gc*:gc.log";
process.env.GRPC_PLATFORM_JAVA_OPTS = "-XX:UseSVE=0";
}
}
/**
* Extracts the image tag from the configuration.
*
* @private
* @param {Configuration} variable - The configuration.
* @returns {string} The extracted image tag.
*/
private extractImageTag(variable: Configuration): {
tag: string,
node: string
} {
const node = variable.key;
let tag = process.env[node] ?? variable.value;
switch (node) {
case "NETWORK_NODE_IMAGE_TAG":
case "HAVEGED_IMAGE_TAG":
if (this.cliOptions.networkTag) {
tag = this.cliOptions.networkTag;
}
break;
case "MIRROR_IMAGE_TAG":
if (this.cliOptions.mirrorTag) {
tag = this.cliOptions.mirrorTag;
}
break;
case "RELAY_IMAGE_TAG":
if (this.cliOptions.relayTag) {
tag = this.cliOptions.relayTag;
}
break;
case "BLOCK_NODE_IMAGE_TAG":
Iif (this.cliOptions.blockNodeTag) {
tag = this.cliOptions.blockNodeTag;
}
break;
}
return {
tag,
node
}
}
/**
* Configures the node properties based on the selected configuration.
* @param {Array<Configuration> | undefined} nodeConfiguration - The node configuration.
*/
private configureNodeProperties(nodeConfiguration: Array<Configuration> | undefined): void {
const propertiesFiles = ['bootstrap.properties', 'application.properties']
for (let index = 0; index < propertiesFiles.length; index++) {
const propertiesFilePath = join(this.cliOptions.workDir, NETWORK_NODE_CONFIG_DIR_PATH, propertiesFiles[index]);
let newProperties = '';
originalNodeConfiguration.bootsrapProperties.forEach(property => {
newProperties = newProperties.concat(`${property.key}=${property.value}\n`);
});
if (!nodeConfiguration) {
this.logger.trace(INIT_STATE_NO_NODE_CONF_NEEDED, this.stateName);
return;
}
nodeConfiguration!.forEach(property => {
newProperties = newProperties.concat(`${property.key}=${property.value}\n`);
this.logger.trace(`Bootstrap property ${property.key} will be set to ${property.value}.`, this.stateName);
});
Iif (this.cliOptions.blockNode) {
newProperties = newProperties.concat(`blockStream.writerMode=FILE_AND_GRPC\n`);
this.logger.trace(`Bootstrap property blockStream.writerMode will be set to FILE_AND_GRPC.`, this.stateName);
}
writeFileSync(propertiesFilePath, newProperties, { flag: 'w' });
this.logger.trace(INIT_STATE_BOOTSTRAPPED_PROP_SET, this.stateName);
}
}
/**
* Configures the mirror node properties.
*
* @private
*/
private configureMirrorNodeProperties(): void {
this.logger.trace('Configuring required mirror node properties, depending on selected configuration...', this.stateName);
const {fullMode, multiNode, persistTransactionBytes, workDir } = this.cliOptions;
const propertiesFilePath = join(workDir, 'compose-network/mirror-node/application.yml');
const application = yaml.load(readFileSync(propertiesFilePath).toString()) as any;
Iif (!fullMode) {
application.hedera.mirror.importer.dataPath = originalNodeConfiguration.turboNodeProperties.dataPath;
application.hedera.mirror.importer.downloader.sources = originalNodeConfiguration.turboNodeProperties.sources;
}
if (multiNode) {
application.hedera.mirror.monitor.nodes = originalNodeConfiguration.multiNodeProperties;
process.env.RELAY_HEDERA_NETWORK = '{"network-node:50211":"0.0.3","network-node-1:50211":"0.0.4","network-node-2:50211":"0.0.5","network-node-3:50211":"0.0.6"}';
}
if (persistTransactionBytes) {
application.hedera.mirror.importer.parser.record.entity.persist.transactionBytes = true;
application.hedera.mirror.importer.parser.record.entity.persist.transactionRecordBytes = true;
}
writeFileSync(propertiesFilePath, yaml.dump(application, { lineWidth: 256 }));
this.logger.trace(INIT_STATE_MIRROR_PROP_SET, this.stateName);
}
/**
* Additional nginx server blocks appended to the mirror-node proxy config.
* These allow the proxy to intercept traffic on every relevant mirror node port so that
* both host-level and intra-Docker requests are routed through it uniformly.
*/
private static readonly ADDITIONAL_PROXY_SERVER_BLOCKS = `
# REST-Java direct passthrough on port 8084
server {
listen 8084;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header "Connection" "";
location / { proxy_pass http://rest_java_host$request_uri; }
}
`;
/**
* Downloads the nginx proxy config from hiero-mirror-node's docker-compose.yml on GitHub,
* extracts the proxy-config block, and writes it to the work directory.
* Falls back to the bundled config if the download or parse fails.
* Caches the result per mirror tag to avoid redundant downloads.
*
* @private
*/
private async setupNginxProxyConfig(): Promise<void> {
const mirrorTag = process.env.MIRROR_IMAGE_TAG ?? '';
const nginxDir = join(this.cliOptions.workDir, 'compose-network', 'nginx');
const configDestPath = join(this.cliOptions.workDir, NGINX_CONFIG_RELATIVE_PATH);
const cacheTagPath = join(nginxDir, '.mirror-tag');
const bundledConfigPath = join(__dirname, '../../', NGINX_CONFIG_RELATIVE_PATH);
FileSystemUtils.ensureDirectoryExists(nginxDir);
// Use cached config if the same mirror tag was already downloaded
try {
const cachedTag = readFileSync(cacheTagPath, 'utf8').trim();
Iif (cachedTag === mirrorTag) {
this.logger.trace(`${CHECK_SUCCESS} Using cached nginx proxy config for mirror-node v${mirrorTag}.`, this.stateName);
return;
}
} catch {
// Cache miss — proceed with download
}
const url = `https://raw.githubusercontent.com/hiero-ledger/hiero-mirror-node/v${mirrorTag}/docker-compose.yml`;
this.logger.trace(`${LOADING} Fetching nginx proxy config from mirror-node v${mirrorTag}...`, this.stateName);
try {
const response = await fetch(url);
Iif (!response.ok) {
throw new Error(`GitHub returned HTTP ${response.status} for ${url}`);
}
const text = await response.text();
const parsed = yaml.load(text) as any;
const rawProxyConfig: string = parsed?.configs?.['proxy-config']?.content;
Iif (typeof rawProxyConfig !== 'string' || rawProxyConfig.trim().length === 0) {
throw new Error('proxy-config block not found or empty in mirror-node docker-compose.yml');
}
// mirror-node embeds the nginx config inside docker-compose.yml and escapes nginx variables
// as $$ so Docker Compose doesn't interpolate them. When we write the config as a standalone
// file (not processed by Docker Compose), we must unescape $$ back to $.
// We also rewrite the listen port from 8080 (mirror-node default) to 5551, and append
// additional server blocks so the proxy handles all internal/external traffic on every
// relevant mirror node port.
const proxyConfig = rawProxyConfig.replace(/\$\$/g, '$').replace(/\blisten\s+8080\b/g, 'listen 5551')
+ InitState.ADDITIONAL_PROXY_SERVER_BLOCKS;
writeFileSync(configDestPath, proxyConfig);
writeFileSync(cacheTagPath, mirrorTag);
this.logger.trace(`${CHECK_SUCCESS} nginx proxy config fetched and cached for mirror-node v${mirrorTag}.`, this.stateName);
} catch (err: any) {
this.logger.warn(`${CHECK_SUCCESS} Could not fetch nginx proxy config from GitHub (${err?.message ?? err}). Using bundled fallback.`, this.stateName);
const fallback = readFileSync(bundledConfigPath, 'utf8');
writeFileSync(configDestPath, fallback);
}
}
/**
* Prints the Hiero Local-Node logo and version information.
* @private
*/
private printLogoAndVersion(): void {
const logo = `
██╗ ██╗██╗███████╗██████╗ ██████╗
██║ ██║██║██╔════╝██╔══██╗██╔═══██╗
███████║██║█████╗ ██████╔╝██║ ██║
██╔══██║██║██╔══╝ ██╔══██╗██║ ██║
██║ ██║██║███████╗██║ ██║╚██████╔╝
╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝
██╗ ██████╗ ██████╗ █████╗ ██╗ ███╗ ██╗ ██████╗ ██████╗ ███████╗
██║ ██╔═══██╗██╔════╝██╔══██╗██║ ████╗ ██║██╔═══██╗██╔══██╗██╔════╝
██║ ██║ ██║██║ ███████║██║ ██╔██╗ ██║██║ ██║██║ ██║█████╗
██║ ██║ ██║██║ ██╔══██║██║ ██║╚██╗██║██║ ██║██║ ██║██╔══╝
███████╗╚██████╔╝╚██████╗██║ ██║███████╗ ██║ ╚████║╚██████╔╝██████╔╝███████╗
╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝
`;
const versionInfo = ` Local-Node Version: ${LOCAL_NODE_VERSION}`;
const divider = ` ─────────────────────────────────────────────`;
const nodesVersionDivider = `
${divider}
Hiero Nodes Version
${divider}`;
const configurationData = ConfigurationData.getInstance();
const nodeVersions = configurationData.imageTagConfiguration
.reduce((acc, variable) => {
const { tag, node } = this.extractImageTag(variable);
let nodeName = '';
switch (node) {
case "NETWORK_NODE_IMAGE_TAG":
nodeName = "Consensus Node";
break;
case "MIRROR_IMAGE_TAG":
nodeName = "Mirror Node";
break;
case "RELAY_IMAGE_TAG":
nodeName = "Relay";
break;
case "BLOCK_NODE_IMAGE_TAG":
nodeName = "Block Node";
break;
case "MIRROR_NODE_EXPLORER_IMAGE_TAG":
nodeName = "Mirror Node Explorer";
break;
default:
return acc;
}
// Only add if we haven't seen this node type before
Iif (!acc.some(item => item.startsWith(nodeName))) {
acc.push(` ${nodeName} Version: ${tag}`);
}
return acc;
}, [] as Array<string>)
.join('\n');
const configStatusDivider = `
${divider}
Configuration Status
${divider}`;
const configStatus = [
` Node Configuration: ${this.cliOptions.multiNode ? 'Multi' : 'Single'} Node`,
` Block Node: ${this.cliOptions.blockNode ? 'Enabled' : 'Disabled'}`,
` Host: ${this.cliOptions.host}`,
` Verbose Level: ${VerboseLevel[this.cliOptions.verbose]}`
].join('\n');
console.log(logo);
console.log(versionInfo);
console.log(nodesVersionDivider);
console.log(nodeVersions);
console.log(divider);
console.log(configStatusDivider);
console.log(configStatus);
console.log(divider);
console.log();
}
}
|