80 lines
2.7 KiB
TypeScript
80 lines
2.7 KiB
TypeScript
import { ipcMain, dialog, app } from 'electron'
|
|
import fs from 'fs'
|
|
import path from 'path'
|
|
import { encrypt, fromEncryptedJson } from './utils/keystore'
|
|
|
|
// Create keystore into default wallets directory
|
|
ipcMain.handle('wallet:createKeystore', async (_event, seed, password) => {
|
|
try {
|
|
const keystore = await encrypt(seed, password)
|
|
|
|
const savePath = path.join(process.cwd(), 'wallets')
|
|
fs.mkdirSync(savePath, { recursive: true })
|
|
|
|
// Use timestamp for filename
|
|
const timestamp = Date.now()
|
|
const fileName = `neptune-wallet-${timestamp}.json`
|
|
const filePath = path.join(savePath, fileName)
|
|
fs.writeFileSync(filePath, keystore)
|
|
|
|
return { filePath }
|
|
} catch (error) {
|
|
console.error('Error creating keystore:', error)
|
|
throw error
|
|
}
|
|
})
|
|
|
|
// New handler: let user choose folder and filename to save keystore
|
|
ipcMain.handle('wallet:saveKeystoreAs', async (_event, seed: string, password: string) => {
|
|
try {
|
|
const keystore = await encrypt(seed, password)
|
|
|
|
// Use timestamp for default filename
|
|
const timestamp = Date.now()
|
|
const defaultName = `neptune-wallet-${timestamp}.json`
|
|
const { canceled, filePath } = await dialog.showSaveDialog({
|
|
title: 'Save Keystore File',
|
|
defaultPath: path.join(app.getPath('documents'), defaultName),
|
|
filters: [{ name: 'JSON', extensions: ['json'] }],
|
|
})
|
|
|
|
if (canceled || !filePath) return { filePath: null }
|
|
|
|
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
|
fs.writeFileSync(filePath, keystore)
|
|
|
|
return { filePath }
|
|
} catch (error) {
|
|
console.error('Error saving keystore (Save As):', error)
|
|
throw error
|
|
}
|
|
})
|
|
|
|
ipcMain.handle('wallet:decryptKeystore', async (_event, filePath, password) => {
|
|
try {
|
|
const json = fs.readFileSync(filePath, 'utf-8')
|
|
const phrase = await fromEncryptedJson(json, password)
|
|
|
|
return { phrase }
|
|
} catch (error) {
|
|
console.error('Error decrypting keystore ipc:', error)
|
|
throw error
|
|
}
|
|
})
|
|
|
|
ipcMain.handle('wallet:checkKeystore', async () => {
|
|
try {
|
|
const walletDir = path.join(process.cwd(), 'wallets')
|
|
if (!fs.existsSync(walletDir)) return { exists: false, filePath: null }
|
|
|
|
const file = fs.readdirSync(walletDir).find((f) => f.endsWith('.json'))
|
|
if (!file) return { exists: false, filePath: null }
|
|
|
|
const filePath = path.join(walletDir, file)
|
|
return { exists: true, filePath}
|
|
} catch (error) {
|
|
console.error('Error checking keystore:', error)
|
|
return { exists: false, filePath: null, error: String(error) }
|
|
}
|
|
})
|