简体   繁体   English

使用 bitcoinjs 发送比特币交易

[英]Sending a bitcoin transaction using bitcoinjs

Can someone please explain how I can send a bitcoin transaction using bitcoinjs???有人可以解释一下我如何使用 bitcoinjs 发送比特币交易吗??? I have setup two wallets using bitcoinjs.我已经使用 bitcoinjs 设置了两个钱包。

I want to send 100000 satoshis from here: 1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM我想从这里发送 100000 satoshis: 1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM

to here: 1HsrKvboax8J3X1sgsRdWybEwnUNWsDw4Y到这里: 1HsrKvboax8J3X1sgsRdWybEwnUNWsDw4Y

In case it's needed here is the last transaction for 1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM如果需要这里是1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM的最后一笔交易

The code I am using is from the bitcoinjs.org website:我使用的代码来自 bitcoinjs.org 网站:

var tx = new bitcoin.TransactionBuilder()

// Add the input (who is paying):
// [previous transaction hash, index of the output to use]
var txId = 'aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31'
tx.addInput(txId, 0)

// Add the output (who to pay to):
// [payee's address, amount in satoshis]
tx.addOutput("1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK", 15000)

// Initialize a private key using WIF
var privateKeyWIF = 'L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'
var keyPair = bitcoin.ECPair.fromWIF(privateKeyWIF)

// Sign the first input with the new key
tx.sign(0, keyPair)

// Print transaction serialized as hex
console.log(tx.build().toHex())
// => 0100000001313eb630b128102b60241ca895f1d0ffca21 ...

// You could now push the transaction onto the Bitcoin network manually
// (see https://blockchain.info/pushtx)

Now I am assuming var txId is the transaction id from the last transaction here现在我假设var txId此处最后一笔交易的交易 ID

Is the `tx.addInput`` where I put the fee? `tx.addInput` 是我收取费用的地方吗? If so is 100 enough?如果是这样,100 就够了吗?

tx.addOutput is obvs so I am okay with that! tx.addOutputtx.addOutput所以我没问题!

Is var privateKeyWIF* where I put the private key from the sending address? var privateKeyWIF*是我将发送地址中的私钥放在哪里吗?

No idea what var keyPair and tx.sign do!不知道var keyPairtx.sign做什么!

Anyone who can help tell me where the details are suppposed to go would be much appreciated!任何可以帮助告诉我细节应该去哪里的人都将不胜感激! For this example pretend my private key for the sender address is 5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF .对于这个例子,假设我的发件人地址的私钥5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF

Cheers干杯

A Bitcoin transaction typically references previous transaction outputs as new transaction inputs.比特币交易通常引用先前的交易输出作为新的交易输入。

First you need to look at your previous transaction.首先,您需要查看之前的交易。 As you can see here or in the snippet above the txId is: 4303caa91ca5a2236396af3bfae26b70a223a2bcee2fe8d23a7b24626c3c4bd2正如您在此处或在 txId 上方的代码段中看到的那样: 4303caa91ca5a2236396af3bfae26b70a223a2bcee2fe8d23a7b24626c3c4bd2

 { "hash":"4303caa91ca5a2236396af3bfae26b70a223a2bcee2fe8d23a7b24626c3c4bd2", "ver":1, "vin_sz":1, "vout_sz":2, "size":225, "weight":900, "fee":18713, "relayed_by":"0.0.0.0", "lock_time":448506, "tx_index":7399058499716239, "double_spend":false, "time":1484590465, "block_index":448507, "block_height":448507, "inputs":[ { "sequence":4294967294, "witness":"", "script":"47304402204fdab6f26efa32f49c79d8c91b5d42ea39760cff5afc34351f8595453bd3c9d102201ff8e25e4ababe3c3515617e90f97516cda50061ad0c02f215e4a008d580ede4012102e801e52ff6e7d1ad0bb46ef6732d8fcfae1e122a47ea5690e084b9fa4a73d106", "index":0, "prev_out":{ "spent":true, "script":"76a914d7819c081b247a146922b8f90f89181b02a3c66f88ac", "spending_outpoints":[ { "tx_index":7399058499716239, "n":0 } ], "tx_index":356328836300976, "value":469871307, "addr":"1LeVYfpp1LQQUBqsmruVW6cMbYrZtmunPr", "n":1, "type":0 } } ], "out":[ { "type":0, "spent":true, "value":469352594, "spending_outpoints":[ { "tx_index":5608049158171792, "n":0 } ], "n":0, "tx_index":7399058499716239, "script":"76a9147adfb2779ee7710b0dffeff8fb77c82867ed43e588ac", "addr":"1CChR9sShAc61MNLhMoLzy87w5DwP6jRvv" }, { "type":0, "spent":true, "value":500000, "spending_outpoints":[ { "tx_index":8253272257190039, "n":0 } ], "n":1, "tx_index":7399058499716239, "script":"76a914a53e0c670a2836baef1ea93de125f1fdd77370dd88ac", "addr":"1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM" } ] }

Your address 1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM shows up as the second output ( index 1 ).您的地址1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM显示为第二个输出( index 1 )。

And the total amount at this address is 500000 satoshis .这个地址的总金额是500000 satoshis

在此处输入图片说明


So, lets create our transaction所以,让我们创建我们的交易

var txb = new bitcoin.TransactionBuilder()
txb.addInput('4303caa91ca5a2236396af3bfae26b70a223a2bcee2fe8d23a7b24626c3c4bd2', 1)

Now we will send 100000 satoshis现在我们将发送 100000 satoshis

txb.addOutput('1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP', 100000)

We need to send the change to some address you own我们需要将更改发送到您拥有的某个地址

txb.addOutput('1cMh228HTCiwS8ZsaakH8A8wze1JR5ZsP', 398130)

What is left is the miner fee.剩下的是矿工费。 You can use online services to estimate the ideal fee.您可以使用在线服务来估算理想的费用。

(in)500000 Satoshis - (out)100000 - (out)398130 = (fee)1870

Now we need to sign the transaction to confirm that you own the input address现在我们需要签署交易以确认您拥有输入地址

var yourAddressPrivateKeyWIF = 'L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'
var yourAddresskeyPair = bitcoin.ECPair.fromWIF(yourAddressPrivateKeyWIF)
txb.sign(0, yourAddresskeyPair)

If you run yourAddresskeyPair.getAdress() the output should be your address 1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM如果你运行yourAddresskeyPair.getAdress()输出应该是你的地址1G4iprWu7Q8tNbQLA8UBM2GearcnzwFrxM

Now you can send your transaction to the network.现在您可以将您的交易发送到网络。 Get raw transaction in hex format:以十六进制格式获取原始交易:

txb.build().toHex()

Paste the result here https://blockchain.info/pushtx or check other solutions here: https://github.com/bitcoinjs/bitcoinjs-lib/issues/839在此处粘贴结果https://blockchain.info/pushtx或在此处检查其他解决方案: https : //github.com/bitcoinjs/bitcoinjs-lib/issues/839

   let bitcoin = require('bitcoinjs-lib');
   const TESTNET = bitcoin.networks.testnet;
   const keyPair = bitcoin.ECPair.makeRandom({ network: TESTNET });
   const { address } = bitcoin.payments.p2pkh({
      pubkey: keyPair.publicKey,
      network: TESTNET,
   });;
   let wif = keyPair.toWIF()
// console.log(address, keyPair.publicKey.toString('hex') , keyPair.privateKey.toString('hex') , wif);

   let fkeyPair = bitcoin.ECPair.fromWIF(fwif , TESTNET);
   const result = await axios.get(`https://testnet.blockchain.info/rawaddr/${fAddress}`);
   let balance = result.data.final_balance;
   let latestTx = result.data.txs[0].hash;
   console.log('testAddress balance:' , balance);
   console.log('latest tx: ', latestTx);
   var txb = new bitcoin.TransactionBuilder(bitcoin.networks.testnet);
   let sendAmount = 15000;
   let fee = 26456;
   let whatIsLeft = balance - fee - sendAmount;
   txb.addInput(latestTx, 1);
   txb.addOutput(f2Address, sendAmount);
   txb.addOutput(f2Address, whatIsLeft);
   txb.sign(0, fkeyPair);
   let body = txb.build().toHex();
   console.log(body);

I am finding a lot of people are confused about that part - "how to post the transaction to the network".我发现很多人对此部分感到困惑 - “如何将交易发布到网络”。 In short, you need access to a separate bitcoin core full node.简而言之,您需要访问一个单独的比特币核心完整节点。 The full nodes include JSON APIs that you post the raw transaction hex to, then the full node basically does the rest of the work for you behind the scenes (broadcasting over the gossip network to the other nodes, which then add the transaction into their own mempools, and then it waits for a miner to process it so it can be added into the blockchain).全节点包括您将原始交易十六进制发布到的 JSON API,然后全节点基本上会在幕后为您完成其余的工作(通过八卦网络向其他节点广播,然后将交易添加到他们自己的节点中) mempools,然后等待矿工处理它,以便将其添加到区块链中)。

There are two main ways to send the transaction to the network (sending it via the JSON RPC APIs in Bitcoin Core, or via the bitcoin-cli):将交易发送到网络有两种主要方式(通过 Bitcoin Core 中的 JSON RPC API 或通过 bitcoin-cli 发送):

  1. You could add a nodeJS library that allows you socket access to webservers, then invoke it as you would any other REST service from your nodeJS code.您可以添加一个 nodeJS 库,允许您通过套接字访问网络服务器,然后像从您的 nodeJS 代码调用任何其他 REST 服务一样调用它。
  2. For testing it is easier to use the "bitcoin-cli" that comes with the full node.对于测试,使用完整节点附带的“bitcoin-cli”更容易。 Make sure your full node is running, SSH onto it, then invoke the sendrawtransaction command from within the bitcoin-cli.确保您的完整节点正在运行,通过 SSH 连接到它,然后从 bitcoin-cli 中调用 sendrawtransaction 命令。 Specifically, from a UNIX prompt, it is one line:具体来说,在 UNIX 提示符下,它是一行:
  •  % bitcoin-cli sendrawtransaction 0000000001186f9f....00000000

That big long hex number IS the transaction HEX that your bitcoinjs code will have generated.那个大的长十六进制数是您的 bitcoinjs 代码将生成的交易十六进制数。 The unconfirmed transaction should appear in your wallet within seconds.未经确认的交易应在几秒钟内出现在您的钱包中。 ie validated, but not yet confirmed.即验证,但尚未确认。

wif老婆

First understand whatwif format is.首先了解什么是wif格式

inputs输入

From github we have: 从github我们有:

Transaction.prototype.addInput = function (hash, index, sequence, scriptSig)

so you have to pass the hash of the transaction and the index (which output will be your input) you should check what a bitcoin tx is所以你必须传递交易的哈希值和索引(输出将是你的输入)你应该检查比特币 tx 是什么

keypair密钥对

Not verified that, but probably keyPair is your Pk and pk.未验证,但可能keyPair是您的 Pk 和 pk。

signatures签名

Please verify also that because I did not, but logically tx.sign(index, keyPair) should sign the tx (SIGHASH_ALL) for the input index with the private key in keyPair .还请验证,因为我没有,但逻辑上tx.sign(index, keyPair)应该使用keyPair 中的私钥对输入index的 tx (SIGHASH_ALL)进行keyPair If you have more than one input of course you must provide a signature for each one.如果您有多个输入,当然您必须为每个输入提供签名。 Take a look at mastering bitcoin看看掌握比特币

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM