bitcoinjs-lib怎么实现多笔交易合并

发布时间:2021-12-18 10:32:19 作者:iii
来源:亿速云 阅读:176

本篇内容主要讲解“bitcoinjs-lib怎么实现多笔交易合并”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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);
  }
})();

到此,相信大家对“bitcoinjs-lib怎么实现多笔交易合并”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. bootstrap table实现横向合并与纵向合并
  2. python如何实现交易记录整合交易类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

bitcoinjs-lib

上一篇:怎么在Shell脚本中逐行读取文件

下一篇:如何进行springboot配置templates直接访问的实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》