bitcoinjs-lib 哈希交易之多筆交易合併。

  • 轉帳的時候須要手動尋找每一筆未花費記錄實在太費時。
  • 比特幣轉帳須要提取或合併全部未花費的交易中的比特幣,才能實現交易。
import * as bitcoin from 'bitcoinjs-lib';
import fetch, { Response } from 'node-fetch';

const quantitySat = 0.0001 * 1e8;
const feeSat = 0.0001 * 1e8;

(async () => {
  try {
    let NETWORK = bitcoin.networks.testnet;
    const keyPair = bitcoin.ECPair.fromWIF(from_pvtkey, NETWORK);
    const p2pkh = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey, network: NETWORK });
    let from = p2pkh.address;
    const utxoResponse: Response = await fetch(`https://api.blockcypher.com/v1/btc/test3/addrs/${from}`);
    const json = await utxoResponse.json();
    console.log(json);
    let balance = json.balance;
    let unspentList: Array<any> = [];
    // 過濾掉已經被花費了的交易和未確認的交易,以及本身不在接收列表的交易
    const txrefs = json.txrefs;
    const unconfirmed_txrefs = json.unconfirmed_txrefs;
    if (unconfirmed_txrefs && unconfirmed_txrefs.length > 0) {
      // 要把未確認的餘額給去掉
      balance += json.unconfirmed_balance;
      unspentList = unspentList.concat(unconfirmed_txrefs.filter((item: any) => !item.spent_by && item.tx_output_n !== -1));
    }
    if (txrefs.length > 0) {
      unspentList = unspentList.concat(txrefs.filter((item: any) => !item.spent_by && item.tx_output_n !== -1));
    }

    // 構建交易對象
    let txb = new bitcoin.TransactionBuilder(NETWORK);

    // 批量插入未花費交易
    unspentList.forEach((item: any) => txb.addInput(item.tx_hash, item.tx_output_n));
    // 轉出帳戶
    txb.addOutput(to, quantitySat);
    // 預留手續費
    txb.addOutput(from, balance - quantitySat - feeSat);
    // 批量簽名,根據索引便可
    unspentList.forEach((item: any, index: any) => { txb.sign(index, keyPair) });
    // 序列化交易
    let tx = txb.build();
    console.log(tx.getHash().toString('hex'));

    // 在一個測試鏈的節點把交易廣佈出去
    const result = await fetch('https://api.blockcypher.com/v1/btc/test3/txs/push',{
      method:'post',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({tx: tx.toHex()})
    });


  } catch (error) {
    console.error(error);
  }
})();
相關文章
相關標籤/搜索