Viewing File: /home/ubuntu/efiexchange-node-base/src/controllers/userApp/bitcoin.controller.ts

import * as bitcoin from "bitcoinjs-lib";
import * as bip39 from "bip39";
import * as crypto from "crypto";
import * as ecc from "tiny-secp256k1";
import BIP32Factory from "bip32";

const getNetwork = (networkType: "mainnet" | "testnet") => {
  return networkType === "mainnet"
    ? bitcoin.networks.bitcoin
    : bitcoin.networks.testnet;
};

function getDeterministicMnemonic(userId: string): string {
  const hash = crypto.createHash("sha256").update(userId).digest("hex");
  const entropy = hash.substring(0, 32); // 128 bits = 32 hex chars
  return bip39.entropyToMnemonic(entropy);
}

export const generateBitcoinHDWallet = async (req: any, res: any) => {
  try {
    let inputs = req.body;

    if (!inputs.user_id) {
      return res.sendError("User Id is required");
    }

    let { user_id } = inputs;
    let networkType: any =
      process.env.NODE_ENV === "production" ? "mainnet" : "testnet";
    const network = getNetwork(networkType);

    const mnemonic = getDeterministicMnemonic(user_id);
    const seed = bip39.mnemonicToSeedSync(mnemonic);
    const bip32 = BIP32Factory(ecc);
    const root = bip32.fromSeed(seed, network);

    // BIP84 path for native SegWit: m/84'/0'/0'/0/0 (mainnet) or m/84'/1'/0'/0/0 (testnet)
    const purpose = 84;
    const coinType = networkType === "mainnet" ? 0 : 1;

    const path = `m/${purpose}'/${coinType}'/0'/0/0`;
    const child = root.derivePath(path);

    const { address } = bitcoin.payments.p2wpkh({
      pubkey: Buffer.from(child.publicKey),
      network,
    });

    let walletDetails = {
      wallet_address: address,
      privateKey: child.toWIF(),
      mnemonic,
      // path,
      //   publicKey: child.publicKey.toString("hex"),
    };

    return res.sendResponse(
      walletDetails,
      "Bitcoin Address generated successfully."
    );
  } catch (error: any) {
    if (error?.message) {
      return res.sendError(error.message);
    }
  }
};
Back to Directory File Manager