Edited Part 3

This commit is contained in:
Shannon Appelcline 2017-03-02 17:01:07 -08:00 committed by GitHub
parent f110a7101f
commit 190297fa55

View File

@ -583,15 +583,17 @@ Using the `sendtoaddress` command isn't necessarily that interesting, if you're
## Part Three: Sending a Raw Transaction to a P2PKH
We're now ready to create Bitcoin rawtransactions. This allows you to send money (as in the interlude above) but to craft the transactions precisely as you want. This section focuses on paying to addresses that are P2PKH: pay to public-key hashes.
You're now ready to create Bitcoin raw transactions. This allows you to send money (as in the interlude above) but to craft the transactions precisely as you want.
This section focuses on paying to addresses that are P2PKH: pay to public-key hashes. In other words: just a normal Bitcoin address, representing some person who wants your money.
## Understand the Bitcoin Transaction
Before we dive into actually creating rawtransactions, you should make sure you understand how a Bitcoin transaction works.
Before you dive into actually creating raw transactions, you should make sure you understand how a Bitcoin transaction works.
When you receive cash in your Bitcoin wallet, it appears as an individual transaction. Each of these transactions is called a Unspent Transaction Output (UTXO). It doesn't matter if multiple bits of money came into the same address or to multiple addresses: each UTXO remains distinct in your wallet.
When you receive cash in your Bitcoin wallet, it appears as an individual transaction. Each of these transactions is called a Unspent Transaction Output (UTXO). It doesn't matter if multiple blobs of money came into the same address or to multiple addresses: each UTXO (incoming transaction) remains distinct in your wallet.
When you create a transaction, you gather together one or more UTXOs, each of which represents a clump of money that you received. Together their amount must equal what you want to spend _or more_. You use these as inputs into the transaction. Then, you generate one or more outputs, which give the money represented by the inputs to one or more people. This creates new UTXOs for the recipients, which may then be used to fund future transactions.
When you create a new outgoing transaction, you gather together one or more UTXOs, each of which represents a blob of money that you received. Together their amount must equal what you want to spend _or more_. You use these as inputs into the new transaction. Then, you generate one or more outputs, which give the money represented by the inputs to one or more people. This creates new UTXOs for the recipients, which may then use _those_ to fund future transactions.
Here's the trick: _all of the UTXOs that you gather are spent in full!_ That means that if you want to send just part of the money in a UTXO to someone else, then you also have to generate an additional output that sends the rest back to you!
@ -599,6 +601,7 @@ Here's the trick: _all of the UTXOs that you gather are spent in full!_ That mea
In order to create a new raw transaction, you must know what UTXOs you have on-hand to spent. You can determine this information with the `bitcoin-cli listunspent` command:
```
$ bitcoin-cli listunspent
[
{
"txid": "ee9805676271f6244eba94c3d1a48b303a8f8359bf711c630eb6f2ea339d0e72",
@ -635,23 +638,28 @@ In order to create a new raw transaction, you must know what UTXOs you have on-h
}
]
```
Here we see a listing of three different UTXOs, worth .08, .078, and .078 BTC. Note that each has its own distinct txi and remains distinct in our wallet, even though two of them were sent to the same address.
This listing shows three different UTXOs, worth .08, .078, and .078 BTC. Note that each has its own distinct txid and remains distinct in the wallet, even though two of them were sent to the same address.
However, when you spend a UTXO you need more than just the transaction id. That's because each transaction can have multiple outputs! The txid just refers to the overall transaction, while a `vout` says which of multiple outputs you've received. In this list, two of our UTXOs are the 0th vout of a transaction, and the other is the 1st. This makes a difference!
However, when you spend a UTXO you need more than just the transaction id. That's because each transaction can have multiple outputs! Remember the example of that first bit of money we got from the faucet: some of it went to us, but some went so someone else (probably a change address). The `txid` just refers to the overall transaction, while a `vout` says which of multiple outputs you've received. In this list, two of our UTXOs are the 0th vout of a transaction, and the other is the 1st. This makes a difference!
So txid+vout=UTXO. This will be the foundation of any rawtransaction.
So txid+vout=UTXO. This will be the foundation of any raw transaction.
### Write a Raw Transaction with One Output
You're now ready to write a simple raw transaction where you're be sending the entirety of a UTXO to another party; that is, you'll be acting like a money launderer, taking all of the money you received in one blob and just passing it on.
#### Prepare the Raw Transaction
For best practices, we'll start out each transaction by carefully recording the txids and vouts that we'll be spending.
In this case, we're going to spend the oldest transaction, because that's the one that's the most validated:
In this case, we're going to spend the oldest transaction, because that's the one that's been validated the most:
```
$ utxo_txid="ee9805676271f6244eba94c3d1a48b303a8f8359bf711c630eb6f2ea339d0e72"
$ utxo_vout="0"
```
> **TESTNET vs MAINNET:** Obviously the "validated the most" criteria would matter a lot more on mainnet, where real money is being used.
You should similarly record your recipient address, to make sure there are no problems. We're sending some money back to the TP faucet:
```
$ recipient="n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi"
@ -669,7 +677,7 @@ That recipient is particularly important, because if you mess it up, your money
#### Write the Raw Transaction
You're now ready to create the raw transaction. This uses the `createrawtransaction` command and it might look a little intimdating. That's because the `createrawtransaction` command doesn't entirely shield you from the JSON RPC that the bitcoin-cli uses. Instead, you are going to input a JSON array to list the UTXOs that you're spending and a JSON object to list the outputs.
You're now ready to create the raw transaction. This uses the `createrawtransaction` command, which might look a little intimidating. That's because the `createrawtransaction` command doesn't entirely shield you from the JSON RPC that the bitcoin-cli uses. Instead, you are going to input a JSON array to list the UTXOs that you're spending and a JSON object to list the outputs.
Here's the standard format:
```
@ -681,16 +689,16 @@ $ bitcoin-cli createrawtransaction
}
]'''
'''{
"'$your_recipient'": $your_amount
"'$your_recipient'": bitcoin_amount
}'''
```
Yeah, there's all kinds of crazy quotes there, but trust they'll do the right thing. Use `'''` to mark the start and end of the JSON array and the JSON object. Protect normal words like `"this"` and normal numbers like `0`. If they're variables, insert single quotes, like `"'$this_word'"` and `'$this_num'`. (Whew. You'll get used to it.)
Yeah, there are all kinds of crazy quotes there, but trust that they'll do the right thing. Use `'''` to mark the start and end of the JSON array and the JSON object. Protect normal words like `"this"` and normal numbers like `0`. If they're variables, insert single quotes, like `"'$this_word'"` and `'$this_num'`. (Whew. You'll get used to it.)
Here's a command that sends creates a raw transaction to send our $utxo to our $recipient
Here's a command that creates a raw transaction to send your $utxo to your $recipient
```
$ rawtxhex=$(bitcoin-cli createrawtransaction '''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' '''{ "'$recipient'": 0.0795 }''')
```
Note that we followed our best practices to immediately save that to variable, because this is another complex result that we don't want to mess up. The result is hex, and here's what it looks like:
Note that we followed our best practices to immediately save that to variable, because this is another complex result that we don't want to mess up. The result is hex, and here's what it looks like:
```
$ echo $rawtxhex
0100000001720e9d33eaf2b60e631c71bf59838f3a308ba4d1c394ba4e24f67162670598ee0000000000ffffffff01b04e7900000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000
@ -736,30 +744,32 @@ $ bitcoin-cli decoderawtransaction $rawtxhex
]
}
```
Check the vin. Is it the right transaction? Verify that it had the right amount of money. Check your vout. Is it the right amount out? Do the math to make sure the money in the transaction in the vin minus the value in the out leaves the transaction fee that you expect. Finally, make sure it's going to the right address(es).
Check the vin. Are you spending the right transaction? Does it contain the expected amount of money? Check your vout. Are you sending the right amount? Is it going to the right address? Finally, do the math to make sure the money balances. Does the value of the UTXO minus the amount being spent equal the expected transaction fee?
#### Understand the Transaction Fee
You'll note that we didn't send the whole .08 BTC to our recipient. That's because you have to pay minor fees to use the Bitcoin network. The amount that you pay as a fee is always equal to the amount of your input minus the amount of your output. So, you have to decrease your output a little bit from your input to make sure that your transaction goes out.
You'll note that we didn't send the whole .08 BTC to our recipient. That's because you have to pay minor fees to use the Bitcoin network. The amount that you will pay as a fee is always equal to the amount of your input minus the amount of your output. So, you have to decrease your output a little bit from your input to make sure that your transaction goes out.
> **WARNING:** This is very dangerous!! Because you automatically pay out all of the amount in the UTXOs that you use, it's critically important to make sure that you know (1) precisely what UTXOs you're using; (2) exactly how much money they contain; (3) exactly how much money you're sending out; and (4) what the difference is. If you mess up and you use the wrong UTXO (with more money than you thought) or if you send out too little money, the excess is lost. Forever. Don't make that mistake! Know your inputs and outputs _precisely_.
> **WARNING:** This is very dangerous!! Because you automatically expend all of the amount in the UTXOs that you use, it's critically important to make sure that you know: (1) precisely what UTXOs you're using; (2) exactly how much money they contain; (3) exactly how much money you're sending out; and (4) what the difference is. If you mess up and you use the wrong UTXO (with more money than you thought) or if you send out too little money, the excess is lost. Forever. Don't make that mistake! Know your inputs and outputs _precisely_.
How much should you spend? [Bitcoin Fees](https://bitcoinfees.21.co/) has a nice live assessment. It told us that the "fastest and cheapest transaction fee is currently 220 satoshis/byte" and that "For the median transaction size of 226 bytes, this results in a fee of 49,720 satoshis". Since this transaction will have just one input and one output, we decided that was more than enough. So, we subtracted 50,000 satoshis, which is .0005 BTC. .0800 BTC - .0005 BC= .0795, which is what we sent.
How much should you spend? [Bitcoin Fees](https://bitcoinfees.21.co/) has a nice live assessment. It says that the "fastest and cheapest transaction fee is currently 220 satoshis/byte" and that "For the median transaction size of 226 bytes, this results in a fee of 49,720 satoshis". Since this transaction will have just one input and one output, we decided that was more than enough. So, we subtracted 50,000 satoshis, which is .0005 BTC. .0800 BTC - .0005 BC= .0795, which is what we sent. (Often transactions don't need to be the "fastest" and can get away with much lower transaction fees; we opted not to because we don't want to delay working through this tutorial.)
> **WARNING:** The lower that you set your transaction fee, the longer before your transaction is built into a block. The Bitcoin Fees lists expected times, from an expected 0 blocks, to 22. Since blocks are built on average every 10 minutes, that's the different between a few minutes and a few hours! So, choose a transaction fee that's appropriate for what you're sending. Note that you should never drop below the minimum relay fee, which is .0001 BTC.
> **WARNING:** The lower that you set your transaction fee, the longer before your transaction is built into a block. The Bitcoin Fees sites lists expected times, from an expected 0 blocks, to 22. Since blocks are built on average every 10 minutes, that's the difference between a few minutes and a few hours! So, choose a transaction fee that's appropriate for what you're sending. Note that you should never drop below the minimum relay fee, which is .0001 BTC.
#### Sign the Raw Transaction
Finally, you need to sign your raw transaction:
To date, your raw transaction is just something theoretical: you _could_ send it, but nothing has been promised. You have to do a few things to get it out onto the network.
First, you need to sign your raw transaction:
```
$ bitcoin-cli signrawtransaction $rawtxhex
{
"hex": "0100000001720e9d33eaf2b60e631c71bf59838f3a308ba4d1c394ba4e24f67162670598ee000000006b483045022100d8f17dadc2501596f75f2c90b8279130e588638d4f7a4f7d5ebb10fea15252f702200ceb164e81335c430893780d06cfe194c36acec26886f180408e3ac4a7d2292f0121035de6239e70523c8f392e32f98e65f6ef704c4b6b0df994e407212b839bf51048ffffffff01b04e7900000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000",
"complete": true
}
signedtx="0100000001720e9d33eaf2b60e631c71bf59838f3a308ba4d1c394ba4e24f67162670598ee000000006b483045022100d8f17dadc2501596f75f2c90b8279130e588638d4f7a4f7d5ebb10fea15252f702200ceb164e81335c430893780d06cfe194c36acec26886f180408e3ac4a7d2292f0121035de6239e70523c8f392e32f98e65f6ef704c4b6b0df994e407212b839bf51048ffffffff01b04e7900000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000"
$ signedtx="0100000001720e9d33eaf2b60e631c71bf59838f3a308ba4d1c394ba4e24f67162670598ee000000006b483045022100d8f17dadc2501596f75f2c90b8279130e588638d4f7a4f7d5ebb10fea15252f702200ceb164e81335c430893780d06cfe194c36acec26886f180408e3ac4a7d2292f0121035de6239e70523c8f392e32f98e65f6ef704c4b6b0df994e407212b839bf51048ffffffff01b04e7900000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000"
```
Note that we captured the signed hex by hand, rather than trying to parse it out of the JSON object.
Note that we captured the signed hex by hand, rather than trying to parse it out of the JSON object. A software package called "JQ" could do better, but for the moment we're keeping things simple and clear.
#### Send the Raw Transaction
@ -820,15 +830,15 @@ Finally, `listtransactions` should soon show a confirmed transaction of category
"abandoned": false
}
```
You can see that it matches our txid and our address. Not only does it show the amount sent, but it also matches the fee we calculated. And, it's already received a confirmation, because we offered a fee that would get us swept up into a block quickly.
You can see that it matches the txid and the recipient address. Not only does it show the amount sent, but it also shows the transaction fee. And, it's already received a confirmation, because we offered a fee that would get it swept up into a block quickly.
Congratulations! You're now a few satoshis poorer!
### Create a Change Address
Our first rawtransaction was very simplistic: we sent the entirety of a UTXO to a new address. More frequently, you'll want to send someone an amount of money that doesn't match a UTXO. But you'll recall that the excess money from a UTXO that's not sent to your recipient just becomes a transaction fee. So, how do you send someone just part of a UTXO, while keeping the rest for yourself (minus a transaction fee, of course)?
Our first raw transaction was very simplistic: we sent the entirety of a UTXO to a new address. More frequently, you'll want to send someone an amount of money that doesn't match a UTXO. But you'll recall that the excess money from a UTXO that's not sent to your recipient just becomes a transaction fee. So, how do you send someone just part of a UTXO, while keeping the rest for yourself?
The answer is that you create a change address:
The solution is to create a change address:
```
$ changeaddress=$(bitcoin-cli getnewaddress)
$ echo $changeaddress
@ -838,7 +848,7 @@ You now have an additional address inside your wallet that you can use to receiv
### Write a Raw Transaction with Two Outputs
You're now ready to write a more complex rawtransaction. It will be based on the two unspent UTXOs still in our wallet:
You're now ready to write a more complex raw transaction. It will be based on the two unspent UTXOs still in our wallet:
```
$ bitcoin-cli listunspent
[
@ -866,11 +876,11 @@ $ bitcoin-cli listunspent
}
]
```
We want to send 0.1 BTC back to the TP faucet. This requires combining our two UTXOs, because neither contains quite that amount of bitcoin. It also requires sending to two addresses: one for the TP faucet (n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi) and one for a change address (mxU9cmhJfkKWDtBspHaA36LkeafEDeaogJ). In other words, we're going to have two inputs and two outputs in our raw transaction
We want to send 0.1 BTC back to the TP faucet. This requires combining our two UTXOs, because neither contains quite that amount of bitcoin. It also requires sending to two addresses: one for the TP faucet (n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi) and one as a change address (mxU9cmhJfkKWDtBspHaA36LkeafEDeaogJ). In other words, we're going to have two inputs and two outputs in our raw transaction
#### Set Up Your Variables
We've already got `$changeaddress` and `$recipient` from our previous example:
We've already have `$changeaddress` and `$recipient` variables from our previous examples:
```
$ echo $changeaddress
mxU9cmhJfkKWDtBspHaA36LkeafEDeaogJ
@ -902,9 +912,9 @@ Here's the example. Take a look at it carefully to understand where the inputs e
```
rawtxhex2=$(bitcoin-cli createrawtransaction '''[ { "txid": "'$utxo_txid_1'", "vout": '$utxo_vout_1' }, { "txid": "'$utxo_txid_2'", "vout": '$utxo_vout_2' } ]''' '''{ "'$recipient'": 0.1, "'$changeaddress'": 0.0555 }''')
```
We were _very_ careful figuring out our money math. These two UTXOs contain .156 BTC. After sending .1 BTC, we'll have .056 BTC left. We again chose .0005 BTC for the transaction fee: this transaction is a little bigger, but that should still be enough to make this transaction go through quickly. To accomodate that, we set our change to .0555 BTC. If we'd messed up our math and instead set our change to .051 BTC, that additional .0045 BTC would be lost. That's $5 or $6 gone to the miners when it didn't need to. If we'd forgot to make change at all, then the whole .056 ($70!) would have disappeared. So, again, _be careful_.
We were _very_ careful figuring out our money math. These two UTXOs contain .156 BTC. After sending .1 BTC, we'll have .056 BTC left. We again chose .0005 BTC for the transaction fee: this transaction about twice as big, but it's still under the average transaction size quoted by Bitcoin Fees, so that should be more than enough to make this transaction go through quickly. To accomodate that fee, we set our change to .0555 BTC. If we'd messed up our math and instead set our change to .051 BTC, that additional .0045 BTC would be lost. That's $5 or $6 gone to the miners when it didn't need to be. If we'd forgot to make change at all, then the whole .056 ($70!) would have disappeared. So, again, _be careful_.
Back to the rawtransaction itself: we'll be honest, it took us a few times to get all the commas, quotes, and brackets in the right places, writing from the command line. We got JSON errors when we didn't format things quite right, and our variable got filled with the hex when we fixed those errors. So, as always, be careful here too, and check your work:
Back to the raw transaction itself: we'll be honest, it took us a few times to get all the commas, quotes, and brackets in the right places, writing from the command line. We got JSON errors when we didn't format things quite right; when we fixed the errors, our variable (correctly) got filled with the hex for the raw transaction. So, as always, be careful here too, and check your work:
```
$ bitcoin-cli decoderawtransaction $rawtxhex2
{
@ -966,7 +976,7 @@ $ bitcoin-cli decoderawtransaction $rawtxhex2
```
#### Finish It Up
You can now sign, seal, and deliver your transaction, and it's yours (and the faucets):
You can now sign, seal, and deliver your transaction, and it's yours (and the faucet's):
```
$ bitcoin-cli signrawtransaction $rawtxhex2
{
@ -979,9 +989,9 @@ $ bitcoin-cli sendrawtransaction $signedtx2
```
#### Wait
As usual, your money will be in flux for a while. You used all of your UTXOs, so your `getbalance` may show that you have cash, but the transaction must be confirmed before you'll see a UTXO with your change.
As usual, your money will be in flux for a while. You used all of your UTXOs, so your `getbalance` may show that you have cash, but the transaction must be confirmed before you see a UTXO with your change.
But, in 10 minutes or less (probably), you'll have your money back and fully spendable again:
But, in 10 minutes or less (probably), you'll have your remaining money back and fully spendable again:
```
$ bitcoin-cli listunspent
[
@ -1003,7 +1013,7 @@ This also might be a good time to revisit a blockchain explorer, so that you can
### Optional: Write a Raw Transaction with Automatic Funding
The purpose of this tutorial is to show you the very basics of Bitcoin scripting, so that you can work at things at a fundamental level. If you were writing a wallet or something other Bitcoin software, you'd probably want to do things exactly as described here. However, if you were for some reason regularly sending bitcoins about through rawtransactions created by hand, then you'd want to have a little better insurance that you weren't making mistakes.
The purpose of this tutorial is to show you the very basics of Bitcoin raw transactions, so that you can work at things at a fundamental level. If you were writing a wallet or something other Bitcoin software, you'd probably want to do things exactly as described here. However, if you were (satoshi forfend!) regularly sending bitcoins about through raw transactions created by hand, then you'd want to have a little better insurance that you weren't making mistakes.
The bitcoin-cli accomodates this with a `fundrawtransaction` command. First, you have to make sure that your ~/.bitcoin/bitcoin.conf file has some rational variables for calculating transaction fees. We've been quite aggressive with fees in this tutorial, to make sure the examples finish quickly, but the following would allow for cheaper transmissions that might take a few hours:
```
@ -1011,7 +1021,7 @@ The bitcoin-cli accomodates this with a `fundrawtransaction` command. First, you
mintxfee=0.0001
txconfirmtarget=25
```
With that in hand you create `createrawtransaction` with just your output(s), then run `fundrawtransaction` on the resulting hex:
With that in hand (and in bitcoin.conf) you can use `createrawtransaction` with just your output(s), then run `fundrawtransaction` on the resulting hex:
```
$ unfinishedtx=$(bitcoin-cli createrawtransaction '''[]''' '''{ "'$recipient'": 0.04 }''')
$ bitcoin-cli fundrawtransaction $unfinishedtx
@ -1020,9 +1030,9 @@ $ bitcoin-cli fundrawtransaction $unfinishedtx
"changepos": 0,
"fee": 0.00004520
}
rawtxhex3="0100000001aec98249082a086dd7ef614f04b8621f9bba4566b8921cbe5d73f7e391a7f1180100000000feffffff0208951700000000001976a914f26e11dc0fcc79fe76fca1d24d7588798922ca7488ac00093d00000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000"
$ rawtxhex3="0100000001aec98249082a086dd7ef614f04b8621f9bba4566b8921cbe5d73f7e391a7f1180100000000feffffff0208951700000000001976a914f26e11dc0fcc79fe76fca1d24d7588798922ca7488ac00093d00000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000"
```
You'll of course want to check the output:
It seems like magic, but when you examine the raw transaction, you'll see it works:
```
$ bitcoin-cli decoderawtransaction $rawtxhex3
{
@ -1073,7 +1083,7 @@ $ bitcoin-cli decoderawtransaction $rawtxhex3
]
}
```
As you can see, it chose UTXOs for the inputs, it created a change address, it calculated a (low) transaction fee based on the variables in the bitcoin.conf file, and it send the amount of the UTXO minus the tx fee back.
As you can see, `fundrawtransaction` chose UTXOs for the inputs, it created a change address, it calculated a (low) transaction fee based on the variables in the bitcoin.conf file, and it sent the amount of the UTXO minus the tx fee back to the change address.
You can even verify that the new address belongs to you:
```