Feature: Implemented Secure Merchant Vault Architecture with On-chain segregation and Encryption
This commit is contained in:
49
lib/encryption.ts
Normal file
49
lib/encryption.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
const ENCRYPTION_KEY = process.env.ENCRYPTION_SECRET || 'fallback_secret_do_not_use_in_production_12345'; // Must be 32 chars for aes-256-gcm
|
||||
const IV_LENGTH = 16;
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
|
||||
/**
|
||||
* Encrypts a piece of sensitive text (like a private key)
|
||||
*/
|
||||
export function encrypt(text: string): string {
|
||||
// Ensure key is 32 bytes
|
||||
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
let encrypted = cipher.update(text, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
|
||||
const authTag = cipher.getAuthTag().toString('hex');
|
||||
|
||||
// Format: iv:authTag:encrypted
|
||||
return `${iv.toString('hex')}:${authTag}:${encrypted}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts an encrypted string back to its original form
|
||||
*/
|
||||
export function decrypt(encryptedText: string): string {
|
||||
try {
|
||||
const parts = encryptedText.split(':');
|
||||
if (parts.length !== 3) throw new Error('Invalid encrypted text format');
|
||||
|
||||
const iv = Buffer.from(parts[0], 'hex');
|
||||
const authTag = Buffer.from(parts[1], 'hex');
|
||||
const encrypted = parts[2];
|
||||
|
||||
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
|
||||
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
|
||||
decrypted += decipher.final('utf8');
|
||||
|
||||
return decrypted;
|
||||
} catch (error) {
|
||||
console.error('Decryption failed:', error);
|
||||
throw new Error('Critical: Could not decrypt sensitive data. Check ENCRYPTION_SECRET.');
|
||||
}
|
||||
}
|
||||
80
lib/vault-manager.ts
Normal file
80
lib/vault-manager.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { ethers } from 'ethers';
|
||||
import { Keypair } from '@solana/web3.js';
|
||||
import bs58 from 'bs58';
|
||||
import { db } from './db';
|
||||
import { encrypt, decrypt } from './encryption';
|
||||
|
||||
/**
|
||||
* Ensures a merchant has EVM and Solana vault wallets.
|
||||
* Generates them if they don't exist.
|
||||
*/
|
||||
export async function ensureMerchantVaults(merchantId: string) {
|
||||
const result = await db.query(
|
||||
'SELECT id, evm_vault_address, sol_vault_address FROM merchants WHERE id = $1',
|
||||
[merchantId]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) throw new Error('Merchant not found');
|
||||
|
||||
const merchant = result.rows[0];
|
||||
|
||||
// If already has vaults, skip
|
||||
if (merchant.evm_vault_address && merchant.sol_vault_address) {
|
||||
return {
|
||||
evm: merchant.evm_vault_address,
|
||||
sol: merchant.sol_vault_address
|
||||
};
|
||||
}
|
||||
|
||||
console.log(`[VaultManager] Generating vaults for merchant ${merchantId}...`);
|
||||
|
||||
// 1. Generate EVM Wallet
|
||||
const evmWallet = ethers.Wallet.createRandom();
|
||||
const encryptedEvmKey = encrypt(evmWallet.privateKey);
|
||||
|
||||
// 2. Generate Solana Wallet
|
||||
const solKeypair = Keypair.generate();
|
||||
const encryptedSolKey = encrypt(bs58.encode(solKeypair.secretKey));
|
||||
|
||||
// 3. Save to DB
|
||||
await db.query(
|
||||
`UPDATE merchants SET
|
||||
evm_vault_address = $1,
|
||||
evm_vault_key = $2,
|
||||
sol_vault_address = $3,
|
||||
sol_vault_key = $4
|
||||
WHERE id = $5`,
|
||||
[
|
||||
evmWallet.address,
|
||||
encryptedEvmKey,
|
||||
solKeypair.publicKey.toBase58(),
|
||||
encryptedSolKey,
|
||||
merchantId
|
||||
]
|
||||
);
|
||||
|
||||
return {
|
||||
evm: evmWallet.address,
|
||||
sol: solKeypair.publicKey.toBase58()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the decrypted private keys for a merchant's vaults.
|
||||
* CRITICAL: Use only when needed (e.g. during manual payout)
|
||||
*/
|
||||
export async function getMerchantVaultSecrets(merchantId: string) {
|
||||
const result = await db.query(
|
||||
'SELECT evm_vault_key, sol_vault_key FROM merchants WHERE id = $1',
|
||||
[merchantId]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) throw new Error('Merchant not found');
|
||||
|
||||
const merchant = result.rows[0];
|
||||
|
||||
return {
|
||||
evmKey: merchant.evm_vault_key ? decrypt(merchant.evm_vault_key) : null,
|
||||
solKey: merchant.sol_vault_key ? decrypt(merchant.sol_vault_key) : null
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user