Skip to content
This repository has been archived by the owner on Jun 11, 2024. It is now read-only.

Commit

Permalink
Applied suggestions from code review
Browse files Browse the repository at this point in the history
  • Loading branch information
nagdahimanshu committed Sep 5, 2023
1 parent e501b9b commit 78741c5
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 58 deletions.
53 changes: 22 additions & 31 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { ApplicationConfigV3, NetworkConfigLocal, NodeInfo } from './types';
import { installLiskCore, startLiskCore } from './utils/node';
import { copyDir, resolveAbsolutePath } from './utils/fs';

let finalConfigCorev4: PartialApplicationConfig;
let configCoreV4: PartialApplicationConfig;
class LiskMigrator extends Command {
public static description = 'Migrate Lisk Core to latest version';

Expand Down Expand Up @@ -107,7 +107,7 @@ class LiskMigrator extends Command {
public async run(): Promise<void> {
try {
const { flags } = this.parse(LiskMigrator);
const liskCoreV3Path = resolveAbsolutePath(
const liskCoreV3DataPath = resolveAbsolutePath(
flags['lisk-core-v3-data-path'] ?? DEFAULT_LISK_CORE_PATH,
);
const outputPath = flags.output ?? join(__dirname, '..', 'output');
Expand All @@ -117,7 +117,7 @@ class LiskMigrator extends Command {
const autoStartLiskCoreV4 = flags['auto-start-lisk-core-v4'];
const snapshotTimeGap = Number(flags['snapshot-time-gap'] ?? SNAPSHOT_TIME_GAP);

const client = await getAPIClient(liskCoreV3Path);
const client = await getAPIClient(liskCoreV3DataPath);
const nodeInfo = (await client.node.getNodeInfo()) as NodeInfo;
const { version: appVersion, networkIdentifier } = nodeInfo;

Expand All @@ -138,7 +138,7 @@ class LiskMigrator extends Command {
cli.action.stop('Snapshot height is valid');

const networkConstant = NETWORK_CONSTANT[networkIdentifier] as NetworkConfigLocal;
const networkDir = `${outputPath}/${networkIdentifier}`;
const outputDir = `${outputPath}/${networkIdentifier}`;

if (autoStartLiskCoreV4) {
if (!networkConstant) {
Expand All @@ -164,23 +164,23 @@ class LiskMigrator extends Command {

// User specified custom config file
const configV3: ApplicationConfigV3 = customConfigPath
? await getConfig(liskCoreV3Path, customConfigPath)
: await getConfig(liskCoreV3Path);
? await getConfig(liskCoreV3DataPath, customConfigPath)
: await getConfig(liskCoreV3DataPath);

await setTokenIDLskByNetID(networkIdentifier);
await setHeightPrevSnapshotBlockByNetID(networkIdentifier);

await observeChainHeight({
label: 'Waiting for snapshot height to be finalized',
liskCoreV3Path,
liskCoreV3DataPath,
height: snapshotHeight,
delay: 500,
isFinal: true,
});

// Create new DB instance based on the snapshot path
cli.action.start('Creating database instance');
const snapshotDirPath = join(liskCoreV3Path, SNAPSHOT_DIR);
const snapshotDirPath = join(liskCoreV3DataPath, SNAPSHOT_DIR);
const db = new Database(snapshotDirPath);
cli.action.stop();

Expand All @@ -193,11 +193,11 @@ class LiskMigrator extends Command {
cli.action.stop();

// Create an app instance for creating genesis block
const configFilePath = await resolveConfigPathByNetworkID(networkIdentifier);
const configV4 = await fs.readJSON(configFilePath);
const defaultConfigFilePath = await resolveConfigPathByNetworkID(networkIdentifier);
const defaultConfigV4 = await fs.readJSON(defaultConfigFilePath);

cli.action.start(`Exporting genesis block to the path ${networkDir}`);
await writeGenesisAssets(genesisAssets, networkDir);
cli.action.start(`Exporting genesis block to the path ${outputDir}`);
await writeGenesisAssets(genesisAssets, outputDir);
cli.action.stop();

if (autoMigrateUserConfig) {
Expand All @@ -208,7 +208,7 @@ class LiskMigrator extends Command {
cli.action.start('Migrating user configuration');
const migratedConfigV4 = (await migrateUserConfig(
configV3,
configV4,
defaultConfigV4,
snapshotHeight,
)) as ApplicationConfig;
cli.action.stop();
Expand All @@ -219,12 +219,12 @@ class LiskMigrator extends Command {

if (!isValidConfig) throw new Error('Migrated user configuration is invalid.');

cli.action.start(`Exporting user configuration to the path: ${networkDir}`);
await writeConfig(migratedConfigV4, networkDir);
cli.action.start(`Exporting user configuration to the path: ${outputDir}`);
await writeConfig(migratedConfigV4, outputDir);
cli.action.stop();

// Set finalConfigCorev4 to the migrated Core config
finalConfigCorev4 = migratedConfigV4 as PartialApplicationConfig;
// Set configCoreV4 to the migrated Core config
configCoreV4 = migratedConfigV4 as PartialApplicationConfig;
}

cli.action.start('Installing lisk-core v4');
Expand All @@ -237,19 +237,17 @@ class LiskMigrator extends Command {
)) as unknown) as Block;
await createGenesisBlock(
networkConstant.name,
configFilePath,
networkDir,
defaultConfigFilePath,
outputDir,
blockAtSnapshotHeight,
snapshotTimeGap,
);
cli.action.stop();

if (autoStartLiskCoreV4) {
try {
// TODO: Verify and update the implementation
// If finalConfigCorev4 is not set to the migrated config use the default config
if (!autoMigrateUserConfig) {
finalConfigCorev4 = configV4;
configCoreV4 = defaultConfigV4;
}

cli.action.start(`Creating legacy.db at ${LEGACY_DB_PATH}`);
Expand All @@ -264,19 +262,12 @@ class LiskMigrator extends Command {
if (isLiskCoreV3Stopped) {
const isUserConfirmed = await cli.confirm(`
Start Lisk Core with the following configuration? [yes/no] \n
${util.inspect(finalConfigCorev4, false, 3)}`);
${util.inspect(configCoreV4, false, 3)}`);

if (isUserConfirmed) {
cli.action.start('Starting lisk-core v4');
const network = networkConstant.name as string;
await startLiskCore(
this,
finalConfigCorev4,
appVersion,
liskCoreV3Path,
network,
networkDir,
);
await startLiskCore(this, liskCoreV3DataPath, configCoreV4, network, outputDir);
this.log('Started Lisk Core v4 at default data directory.');
cli.action.stop();
} else {
Expand Down
10 changes: 5 additions & 5 deletions src/utils/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ let heightPreviousSnapshotBlock: number;
interface ObserveParams {
readonly label: string;
readonly height: number;
readonly liskCoreV3Path: string;
readonly liskCoreV3DataPath: string;
readonly delay: number;
readonly isFinal: boolean;
}
Expand Down Expand Up @@ -91,8 +91,8 @@ const getRemainingTime = (currentHeight: number, observedHeight: number): string
export const observeChainHeight = async (options: ObserveParams): Promise<number> => {
const observedHeight = options.height;
const startHeight = options.isFinal
? (await getNodeInfo(options.liskCoreV3Path)).finalizedHeight
: (await getNodeInfo(options.liskCoreV3Path)).height;
? (await getNodeInfo(options.liskCoreV3DataPath)).finalizedHeight
: (await getNodeInfo(options.liskCoreV3DataPath)).height;

if (startHeight >= observedHeight) {
return startHeight;
Expand Down Expand Up @@ -120,8 +120,8 @@ export const observeChainHeight = async (options: ObserveParams): Promise<number
let height!: number;
try {
height = options.isFinal
? (await getNodeInfo(options.liskCoreV3Path)).finalizedHeight
: (await getNodeInfo(options.liskCoreV3Path)).height;
? (await getNodeInfo(options.liskCoreV3DataPath)).finalizedHeight
: (await getNodeInfo(options.liskCoreV3DataPath)).height;
} catch (error) {
return reject(error);
}
Expand Down
8 changes: 4 additions & 4 deletions src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,10 +264,10 @@ export const validateConfig = async (config: ApplicationConfig): Promise<boolean
}
};

export const writeConfig = async (config: ApplicationConfig, outputPath: string): Promise<void> => {
if (!existsSync(outputPath)) {
mkdirSync(outputPath, { recursive: true });
export const writeConfig = async (config: ApplicationConfig, outputDir: string): Promise<void> => {
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}

writeFileSync(resolve(outputPath, 'config.json'), JSON.stringify(config));
writeFileSync(resolve(outputDir, 'config.json'), JSON.stringify(config));
};
20 changes: 11 additions & 9 deletions src/utils/genesis_block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,26 +45,28 @@ export const createChecksum = async (filePath: string): Promise<string> => {

export const createGenesisBlock = async (
network: string,
config: string,
output: string,
configFilepath: string,
outputDir: string,
blockAtSnapshotHeight: BlockVersion3,
snapshotTimeGap: number,
) => {
const timestamp = blockAtSnapshotHeight.header.timestamp + snapshotTimeGap;
const height = blockAtSnapshotHeight.header.height + 1;
const previousBlockID = blockAtSnapshotHeight.header.previousBlockID.toString('hex');
const genesisBlockCreateCommand = `lisk-core genesis-block:create --network ${network} --config=${config} --output=${output} --assets-file=${output}/genesis_assets.json --height=${height} --previous-block-id=${previousBlockID} --timestamp=${timestamp}`;
const timestamp = blockAtSnapshotHeight.header.timestamp + snapshotTimeGap;
const previousBlockID = blockAtSnapshotHeight.header.id.toString('hex');

const genesisBlockCreateCommand = `lisk-core genesis-block:create --network ${network} --config=${configFilepath} --output=${outputDir} --assets-file=${outputDir}/genesis_assets.json --height=${height} --previous-block-id=${previousBlockID} --timestamp=${timestamp}`;

await execAsync(genesisBlockCreateCommand);
};

export const writeGenesisAssets = async (
genesisAssets: GenesisAssetEntry[],
outputPath: string,
outputDir: string,
): Promise<void> => {
if (fs.existsSync(outputPath)) fs.rmdirSync(outputPath, { recursive: true });
fs.mkdirSync(outputPath, { recursive: true });
if (fs.existsSync(outputDir)) fs.rmdirSync(outputDir, { recursive: true });
fs.mkdirSync(outputDir, { recursive: true });

const genesisAssetsJsonFilepath = path.resolve(outputPath, 'genesis_assets.json');
const genesisAssetsJsonFilepath = path.resolve(outputDir, 'genesis_assets.json');
fs.writeFileSync(
genesisAssetsJsonFilepath,
JSON.stringify({ assets: genesisAssets }, null, '\t'),
Expand Down
16 changes: 7 additions & 9 deletions src/utils/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ import { DEFAULT_PORT_P2P, DEFAULT_PORT_RPC } from '../constants';

const INSTALL_LISK_CORE_COMMAND = 'npm i -g lisk-core@^4.0.0-beta.5';
const INSTALL_PM2_COMMAND = 'npm i -g pm2';
const START_PM2_COMMAND = 'pm2 start pm2.config.json';
const PM2_FILE_NAME = 'pm2.migrator.config.json';
const START_PM2_COMMAND = `pm2 start ${PM2_FILE_NAME}`;

const DEFAULT_LISK_DATA_DIR = `${homedir()}/.lisk/lisk-core`;
const LISK_V3_BACKUP_DATA_DIR = `${homedir()}/.lisk/lisk-core-v3`;
const PM2_FILE_NAME = 'pm2.config.json';

export const installLiskCore = async (): Promise<string> => execAsync(INSTALL_LISK_CORE_COMMAND);

Expand All @@ -56,14 +56,12 @@ const backupDefaultDirectoryIfExists = async (_this: Command) => {

export const startLiskCore = async (
_this: Command,
liskCoreV3DataPath: string,
_config: PartialApplicationConfig,
_previousLiskCoreVersion: string,
liskCorePath: string,
network: string,
networkDir: string,
outputDir: string,
): Promise<string | Error> => {
await isLiskCoreV3Running(liskCorePath);
const isCoreV3Running = await isLiskCoreV3Running(liskCorePath);
const isCoreV3Running = await isLiskCoreV3Running(liskCoreV3DataPath);
if (isCoreV3Running) throw new Error('Lisk Core v3 is still running.');

const networkPort = (_config?.network?.port as Port) ?? DEFAULT_PORT_P2P;
Expand All @@ -82,7 +80,7 @@ export const startLiskCore = async (
await installPM2();
_this.log('Finished installing pm2.');

const customConfigFilepath = resolve(networkDir, 'custom_config.json');
const customConfigFilepath = resolve(outputDir, 'custom_config.json');

fs.writeFileSync(
customConfigFilepath,
Expand All @@ -92,7 +90,7 @@ export const startLiskCore = async (
genesis: {
..._config.genesis,
block: {
fromFile: `${networkDir}/genesis_block.blob`,
fromFile: `${outputDir}/genesis_block.blob`,
},
},
},
Expand Down

0 comments on commit 78741c5

Please sign in to comment.