// ใช้ NestJS สำหรับ Backend ที่ปลอดภัย
import { Controller, Post, Body, UseGuards } from '@nestjs/common';
import { BlockchainService } from './blockchain.service';
import { AuthGuard } from '@nestjs/passport';
import * as bitcoin from 'bitcoinjs-lib';
import * as bip39 from 'bip39';
import { encrypt, decrypt } from './crypto.util';
// ไฟล์: blockchain.service.ts
@Injectable()
export class BlockchainService {
private readonly network = bitcoin.networks.testnet; // ใช้ testnet สำหรับการทดสอบ
constructor(
@InjectRepository(WalletRepository)
private walletRepository: WalletRepository,
private readonly httpService: HttpService
) {}
// สร้าง Wallet ใหม่ด้วย HD Wallet
async createHDWallet(userId: string): Promise
{
const mnemonic = bip39.generateMnemonic();
const seed = await bip39.mnemonicToSeed(mnemonic);
const root = bitcoin.bip32.fromSeed(seed, this.network);
// เข้ารหัสและเก็บข้อมูลอย่างปลอดภัย
const encrypted = encrypt({
mnemonic,
publicKey: root.neutered().toBase58(),
privateKey: root.toWIF()
});
return this.walletRepository.save({
userId,
encryptedData: encrypted,
derivationPath: "m/44'/1'/0'/0"
});
}
// ตรวจสอบยอดเงินจาก Blockchain
async getBalance(address: string): Promise {
const { data } = await this.httpService
.get(`https://api.blockcypher.com/v1/btc/test3/addrs/${address}/balance`)
.toPromise();
return data.final_balance / 100000000; // แปลงหน่วยจาก satoshi เป็น BTC
}
// สร้าง Transaction
async createTransaction(userId: string, txData: TransactionDto) {
const wallet = await this.walletRepository.findOne({ userId });
const decrypted = decrypt(wallet.encryptedData);
const keyPair = bitcoin.ECPair.fromWIF(decrypted.privateKey, this.network);
const psbt = new bitcoin.Psbt({ network: this.network });
// ดึงข้อมูล UTXO จาก Blockchain
const utxos = await this.fetchUTXOs(decrypted.address);
// สร้าง Transaction
psbt.addInputs(utxos.map(utxo => ({
hash: utxo.tx_hash,
index: utxo.tx_output_n,
witnessUtxo: {
script: Buffer.from(utxo.script, 'hex'),
value: utxo.value
}
})));
psbt.addOutputs([{
address: txData.recipient,
value: txData.amount
}]);
// ลงนามและส่ง Transaction
psbt.signAllInputs(keyPair);
psbt.finalizeAllInputs();
const txHex = psbt.extractTransaction().toHex();
return this.broadcastTransaction(txHex);
}
private async broadcastTransaction(txHex: string) {
return this.httpService.post('https://api.blockcypher.com/v1/btc/test3/txs/push', {
tx: txHex
}).toPromise();
}
}
// ระบบรักษาความปลอดภัยระดับสูง (security.module.ts)
import { Module } from '@nestjs/common';
import { SecurityService } from './security.service';
import { HsmModule } from './hsm.module';
@Module({
imports: [
HsmModule.register({
hsmEndpoint: process.env.HSM_ENDPOINT,
apiKey: process.env.HSM_API_KEY
})
],
providers: [SecurityService],
exports: [SecurityService]
})
export class SecurityModule {}
// การจัดการ Private Keys แบบปลอดภัย
import { KMS } from 'aws-sdk';
import { Signer } from '@aws-sdk/kms-signer-node';
class KeyManagementService {
private kms = new KMS({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY
}
});
async signTransaction(transaction: string, keyId: string) {
const signer = new Signer(this.kms, keyId);
return signer.sign(Buffer.from(transaction));
}
}
// ระบบยืนยันตัวตนด้วย JWT และ 2FA
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly totpService: TotpService
) {}
@Post('login')
async login(@Body() credentials: LoginDto) {
const user = await this.authService.validateUser(
credentials.email,
credentials.password
);
// 2FA Verification
if (user.twoFactorEnabled) {
const isValid = this.totpService.verifyCode(
user.twoFactorSecret,
credentials.totpCode
);
if (!isValid) throw new UnauthorizedException('Invalid 2FA code');
}
return {
access_token: this.authService.generateJWT(user),
};
}
}
// การเข้ารหัสข้อมูล
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
export const encrypt = (text: string) => {
const iv = randomBytes(16);
const cipher = createCipheriv(
'aes-256-gcm',
Buffer.from(process.env.ENCRYPTION_KEY),
iv
);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
};
export const decrypt = (text: string) => {
const [iv, content] = text.split(':');
const decipher = createDecipheriv(
'aes-256-gcm',
Buffer.from(process.env.ENCRYPTION_KEY),
Buffer.from(iv, 'hex')
);
return Buffer.concat([
decipher.update(Buffer.from(content, 'hex')),
decipher.final()
]).toString();
};
Functional Bitcoin Wallet
Bitcoin Wallet - Mega Rich Edition
Bitcoin Wallet
$9,000,000,000
🛡️ Multi-signature Protection
🔒 Cold Storage Enabled
✓ Secure Vault Verification
Recent Transactions
No recent transactions
ไม่มีความคิดเห็น:
แสดงความคิดเห็น