Skip to content

feat: use keystore to store private keys - #236

Closed
epsjunior wants to merge 11 commits into
mainfrom
dxp-450-use-keystore-to-store-private-keys
Closed

epsjunior wants to merge 11 commits into
mainfrom
dxp-450-use-keystore-to-store-private-keys

Conversation

@epsjunior

@epsjunior epsjunior commented Jul 8, 2025 •

Copy link
Copy Markdown
Contributor

🔐 Implement Encrypted Keystore Security

Overview

Replaces the insecure keypairManager system with enterprise-grade encrypted keystore functionality using ethers.js HDNodeWallet encryption. Centralizes all keystore logic in BaseAction to eliminate code duplication and prevent cyclic import issues across commands.

🚀 Key Features

Security Enhancements

  • Encrypted Storage: All private keys now stored encrypted using ethers.js wallet encryption
  • 3-Tries Security: Maximum 3 password attempts before lockout with progressive messaging
  • Password Validation: Minimum 8 characters + confirmation matching required

Architecture Improvements

  • Centralized Logic: All keystore operations consolidated in BaseAction class
  • Eliminated Duplication: Single source of truth for private key management across all commands
  • Resolved Cyclic Imports: Commands now inherit keystore functionality instead of importing separate managers
  • Clean Error Patterns: Eliminated fragile string matching (error.message.includes())
  • Method Organization: Private methods first, then protected (proper encapsulation)
  • Recursive Retry Logic: Clean password retry implementation without string parsing
  • Type Safety: Proper KeystoreData interface with validation

UX Improvements

  • Spinner Feedback: Replaced raw exceptions with clean spinner fail messages
  • Optimized Flow: Eliminated redundant password prompts after keystore creation
  • Progressive Messaging: Clear attempt counters ("Attempt 2/3") for password retries
  • Graceful Recovery: Automatic new keypair creation on file corruption/wrong format

🛠️ Technical Implementation

Centralized BaseAction Design

// All commands inherit keystore functionality
export class BaseAction extends ConfigFileManager {
  // Private keystore methods (internal use only)
  private async decryptKeystore(keystoreData, attempt): Promise<string>
  private isValidKeystoreFormat(data): boolean
  
  // Protected methods (available to all commands)
  protected async getPrivateKey(): Promise<string>
  protected async createKeypair(outputPath, overwrite): Promise<string>
  protected async promptPassword(message): Promise<string>
}

Benefits of Centralization

  • No Code Duplication: All commands use same keystore logic via inheritance
  • Consistent Security: Same 3-tries mechanism across all commands
  • Maintainability: Single location for keystore updates
  • Import Simplicity: Commands extend BaseAction instead of importing multiple managers
  • Testing: Unified test suite for all keystore operations

Security Features

// Progressive password attempts with clear messaging
const message = attempt === 1 
  ? "Enter password to decrypt keystore:" 
  : `Invalid password. Attempt ${attempt}/3 - Enter password to decrypt keystore:`;

// Lockout after max attempts
if (attempt >= 3) {
  this.failSpinner("Maximum password attempts exceeded (3/3).");
  process.exit(1);
}

Keystore Format

{
  "version": 1,
  "encrypted": "ethers-encrypted-json-wallet",
  "address": "0x..."
}

📋 Breaking Changes

  • Removed: keypairManager class and all references
  • Centralized: All keystore logic moved to BaseAction
  • Modified: getPrivateKey() now handles encrypted keystore directly
  • Modified: createKeypair() returns private key instead of void
  • File Format: New encrypted keystore format (auto-migration on corruption)

🧪 Testing Coverage

  • Password Handling: promptPassword, validation, retry mechanisms
  • Keystore Operations: read/write/decrypt operations with error scenarios
  • 3-Tries Security: attempt counting, progressive messaging, lockout behavior
  • File System: corruption handling, overwrite protection, path validation
  • Error Scenarios: invalid formats, wrong passwords, file conflicts
  • Security Validation: format checking, version validation, null/undefined handling

🔄 Migration Path

  • Existing plain text keypairs automatically trigger "create new keypair" flow
  • Users prompted to create encrypted keystore on first use
  • Corrupted files gracefully handled with new keypair creation option
  • No data loss - users can recover by creating new keypair

📈 Benefits

  • Security: Private keys now encrypted at rest with user passwords
  • Architecture: Centralized logic eliminates duplication and cyclic imports
  • UX: Clean error messages and progressive feedback instead of raw exceptions
  • Reliability: Proper error handling patterns without fragile string matching
  • Maintainability: Single source of truth for all keystore operations
  • Testability: Comprehensive test coverage for all security scenarios

Files Changed:

  • src/lib/actions/BaseAction.ts - Centralized keystore implementation
  • src/commands/keygen/create.ts - Updated integration
  • src/lib/interfaces/KeystoreData.ts - New type definitions
  • tests/libs/baseAction.test.ts - Comprehensive test coverage

Files Removed:

  • src/lib/accounts/KeypairManager.ts - Logic moved to BaseAction
  • tests/libs/accounts/KeypairManager.test.ts - Tests consolidated

Security Review: ✅ All private keys encrypted, proper attempt limiting, no plain text storage

Summary by CodeRabbit

  • New Features

    • Enhanced security by replacing unencrypted keypair files with encrypted keystore files protected by user passwords.
    • Added user prompts for password creation and confirmation during keystore generation.
    • Improved error handling for keystore file validation and decryption.
  • Bug Fixes

    • Updated user messages and prompts to accurately reflect the use of encrypted keystores instead of plain keypairs.
  • Tests

    • Expanded and improved test coverage for keystore management, password handling, and user interaction flows.
    • Removed obsolete tests related to the previous keypair management approach.

@coderabbitai

coderabbitai Bot commented Jul 8, 2025 •

Copy link
Copy Markdown

Walkthrough

The changes transition the key management system from using unencrypted keypair files to encrypted keystore files protected by user passwords. The KeypairManager class and its tests were removed, replaced by new keystore logic integrated into BaseAction. Command descriptions, user prompts, and tests were updated to reflect this new approach.

Changes

File(s) Change Summary
src/commands/keygen/create.ts, src/commands/keygen/index.ts Updated command and action logic to use encrypted keystore terminology and asynchronous keystore creation.
src/lib/accounts/KeypairManager.ts, tests/libs/accounts/KeypairManager.test.ts Removed the unencrypted keypair manager class and its associated tests.
src/lib/actions/BaseAction.ts Refactored key management to use encrypted keystores, added password prompts, decryption, and keystore validation.
src/lib/interfaces/KeystoreData.ts Introduced a new KeystoreData interface for typed keystore file handling.
tests/actions/create.test.ts Updated tests to mock internal keystore creation methods and reflect new terminology and asynchronous logic.
tests/libs/baseAction.test.ts Added comprehensive tests for keystore creation, decryption, password handling, and error cases in BaseAction.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant BaseAction
    participant FileSystem

    User->>CLI: Run keygen create command
    CLI->>BaseAction: createKeypairAction()
    BaseAction->>User: Prompt for password (and confirm)
    User->>BaseAction: Enter password
    BaseAction->>BaseAction: Generate wallet & encrypt with password
    BaseAction->>FileSystem: Write encrypted keystore file
    FileSystem-->>BaseAction: Confirm write
    BaseAction->>CLI: Show success message
Loading
sequenceDiagram
    participant User
    participant CLI
    participant BaseAction
    participant FileSystem

    CLI->>BaseAction: getPrivateKey()
    BaseAction->>FileSystem: Check for keystore file
    alt Keystore exists and valid
        BaseAction->>User: Prompt for password (up to 3 attempts)
        User->>BaseAction: Enter password
        BaseAction->>BaseAction: Decrypt keystore
        BaseAction->>CLI: Return private key
    else Keystore missing/invalid
        BaseAction->>User: Prompt to create new keypair
        User->>BaseAction: Confirm
        BaseAction->>BaseAction: createKeypair()
        BaseAction->>CLI: Return new private key
    end
Loading

Poem

In the warren of code, a secret we keep,
Now keys are encrypted, protected in sleep.
With passwords and prompts, our wallets secure,
No plaintext remains, of that we are sure!
🐇✨
Hop, hop, hooray—keystores today!
Safe in our burrow, our secrets shall stay.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-08T23_32_03_571Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/lib/interfaces/KeystoreData.ts (1)

1-5: Add JSDoc documentation for the interface.

Consider adding JSDoc comments to document the purpose of each field in the interface for better maintainability.

+/**
+ * Represents the structure of an encrypted keystore file
+ */
 export interface KeystoreData {
+    /** Version of the keystore format */
     version: number;
+    /** Encrypted wallet data in JSON string format */
     encrypted: string;
+    /** Ethereum address associated with the keystore */
     address: string;
   }
tests/libs/baseAction.test.ts (1)

110-119: Remove duplicate process.exit mock.

The process.exit is already mocked in the beforeEach hook (line 38). This duplicate mock is unnecessary and could cause confusion.

   test("should confirm prompt and exit when declined", async () => {
     vi.mocked(inquirer.prompt).mockResolvedValue({confirmAction: false});
-    const processExitSpy = vi.spyOn(process, "exit").mockImplementation(() => {
-      throw new Error("process exited");
-    });
 
     await expect(baseAction["confirmPrompt"]("Are you sure?")).rejects.toThrow("process exited");
     expect(inquirer.prompt).toHaveBeenCalled();
     expect(processExitSpy).toHaveBeenCalledWith(0);
   });
src/lib/actions/BaseAction.ts (1)

1-208: Consider architectural improvements for better separation of concerns.

The implementation successfully achieves the PR objectives of replacing the insecure keypair system with encrypted keystore. For future enhancements, consider:

  1. Separation of Concerns: Extract UI operations (prompts, spinners) into a separate class to improve testability and reusability
  2. Error Handling Strategy: Replace process.exit() calls with a proper error handling strategy using exceptions
  3. Security Enhancements:
    • Consider implementing session timeout for decrypted private keys
    • Add option to clear sensitive data from memory after use
    • Implement key derivation with salt for additional security
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a17392f and 75447dc.

📒 Files selected for processing (8)
  • src/commands/keygen/create.ts (1 hunks)
  • src/commands/keygen/index.ts (1 hunks)
  • src/lib/accounts/KeypairManager.ts (0 hunks)
  • src/lib/actions/BaseAction.ts (2 hunks)
  • src/lib/interfaces/KeystoreData.ts (1 hunks)
  • tests/actions/create.test.ts (1 hunks)
  • tests/libs/accounts/KeypairManager.test.ts (0 hunks)
  • tests/libs/baseAction.test.ts (3 hunks)
💤 Files with no reviewable changes (2)
  • src/lib/accounts/KeypairManager.ts
  • tests/libs/accounts/KeypairManager.test.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/commands/keygen/index.ts (1)
src/commands/keygen/create.ts (2)
  • CreateKeypairOptions (3-6)
  • KeypairCreator (8-23)
tests/libs/baseAction.test.ts (1)
src/lib/actions/BaseAction.ts (1)
  • BaseAction (13-208)
src/lib/actions/BaseAction.ts (2)
src/lib/config/ConfigFileManager.ts (1)
  • ConfigFileManager (5-51)
src/lib/interfaces/KeystoreData.ts (1)
  • KeystoreData (1-5)
🔇 Additional comments (7)
src/commands/keygen/index.ts (1)

12-17: LGTM! Terminology and async handling are correctly updated.

The changes properly reflect the transition to encrypted keystores and correctly handle the asynchronous nature of the keystore creation process.

src/commands/keygen/create.ts (1)

13-22: LGTM! Async implementation and messaging are consistent.

The method correctly handles the asynchronous keystore creation with appropriate spinner feedback messages.

tests/actions/create.test.ts (1)

10-44: LGTM! Test refactoring provides better isolation.

The tests correctly mock internal methods and properly test the async behavior of keystore creation. The terminology updates are consistent throughout.

tests/libs/baseAction.test.ts (1)

198-439: Excellent test coverage for keystore management.

The test suite comprehensively covers all aspects of the new keystore functionality including:

  • Password validation and retry logic
  • Keystore format validation
  • Encryption/decryption flows
  • Error handling and edge cases
  • File system operations

Great work on ensuring robust test coverage!

src/lib/actions/BaseAction.ts (3)

9-11: LGTM! Appropriate imports for keystore functionality.

The addition of ethers for wallet encryption and file system utilities aligns well with the PR's objective of implementing encrypted keystore storage.


39-46: Well-implemented type guard for keystore validation.

The method correctly validates the keystore structure with proper TypeScript type predicate syntax. The version check ensures forward compatibility.


125-141: Well-implemented secure password prompt.

Good use of inquirer's password type with masking and appropriate validation for empty passwords.

Comment on lines +87 to +123
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;
}

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.

Comment on lines +22 to +37
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);
}
}

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.

Comment on lines +68 to +85
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);
}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant