Skip to content
Closed
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
11 changes: 6 additions & 5 deletions src/commands/keygen/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ export class KeypairCreator extends BaseAction {
super();
}

createKeypairAction(options: CreateKeypairOptions) {
async createKeypairAction(options: CreateKeypairOptions) {
try {
this.startSpinner(`Creating keypair...`);
this.keypairManager.createKeypair(options.output, options.overwrite);
this.succeedSpinner(`Keypair successfully created and saved to: ${options.output}`);
this.startSpinner(`Creating encrypted keystore...`);
await this.createKeypair(options.output, options.overwrite);

this.succeedSpinner(`Encrypted keystore successfully created and saved to: ${options.output}`);
} catch (error) {
this.failSpinner("Failed to generate keypair", error);
this.failSpinner("Failed to generate keystore", error);
}
}
}
8 changes: 4 additions & 4 deletions src/commands/keygen/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ export function initializeKeygenCommands(program: Command) {

keygenCommand
.command("create")
.description("Generates a new keypair and saves it to a file")
.option("--output <path>", "Path to save the keypair", "./keypair.json")
.description("Generates a new encrypted keystore and saves it to a file")
.option("--output <path>", "Path to save the keystore", "./keypair.json")
.option("--overwrite", "Overwrite the existing file if it already exists", false)
.action((options: CreateKeypairOptions) => {
.action(async (options: CreateKeypairOptions) => {
const keypairCreator = new KeypairCreator();
keypairCreator.createKeypairAction(options);
await keypairCreator.createKeypairAction(options);
});

return program;
Expand Down
43 changes: 0 additions & 43 deletions src/lib/accounts/KeypairManager.ts

This file was deleted.

125 changes: 108 additions & 17 deletions src/lib/actions/BaseAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,53 @@ import ora, {Ora} from "ora";
import chalk from "chalk";
import inquirer from "inquirer";
import { inspect } from "util";
import {KeypairManager} from "../accounts/KeypairManager";
import {createClient, createAccount} from "genlayer-js";
import {localnet} from "genlayer-js/chains";
import type {GenLayerClient, GenLayerChain} from "genlayer-js/types";
import { ethers } from "ethers";
import { writeFileSync, existsSync, readFileSync } from "fs";
import { KeystoreData } from "../interfaces/KeystoreData";

export class BaseAction extends ConfigFileManager {
protected keypairManager: KeypairManager;
private spinner: Ora;
private _genlayerClient: GenLayerClient<GenLayerChain> | null = null;

constructor() {
super();
this.spinner = ora({text: "", spinner: "dots"});
this.keypairManager = new KeypairManager();
}

private async decryptKeystore(keystoreData: KeystoreData, attempt: number = 1): Promise<string> {
try {
const message = attempt === 1
? "Enter password to decrypt keystore:"
: `Invalid password. Attempt ${attempt}/3 - Enter password to decrypt keystore:`;
const password = await this.promptPassword(message);
const wallet = await ethers.Wallet.fromEncryptedJson(keystoreData.encrypted, password);
return wallet.privateKey;
} catch (error) {
if (attempt >= 3) {
this.failSpinner("Maximum password attempts exceeded (3/3).");
process.exit(1);
}
return await this.decryptKeystore(keystoreData, attempt + 1);
}
}
Comment on lines +22 to +37

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Consider throwing an error instead of calling process.exit for better testability.

The method implementation is solid with good retry logic and user feedback. However, there are a few improvements to consider:

  1. Replace process.exit(1) with throwing an error to make the code more testable and library-friendly
  2. Extract the magic number 3 to a class constant
  3. Consider adding a delay between attempts to further prevent brute-force attacks
+  private static readonly MAX_PASSWORD_ATTEMPTS = 3;
+
   private async decryptKeystore(keystoreData: KeystoreData, attempt: number = 1): Promise<string> {
     try {
       const message = attempt === 1 
         ? "Enter password to decrypt keystore:" 
-        : `Invalid password. Attempt ${attempt}/3 - Enter password to decrypt keystore:`;
+        : `Invalid password. Attempt ${attempt}/${BaseAction.MAX_PASSWORD_ATTEMPTS} - Enter password to decrypt keystore:`;
       const password = await this.promptPassword(message);
       const wallet = await ethers.Wallet.fromEncryptedJson(keystoreData.encrypted, password);
       return wallet.privateKey;
     } catch (error) {
-      if (attempt >= 3) {
-        this.failSpinner("Maximum password attempts exceeded (3/3).");
-        process.exit(1);
+      if (attempt >= BaseAction.MAX_PASSWORD_ATTEMPTS) {
+        this.failSpinner(`Maximum password attempts exceeded (${BaseAction.MAX_PASSWORD_ATTEMPTS}/${BaseAction.MAX_PASSWORD_ATTEMPTS}).`);
+        throw new Error("Maximum password attempts exceeded");
       }
+      // Add delay to prevent rapid attempts
+      await new Promise(resolve => setTimeout(resolve, 1000));
       return await this.decryptKeystore(keystoreData, attempt + 1);
     }
   }
πŸ€– Prompt for AI Agents
In src/lib/actions/BaseAction.ts around lines 22 to 37, replace the call to
process.exit(1) with throwing a specific error to improve testability and avoid
abrupt termination. Extract the maximum retry count (currently 3) into a
class-level constant for easier configuration and clarity. Additionally, add a
short delay (e.g., using a timeout or sleep function) between retry attempts to
help mitigate brute-force password guessing.


private isValidKeystoreFormat(data: any): data is KeystoreData {
return Boolean(
data &&
data.version === 1 &&
typeof data.encrypted === "string" &&
typeof data.address === "string"
);
}

private formatOutput(data: any): string {
if (typeof data === "string") {
return data;
}
return inspect(data, { depth: null, colors: false });
}

protected async getClient(rpcUrl?: string): Promise<GenLayerClient<GenLayerChain>> {
Expand All @@ -32,14 +65,79 @@ export class BaseAction extends ConfigFileManager {
return this._genlayerClient;
}

protected async getPrivateKey() {
const privateKey = this.keypairManager.getPrivateKey();
if (privateKey) {
return privateKey;
protected async getPrivateKey(): Promise<string> {
const keypairPath = this.getConfigByKey("keyPairPath");

if (!keypairPath || !existsSync(keypairPath)) {
await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
return await this.createKeypair("./keypair.json", false);
}

const keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));

if (!this.isValidKeystoreFormat(keystoreData)) {
this.failSpinner("Invalid keystore format. Expected encrypted keystore file.");
await this.confirmPrompt("Would you like to create a new keypair?");
return await this.createKeypair("./keypair.json", true);
}
await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
this.keypairManager.createKeypair();
return this.keypairManager.getPrivateKey();

return await this.decryptKeystore(keystoreData);
}
Comment on lines +68 to +85

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Improve error handling and make keystore path configurable.

The method handles missing and invalid keystore files well, but there are a few improvements to consider:

  1. Add try-catch for readFileSync to handle corrupted files gracefully
  2. Make the default keystore path configurable instead of hardcoding "./keypair.json"
  3. Consider splitting the method to follow Single Responsibility Principle
+  private static readonly DEFAULT_KEYSTORE_PATH = "./keystore.json";
+
   protected async getPrivateKey(): Promise<string> {
     const keypairPath = this.getConfigByKey("keyPairPath");
 
     if (!keypairPath || !existsSync(keypairPath)) {
       await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
-      return await this.createKeypair("./keypair.json", false);
+      return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, false);
     }
 
-    const keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));
+    let keystoreData: any;
+    try {
+      keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));
+    } catch (error) {
+      this.failSpinner("Failed to read or parse keystore file.");
+      await this.confirmPrompt("Would you like to create a new keypair?");
+      return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true);
+    }
 
     if (!this.isValidKeystoreFormat(keystoreData)) {
       this.failSpinner("Invalid keystore format. Expected encrypted keystore file.");
       await this.confirmPrompt("Would you like to create a new keypair?");
-      return await this.createKeypair("./keypair.json", true);
+      return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true);
     }
 
     return await this.decryptKeystore(keystoreData);
   }
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
protected async getPrivateKey(): Promise<string> {
const keypairPath = this.getConfigByKey("keyPairPath");
if (!keypairPath || !existsSync(keypairPath)) {
await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
return await this.createKeypair("./keypair.json", false);
}
const keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));
if (!this.isValidKeystoreFormat(keystoreData)) {
this.failSpinner("Invalid keystore format. Expected encrypted keystore file.");
await this.confirmPrompt("Would you like to create a new keypair?");
return await this.createKeypair("./keypair.json", true);
}
await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
this.keypairManager.createKeypair();
return this.keypairManager.getPrivateKey();
return await this.decryptKeystore(keystoreData);
}
private static readonly DEFAULT_KEYSTORE_PATH = "./keystore.json";
protected async getPrivateKey(): Promise<string> {
const keypairPath = this.getConfigByKey("keyPairPath");
if (!keypairPath || !existsSync(keypairPath)) {
await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, false);
}
let keystoreData: any;
try {
keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));
} catch (error) {
this.failSpinner("Failed to read or parse keystore file.");
await this.confirmPrompt("Would you like to create a new keypair?");
return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true);
}
if (!this.isValidKeystoreFormat(keystoreData)) {
this.failSpinner("Invalid keystore format. Expected encrypted keystore file.");
await this.confirmPrompt("Would you like to create a new keypair?");
return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true);
}
return await this.decryptKeystore(keystoreData);
}
πŸ€– Prompt for AI Agents
In src/lib/actions/BaseAction.ts around lines 68 to 85, improve error handling
by wrapping the readFileSync call in a try-catch block to gracefully handle
corrupted or unreadable keystore files. Replace the hardcoded default keystore
path "./keypair.json" with a configurable option, possibly passed as a parameter
or retrieved from configuration. Refactor the method by splitting it into
smaller functions, each handling a single responsibility such as checking file
existence, validating format, and decrypting the keystore, to enhance
readability and maintainability.


protected async createKeypair(outputPath: string, overwrite: boolean): Promise<string> {
const finalOutputPath = this.getFilePath(outputPath);
this.stopSpinner();

if (existsSync(finalOutputPath) && !overwrite) {
this.failSpinner(`The file at ${finalOutputPath} already exists. Use the '--overwrite' option to replace it.`);
process.exit(1);
}

const wallet = ethers.Wallet.createRandom();

const password = await this.promptPassword("Enter password to encrypt your keystore:");
const confirmPassword = await this.promptPassword("Confirm password:");

if (password !== confirmPassword) {
this.failSpinner("Passwords do not match");
process.exit(1);
}

if (password.length < 8) {
this.failSpinner("Password must be at least 8 characters long");
process.exit(1);
}

const encryptedJson = await wallet.encrypt(password);

const keystoreData: KeystoreData = {
version: 1,
encrypted: encryptedJson,
address: wallet.address,
};

writeFileSync(finalOutputPath, JSON.stringify(keystoreData, null, 2));
this.writeConfig('keyPairPath', finalOutputPath);

return wallet.privateKey;
}
Comment on lines +87 to +123

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Use async file operations and consider enhancing password validation.

The keypair creation logic is well-structured, but consider these improvements:

  1. Replace writeFileSync with async writeFile to avoid blocking
  2. Extract magic number for minimum password length
  3. Consider adding password complexity requirements beyond just length
  4. Replace process.exit calls with error throwing
+  private static readonly MIN_PASSWORD_LENGTH = 8;
+
   protected async createKeypair(outputPath: string, overwrite: boolean): Promise<string> {
     const finalOutputPath = this.getFilePath(outputPath);
     this.stopSpinner();
 
     if (existsSync(finalOutputPath) && !overwrite) {
       this.failSpinner(`The file at ${finalOutputPath} already exists. Use the '--overwrite' option to replace it.`);
-      process.exit(1);
+      throw new Error(`File already exists at ${finalOutputPath}`);
     }
 
     const wallet = ethers.Wallet.createRandom();
     
     const password = await this.promptPassword("Enter password to encrypt your keystore:");
     const confirmPassword = await this.promptPassword("Confirm password:");
 
     if (password !== confirmPassword) {
       this.failSpinner("Passwords do not match");
-      process.exit(1);
+      throw new Error("Passwords do not match");
     }
 
-    if (password.length < 8) {
-      this.failSpinner("Password must be at least 8 characters long");
-      process.exit(1);
+    if (password.length < BaseAction.MIN_PASSWORD_LENGTH) {
+      this.failSpinner(`Password must be at least ${BaseAction.MIN_PASSWORD_LENGTH} characters long`);
+      throw new Error(`Password too short`);
     }
 
     const encryptedJson = await wallet.encrypt(password);
     
     const keystoreData: KeystoreData = {
       version: 1,
       encrypted: encryptedJson,
       address: wallet.address,
     };
 
-    writeFileSync(finalOutputPath, JSON.stringify(keystoreData, null, 2));
+    const { writeFile } = await import('fs/promises');
+    await writeFile(finalOutputPath, JSON.stringify(keystoreData, null, 2));
     this.writeConfig('keyPairPath', finalOutputPath);
     
     return wallet.privateKey;
   }

Consider adding password strength validation to ensure better security:

private validatePasswordStrength(password: string): string | true {
  if (password.length < BaseAction.MIN_PASSWORD_LENGTH) {
    return `Password must be at least ${BaseAction.MIN_PASSWORD_LENGTH} characters long`;
  }
  // Add additional checks for complexity
  if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
    return "Password must contain uppercase, lowercase, and numeric characters";
  }
  return true;
}
πŸ€– Prompt for AI Agents
In src/lib/actions/BaseAction.ts lines 87 to 123, replace the synchronous
writeFileSync call with the asynchronous writeFile to prevent blocking. Define a
constant for the minimum password length instead of using the magic number 8
directly. Add a password complexity validation method that checks for uppercase,
lowercase, and numeric characters, and use it to validate the password instead
of just length. Finally, replace all process.exit calls with throwing errors to
allow proper error handling and avoid abrupt termination.


protected async promptPassword(message: string): Promise<string> {
const answer = await inquirer.prompt([
{
type: "password",
name: "password",
message: chalk.yellow(message),
mask: "*",
validate: (input: string) => {
if (!input) {
return "Password cannot be empty";
}
return true;
},
},
]);
return answer.password;
}

protected async confirmPrompt(message: string): Promise<void> {
Expand All @@ -58,13 +156,6 @@ export class BaseAction extends ConfigFileManager {
}
}

private formatOutput(data: any): string {
if (typeof data === "string") {
return data;
}
return inspect(data, { depth: null, colors: false });
}

protected log(message: string, data?: any): void {
console.log(chalk.white(`\n${message}`));
if (data !== undefined) console.log(this.formatOutput(data));
Expand Down
5 changes: 5 additions & 0 deletions src/lib/interfaces/KeystoreData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface KeystoreData {
version: number;
encrypted: string;
address: string;
}
52 changes: 15 additions & 37 deletions tests/actions/create.test.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,45 @@
import {describe, test, vi, beforeEach, afterEach, expect} from "vitest";
import {KeypairCreator} from "../../src/commands/keygen/create";
import {writeFileSync, existsSync} from "fs";
import {ethers} from "ethers";

vi.mock("fs");

vi.mock("ethers", () => ({
ethers: {
Wallet: {
createRandom: vi.fn(),
},
},
}));

describe("KeypairCreator", () => {
let keypairCreator: KeypairCreator;

const mockWallet: any = {
address: "0xMockedAddress",
privateKey: "0xMockedPrivateKey",
};

const mockKeypairManager = {
createKeypair: vi.fn(),
};

beforeEach(() => {
vi.clearAllMocks();
keypairCreator = new KeypairCreator();
(keypairCreator as any).keypairManager = mockKeypairManager;

// Mock the BaseAction methods
vi.spyOn(keypairCreator as any, "startSpinner").mockImplementation(() => {});
vi.spyOn(keypairCreator as any, "succeedSpinner").mockImplementation(() => {});
vi.spyOn(keypairCreator as any, "failSpinner").mockImplementation(() => {});
vi.spyOn(keypairCreator as any, "writeConfig").mockImplementation(() => {});
vi.spyOn(keypairCreator as any, "getFilePath").mockImplementation(fileName => `/mocked/path/${fileName}`);
vi.mocked(ethers.Wallet.createRandom).mockReturnValue(mockWallet);
vi.spyOn(keypairCreator as any, "createKeypair").mockResolvedValue("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef");
});

afterEach(() => {
vi.restoreAllMocks();
});

test("successfully creates and saves a keypair", () => {
vi.mocked(existsSync).mockReturnValue(false);
test("successfully creates and saves an encrypted keystore", async () => {
const options = {output: "keypair.json", overwrite: false};

keypairCreator.createKeypairAction(options);
await keypairCreator.createKeypairAction(options);

expect(keypairCreator["startSpinner"]).toHaveBeenCalledWith("Creating keypair...");
expect(mockKeypairManager.createKeypair).toHaveBeenCalledWith(options.output, options.overwrite);
expect(keypairCreator["startSpinner"]).toHaveBeenCalledWith("Creating encrypted keystore...");
expect(keypairCreator["createKeypair"]).toHaveBeenCalledWith(
options.output,
options.overwrite
);
expect(keypairCreator["succeedSpinner"]).toHaveBeenCalledWith(
"Keypair successfully created and saved to: keypair.json",
"Encrypted keystore successfully created and saved to: keypair.json",
);
});

test("handles errors during keypair creation", () => {
test("handles errors during keystore creation", async () => {
const mockError = new Error("Mocked creation error");
mockKeypairManager.createKeypair.mockImplementation(() => {
throw mockError;
});
vi.spyOn(keypairCreator as any, "createKeypair").mockRejectedValue(mockError);

keypairCreator.createKeypairAction({output: "keypair.json", overwrite: true});
await keypairCreator.createKeypairAction({output: "keypair.json", overwrite: true});

expect(keypairCreator["failSpinner"]).toHaveBeenCalledWith("Failed to generate keypair", mockError);
expect(keypairCreator["failSpinner"]).toHaveBeenCalledWith("Failed to generate keystore", mockError);
});
});
Loading