如何在bitcoinjs-lib上使用Psbt?

问题描述 投票:0回答:3

我正在尝试创建一个原始交易以发送到区块链。为此,我想在浏览器中执行此操作。

哪里可以买到

nonWitnessUtxo

我在此处概述的所有信息都是我在测试中找到的。 我做的对吗?

const bitcoin = require('bitcoinjs-lib')
const testnet = bitcoin.networks.testnet
const keyPair = bitcoin.ECPair.makeRandom({ network: testnet })
const publicKey = keyPair.publicKey
const { address } = bitcoin.payments.p2pkh({
  pubkey: publicKey,
  network: testnet
})
const privateKey = keyPair.toWIF()
const psbt = new bitcoin.Psbt({ network: testnet })
const txid = '226a14d30cfd411b14bf20b7ffd211f7f206699690c54d456cc1bef70c2de5a6'
const key = bitcoin.ECPair.fromWIF(privateKey, testnet)
psbt.addInput({
  hash: txid,
  index: 0,
  nonWitnessUtxo: Buffer.from('Where can i get this?', 'hex')
})
psbt.addOutput({
  script: Buffer.from('mmpAPZSvhJs1NGw8UaJXEJ9vRByAxProUL', 'hex')
  value: 10000
})
psbt.signInput(0, key)
psbt.validateSignaturesOfInput(0)
psbt.finalizeAllInputs()
psbt.extractTransaction().toHex()

如果有任何帮助,我将不胜感激!

javascript browser ecmascript-6 bitcoin bitcoinjs-lib
3个回答
3
投票

nonWitnessUtxo
是您使用输入 txid 引用的完整原始交易。


2
投票

这个答案适用于那些寻找在浏览器中创建交易的方法,但无法处理的人

bitcoinjs-lib

我使用

bitcore-lib
- https://www.npmjs.com/package/bitcore-lib

const bitcore = require('bitcore-lib')

const firstPrivateKey = new bitcore.PrivateKey()
const secondPrivateKey = new bitcore.PrivateKey() 

const wif = firstPrivateKey.toString()
const toAddress = secondPrivateKey.toAddress().toString()
const satoshiAmount = 10000

const privateKey = bitcore.PrivateKey.fromWIF(wif)
const sourceAddress = privateKey.toAddress(bitcore.Networks.testnet)
const targetAddress = bitcore.Address.fromString(toAddress)
const utxos = [
  {
    address: 'mywRqUpbENhbu5VsYDwiMTJouVK9g2ZEJQ',
    txid: '761693565e82ca176532c52a37fb38cd9f1eb0172a00562b394e60ede0b7df8a',
    vout: 1,
    scriptPubKey: '76a914ca133ceac705b723b91263aa163ea8a45954e49a88ac',
    amount: 0.0001,
    satoshis: 10000,
    height: 1578273,
    confirmations: 338
  }
]
const transaction = new bitcore.Transaction()

transaction.from(utxos)
transaction.to(targetAddress, Number(satoshiAmount))
transaction.change(sourceAddress)
transaction.sign(privateKey)

const serializedTX = tx.serialize()

然后您需要将这个

serializedTX
作为原始交易发送到比特币网络。

附注此示例不起作用,因为存在无效的内容

utxos
。使用
utxos
获取您的
API
,例如
https://bitpay.com/api/addr/${sourceAddress}/utxo
,然后一切都会正常。


0
投票

“我在哪里可以得到这个?”该值可以从这里获得: https://mempool.space/testnet/api/tx/{这里是您的 txId}/hex

© www.soinside.com 2019 - 2024. All rights reserved.