@hashgraph/hedera-local
Version:
Developer tooling for running Local Hedera Network (Consensus + Mirror Nodes).
369 lines (368 loc) • 20.7 kB
JavaScript
"use strict";
// SPDX-License-Identifier: Apache-2.0
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InitState = void 0;
const semver_1 = __importDefault(require("semver"));
const shelljs_1 = __importDefault(require("shelljs"));
const dotenv_1 = require("dotenv");
const fs_1 = require("fs");
const path_1 = __importStar(require("path"));
const js_yaml_1 = __importDefault(require("js-yaml"));
const LoggerService_1 = require("../services/LoggerService");
const ServiceLocator_1 = require("../services/ServiceLocator");
const CLIService_1 = require("../services/CLIService");
const FileSystemUtils_1 = require("../utils/FileSystemUtils");
const EventType_1 = require("../types/EventType");
const ConfigurationData_1 = require("../data/ConfigurationData");
const originalNodeConfiguration_json_1 = __importDefault(require("../configuration/originalNodeConfiguration.json"));
const DockerService_1 = require("../services/DockerService");
const constants_1 = require("../constants");
const os_1 = __importDefault(require("os"));
const package_json_1 = __importDefault(require("../../package.json"));
const VerboseLevel_1 = require("../types/VerboseLevel");
(0, dotenv_1.configDotenv)({ path: path_1.default.resolve(__dirname, '../../.env') });
const LOCAL_NODE_VERSION = package_json_1.default.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.
*/
class InitState {
/**
* Initializes a new instance of the InitState class.
*/
constructor() {
this.stateName = InitState.name;
this.logger = ServiceLocator_1.ServiceLocator.Current.get(LoggerService_1.LoggerService.name);
this.cliOptions = ServiceLocator_1.ServiceLocator.Current.get(CLIService_1.CLIService.name).getCurrentArgv();
this.dockerService = ServiceLocator_1.ServiceLocator.Current.get(DockerService_1.DockerService.name);
this.logger.trace(constants_1.INIT_STATE_INIT_MESSAGE, this.stateName);
}
/**
* Subscribes an observer to the state.
*
* @param {IOBserver} observer - The observer to subscribe.
*/
subscribe(observer) {
this.observer = observer;
}
/**
* Called when the state is started.
* @returns {Promise<void>} A promise that resolves when the state has started.
*/
onStart() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
this.printLogoAndVersion();
this.logger.trace(constants_1.INIT_STATE_STARTING_MESSAGE, this.stateName);
const configurationData = ConfigurationData_1.ConfigurationData.getInstance();
// Check if docker is running and it's the correct version
this.logger.info(constants_1.INIT_STATE_START_DOCKER_CHECK, this.stateName);
const isCorrectDockerComposeVersion = yield this.dockerService.isCorrectDockerComposeVersion();
const isDockerStarted = yield this.dockerService.checkDocker();
const dockerHasEnoughResources = yield this.dockerService.checkDockerResources(this.cliOptions.multiNode);
const areNodeAndNpmVersionsValid = this.checkNodeAndNpmVersions();
if (!(isCorrectDockerComposeVersion && isDockerStarted && dockerHasEnoughResources) && areNodeAndNpmVersionsValid) {
this.observer.update(EventType_1.EventType.UnresolvableError);
return;
}
yield this.dockerService.isPortInUse(constants_1.NECESSARY_PORTS.concat(constants_1.OPTIONAL_PORTS));
this.logger.info(`${constants_1.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: (0, path_1.join)(this.cliOptions.workDir, 'network-logs', 'node') },
{ key: 'APPLICATION_CONFIG_PATH', value: (0, path_1.join)(this.cliOptions.workDir, 'compose-network', 'network-node', 'data', 'config') },
{ key: 'MIRROR_NODE_CONFIG_PATH', value: this.cliOptions.workDir },
];
configurationData.envConfiguration = ((_a = configurationData.envConfiguration) !== null && _a !== void 0 ? _a : []).concat(workDirConfiguration);
this.configureEnvVariables(configurationData.imageTagConfiguration, configurationData.envConfiguration);
this.configureNodeProperties((_b = configurationData.nodeConfiguration) === null || _b === void 0 ? void 0 : _b.properties);
this.configureMirrorNodeProperties();
this.observer.update(EventType_1.EventType.Finish);
});
}
checkNodeAndNpmVersions() {
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 = shelljs_1.default.exec(`node -v `, { silent: true }).replace(V_OR_NEW_LINE_REGEX, '');
const npmVersion = shelljs_1.default.exec(`npm -v `, { silent: true }).replace(V_OR_NEW_LINE_REGEX, '');
const isNodeVersionValid = semver_1.default.gte(nodeVersion, MIN_NODE_VERSION);
const isNpmVersionValid = semver_1.default.gte(npmVersion, MIN_NPM_VERSION);
if (!isNodeVersionValid) {
this.logger.error(`Current node version is ${nodeVersion} but minimum required one is ${MIN_NODE_VERSION}`);
}
if (!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}
*/
prepareWorkDirectory() {
this.logger.trace(`${constants_1.CHECK_SUCCESS} Local Node Working directory set to ${this.cliOptions.workDir}.`, this.stateName);
FileSystemUtils_1.FileSystemUtils.createEphemeralDirectories(this.cliOptions.workDir);
const configDirSource = (0, path_1.join)(__dirname, `../../${constants_1.NETWORK_NODE_CONFIG_DIR_PATH}`);
const configPathMirrorNodeSource = (0, path_1.join)(__dirname, `../../${constants_1.APPLICATION_YML_RELATIVE_PATH}`);
const configFiles = {
[configDirSource]: `${this.cliOptions.workDir}/${constants_1.NETWORK_NODE_CONFIG_DIR_PATH}`,
[configPathMirrorNodeSource]: `${this.cliOptions.workDir}/${constants_1.APPLICATION_YML_RELATIVE_PATH}`,
};
FileSystemUtils_1.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.
*/
configureEnvVariables(imageTagConfiguration, envConfiguration) {
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(constants_1.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(constants_1.INIT_STATE_RELAY_LIMITS_DISABLED, this.stateName);
}
this.logger.trace(constants_1.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
if (os_1.default.platform() === "darwin" && os_1.default.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.
*/
extractImageTag(variable) {
const node = variable.key;
let tag = 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":
if (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.
*/
configureNodeProperties(nodeConfiguration) {
const propertiesFiles = ['bootstrap.properties', 'application.properties'];
for (let index = 0; index < propertiesFiles.length; index++) {
const propertiesFilePath = (0, path_1.join)(this.cliOptions.workDir, constants_1.NETWORK_NODE_CONFIG_DIR_PATH, propertiesFiles[index]);
let newProperties = '';
originalNodeConfiguration_json_1.default.bootsrapProperties.forEach(property => {
newProperties = newProperties.concat(`${property.key}=${property.value}\n`);
});
if (!nodeConfiguration) {
this.logger.trace(constants_1.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);
});
if (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);
}
(0, fs_1.writeFileSync)(propertiesFilePath, newProperties, { flag: 'w' });
this.logger.trace(constants_1.INIT_STATE_BOOTSTRAPPED_PROP_SET, this.stateName);
}
}
/**
* Configures the mirror node properties.
*
* @private
*/
configureMirrorNodeProperties() {
this.logger.trace('Configuring required mirror node properties, depending on selected configuration...', this.stateName);
const { fullMode, multiNode, persistTransactionBytes, workDir } = this.cliOptions;
const propertiesFilePath = (0, path_1.join)(workDir, 'compose-network/mirror-node/application.yml');
const application = js_yaml_1.default.load((0, fs_1.readFileSync)(propertiesFilePath).toString());
if (!fullMode) {
application.hedera.mirror.importer.dataPath = originalNodeConfiguration_json_1.default.turboNodeProperties.dataPath;
application.hedera.mirror.importer.downloader.sources = originalNodeConfiguration_json_1.default.turboNodeProperties.sources;
}
if (multiNode) {
application.hedera.mirror.monitor.nodes = originalNodeConfiguration_json_1.default.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;
}
(0, fs_1.writeFileSync)(propertiesFilePath, js_yaml_1.default.dump(application, { lineWidth: 256 }));
this.logger.trace(constants_1.INIT_STATE_MIRROR_PROP_SET, this.stateName);
}
/**
* Prints the Hiero Local-Node logo and version information.
* @private
*/
printLogoAndVersion() {
const logo = `
██╗ ██╗██╗███████╗██████╗ ██████╗
██║ ██║██║██╔════╝██╔══██╗██╔═══██╗
███████║██║█████╗ ██████╔╝██║ ██║
██╔══██║██║██╔══╝ ██╔══██╗██║ ██║
██║ ██║██║███████╗██║ ██║╚██████╔╝
╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝
██╗ ██████╗ ██████╗ █████╗ ██╗ ███╗ ██╗ ██████╗ ██████╗ ███████╗
██║ ██╔═══██╗██╔════╝██╔══██╗██║ ████╗ ██║██╔═══██╗██╔══██╗██╔════╝
██║ ██║ ██║██║ ███████║██║ ██╔██╗ ██║██║ ██║██║ ██║█████╗
██║ ██║ ██║██║ ██╔══██║██║ ██║╚██╗██║██║ ██║██║ ██║██╔══╝
███████╗╚██████╔╝╚██████╗██║ ██║███████╗ ██║ ╚████║╚██████╔╝██████╔╝███████╗
╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝
`;
const versionInfo = ` Local-Node Version: ${LOCAL_NODE_VERSION}`;
const divider = ` ─────────────────────────────────────────────`;
const nodesVersionDivider = `
${divider}
Hiero Nodes Version
${divider}`;
const configurationData = ConfigurationData_1.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
if (!acc.some(item => item.startsWith(nodeName))) {
acc.push(` ${nodeName} Version: ${tag}`);
}
return acc;
}, [])
.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_1.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();
}
}
exports.InitState = InitState;
//# sourceMappingURL=InitState.js.map