Compare commits

...

17 Commits

Author SHA1 Message Date
Shannon Appelcline
d177b8dc68
Update 04_5_Sending_Coins_with_Automated_Raw_Transactions.md 2026-02-26 12:58:18 -10:00
Shannon Appelcline
841cf40eb1
Update TODO.md 2026-02-26 12:47:02 -10:00
Shannon Appelcline
f9f5335c8e
Update 04_3_Creating_a_Raw_Transaction_with_Named_Arguments.md 2026-02-26 12:46:30 -10:00
Shannon Appelcline
34db2c5164
edits/updates 2026-02-26 12:02:25 -10:00
Shannon Appelcline
cef132dbad
full edit/update 2026-02-26 11:42:59 -10:00
Shannon Appelcline
c8df37d852
updated help listing 2026-02-26 11:36:50 -10:00
Shannon Appelcline
5417668461
more clarification of change & unspent transactions 2026-02-26 10:53:36 -10:00
Shannon Appelcline
3edcfe0aa9
Update 04_2_Creating_a_Raw_Transaction.md 2026-02-26 10:51:21 -10:00
Shannon Appelcline
7f7a5648c6
Update README.md 2026-02-26 10:41:49 -10:00
Shannon Appelcline
eb3abaff61
full edit & update with virtual Bytes and sendall 2026-02-26 10:41:24 -10:00
Shannon Appelcline
6763f49182
Update TODO.md 2026-02-26 10:29:16 -10:00
Shannon Appelcline
f36f9fedc7
Update 04_1_Sending_Coins_The_Easy_Way.md 2026-02-26 09:23:26 -10:00
Shannon Appelcline
35a378d6ed
a new faucet 2026-02-26 09:10:52 -10:00
Shannon Appelcline
8bdbc31593
revised transaction fees for modern uses of SegWit & vB 2026-02-26 09:07:05 -10:00
Shannon Appelcline
b50213ca40
Update TODO.md 2026-02-26 08:56:57 -10:00
Shannon Appelcline
ad29de1a1c
Update 04_0_Sending_Bitcoin_Transactions.md 2026-02-26 07:50:57 -10:00
Shannon Appelcline
04132b46ae
Update TODO.md 2026-02-26 07:32:57 -10:00
10 changed files with 360 additions and 248 deletions

View File

@ -194,7 +194,6 @@ walletprocesspsbt "psbt" ( sign "sighashtype" bip32derivs finalize )
== Zmq ==
getzmqnotifications
```
You can also type `bitcoin-cli help [command]` to get even more extensive info on that command. For example:
```

View File

@ -4,7 +4,7 @@ You're now ready to receive some money at an address you created.
## Get Some Money
To do anything more, you need to get some money. On signet this is done through faucets. Since the money is all pretend, you just go to a faucet, request some money, and it will be sent over to you. We suggest using the faucet at [https://signetfaucet.com/](https://signetfaucet.com/) or [https://signet257.bublina.eu.org/](https://signet257.bublina.eu.org/). If they're not available for some reason, search for "bitcoin signet faucet", and you should find others.
To do anything more, you need to get some money. On signet this is done through faucets. Since the money is all pretend, you just go to a faucet, request some money, and it will be sent over to you. We suggest using the faucet at [https://faucet.coinbin.org/](https://faucet.coinbin.org/) or [https://signet257.bublina.eu.org/](https://signet257.bublina.eu.org/). If they're not available for some reason, search for "bitcoin signet faucet", and you should find others.
To use a faucet, you'll usually need to go to a URL and copy and paste in your address. Afterward, a transaction will be created that sends money from the faucet to you.

View File

@ -1,6 +1,6 @@
# Chapter Four: Sending Bitcoin Transactions
This chapter describes three different methods for sending bitcoins to normal P2PKH addresses from the command line, using only the bitcoin-cli interface.
This chapter describes three different methods for sending bitcoins to normal P2WPKH addresses from the command line, using only the bitcoin-cli interface.
## Objectives for This Chapter
@ -13,7 +13,6 @@ After working through this chapter, a developer will be able to:
Supporting objectives include the ability to:
* Understand Transactions & Transaction Fees
* Understand Legacy & SegWit Transactions
* Use Basic Methods to Send Money
* Use Auto Fee Calculation Methods to Send Money
* Understand the Dangers of Raw Transactions
@ -27,4 +26,3 @@ Supporting objectives include the ability to:
* [Section Four: Sending Coins with Raw Transactions](04_4_Sending_Coins_with_a_Raw_Transaction.md)
* [Interlude: Using Curl](04_4__Interlude_Using_Curl.md)
* [Section Five: Sending Coins with Automated Raw Transactions](04_5_Sending_Coins_with_Automated_Raw_Transactions.md)
* [Section Six: Creating a SegWit Transaction](04_6_Creating_a_Segwit_Transaction.md)

View File

@ -1,59 +1,58 @@
TODO:
* Obviously, this is where the Segwit work starts.
* Also: Fees. There was some question of if mintxfee is still current, or if paytxfee should be used. I haven't seen any evidence of obsolence, but it'd be good to check this and make sure we're still on the best practices.
* Also: sendall as an alternative
==
UNDERSTANDING ADDRESSES MIGHT BE A WHOLE NEW SECTION
==
### Knowing Your Bitcoin Addresses
There are three types of Bitcoin addresses that you can create with the `getnewaddress` RPC command. You'll be using a `legacy` (P2PKH) address here, while you'll move over to a SegWit (P2SH-SegWit) or Bech32 address in [§4.6: Creating a Segwit Transaction](04_6_Creating_a_Segwit_Transaction.md).
As noted above, the foundation of a Bitcoin address is a public key: someone sends funds to your public key, and then you use your private key to redeem it. Easy? Except putting your public key out there isn't entirely secure. At the moment, if someone has your public key, then they can't retrieve your private key (and thus your funds); that's the basis of cryptography, which uses a trap-door function to ensure that you can only go from private to public key, and not vice-versa. But the problem is that we don't know what the future might bring. Except we do know that cryptography systems eventually get broken by the relentless advance of technology, so it's better not to put raw public keys on the 'net, to future-proof your transactions.
Classic Bitcoin transactions created P2PKH addresses that added an additional cryptographic step to protect public keys.
> :book: ***What is a Legacy (P2PKH) address?*** This is a Legacy address of the sort used by the early Bitcoin network. We'll be using it in examples for the next few sections. It's called a Pay to PubKey Hash (or P2PKH) address because the address is a 160-bit hash of a public key. Using a hash of your public key as your address creates a two-step process where to spend funds you need to reveal both the private key and the public key, and it increases future security accordingly. This sort of address remains important for receiving funds from people with out-of-date wallet software.
As described more fully in [§4.6: Creating a Segwit Transaction](04_6_Creating_a_Segwit_Transaction.md), the Block Size Wars of the late '10s resulted in a new sort of address: SegWit. This is the preferred sort of address currently, and should be fully integrated into Bitcoin-Core at this point, but nonetheless we're saving it for §4.6.
SegWit simply means "segregated witness" and it's a way of separating the transaction signatures out from the rest of the transaction to reduce transaction size. Some SegWit addresses will sneak into some of our examples prior to §4.6 as change addresses, which you'll see as addresses that begin with "tb". This is fine because the `bitcoin-cli` entirely supports their usage. But we won't use them otherwise.
There are two addresses of this sort:
> :book: ***What is a P2SH-SegWit (aka Nested SegWit) address?*** This is the first generation of SegWit. It wraps the SegWit address in a Script hash to ensure backward compatibility. The result creates transactions that are about 25%+ smaller (with corresponding reductions in transaction fees).
> :book: ***What is a Bech32 (aka Native SegWit, aka P2WPKH) address?*** This is the second generation of SegWit. It's fully described in [BIP 173](https://en.bitcoin.it/wiki/BIP_0173). It creates transactions that are even smaller but more notably also has some advantages in creating addresses that are less prone to human error and have some implicit error-correction beyond that. It is *not* backward compatible like P2SH-SegWit was, and so some people may not be able to send to it.
There are other sorts of Bitcoin addresses, such as P2PK (which paid to a bare public key, and is deprecated because of its future insecurity) and P2SH (which pays to a Script Hash, and which is used by the first-generation Nested SegWit addresses; we'll meet it more fully in a few chapters).
==
# 4.1: Sending Coins the Easy Way
The `bitcoin-cli` offers three major ways to send coins: as a simple command; as a raw transaction; and as a raw transaction with calculation. Each has their own advantages and disadvantages. This first method for sending coins is also the simplest.
The `bitcoin-cli` offers three major ways to send coins: as one of a few simple commands; as a raw transaction; and as a raw transaction with calculation. Each has their own advantages and disadvantages. This first method for sending coins is also the simplest.
## Set Your Transaction Fee
Before you send any money on the Bitcoin network, you should think about what transaction fees you're going to pay.
> :book: ***What is a transaction fee?*** There's no such thing as a free lunch. Miners incorporate transactions into blocks because they're paid to do so. Not only do they get paid by the network for making the block, but they also get paid by transactors for including their transactions. If you don't pay a fee, your transaction might get stuck ... forever (or, until saved by some of the tricks in [Chapter Five](05_0_Controlling_Bitcoin_Transactions.md)).
> 📖 ***What is a transaction fee?*** There's no such thing as a free lunch. Miners incorporate transactions into blocks because they're paid to do so. Not only do they get paid by the network for making the block, but they also get paid by transactors for including their transactions. If you don't pay a fee, your transaction might get stuck ... forever (or, until saved by some of the tricks in [Chapter Five](05_0_Controlling_Bitcoin_Transactions.md)).
When you're using the simple and automated methods for creating transactions, as outlined here and in [§4.5: Sending Coins with Automated Raw Transactions](04_5_Sending_Coins_with_Automated_Raw_Transactions.md), Bitcoin will calculate transaction fees for you. This is done using Floating Fees, where the `bitcoind` watches how long transactions are taking to confirm and automatically calculates for you what to spend.
You can help control this by putting rational values into your `~/.bitcoin/bitcoin.conf`. The following low-cost values would ensure that there was a minimum transaction fee of 10,000 satoshis per kByte of data in your transaction and request that the floating fees figure out a good amount to get your transaction somewhere into the next six blocks.
You can help control how Floating Fees determines your transaction fees by putting rational values into your `~/.bitcoin/bitcoin.conf`. This is done by setting up to five values. They would usually be placed in the top of your file, but they could be placed in a `[test]`, `[regtest]`, or `[signet]` section if you want to place higher values for your testing (when you're waiting around), but lower values for actual payments on a real network.
| Variable | Default | Explanation |
|----------|---------|-------------|
| `fallbackfee` | 0 | Precise BTC/kvB for transaction if Floating Fees fails |
| `maxtxfee` | .1 | Maximum total BTC for transaction using Floating Fees |
| `mintxfee` | 0.00001 | Minimum BTC/kvB for transaction using Floating Fees |
| `paytxfee` | 0 | Precise BTC/kvB of transaction size without Floating Fees (deprecated) |
| `txconfirmtarget` | 6 | Average confirmations for automated fee calculation using Floating Fees |
Since the `paytxfee` has been deprecated, you'll mostly be depending on `mintxfee` and `txconfirmtarget` (and perhaps `fallbackfee` for testing), which work like this:
1. If `paytxfee` is set, Floating Fees is not used.
2. If there is insufficient data for Floating Fees, `fallbackfee` is used.
3. Otherwise, Floating Fees calculates how much fee is required for your transaction to be accepted within `txconfirmtarget` blocks.
4. Floating Fees sets the transaction fee for your transaction to that value.
5. Floating Fees sees if that value is lower than `mintxfee`, if so it increases your fee to the value of `mintxfee`.
6. Floating Fees sees if the total value would be higher than `maxtxfee`, if so it decreases your fee to the value of `maxtxfee`.
As shown, the default value for `mintxfee` is 0.00001 BTC/kvB or one-one hundredth of a BTC for every virtual kB of data in your transaction. That's the equivalent to 1,000 Satoshis per kvB or (more simply) 1 Satoshi per virtual Byte. The sats/vB or sat/B measure is what most wallets and explorers use nowadays, because small numbers in the range of .1 sat/vB to 10 sat/vB are much easier to understand than values from 0.0001 BTC to 0.000001 BTC. However, Bitcoin Core continues to use the older measures.
> 📖 ***What is a virtual byte or virtual kilobyte?*** Transactions fees used to be measured as BTC/kB, but following the block size wars and the adoption of Segwit, the value was changed to BTC/kvB or sat/vB. The "v" stands for virtual and it reflects the fact that the size of Segwit transactions are "discounted" because their signatures are placed in block space that didn't previously exist. So a virtual byte (or virtual kilobyte) isn't the _actual_ size of a transaction, but the size that you're required to pay for, including discounts.
To put this all in perspective, the average size of a transaction runs as low as 226 bytes for a legacy P2PKH transaction, which discounts down to 144 virtual bytes for a modern P2WPKH transaction. Precise size depends on the number of inputs to your transactions, the number of outputs, what type of Signature system you're using, and how many signatures you have. But assuming an average transaction, here's what it cost if Bitcoin has a current value of $100,000 USD/BTC:
| Transaction Type | Size | `mintxfee` | sat/vB | Satoshi Cost | USD Cost |
|------------------|------|------------|--------|--------------|----------|
| Legacy, 2-output | 226 B | 0.00001 | 1 | 226 | $.23 |
| Legacy, 2-output | 226 B | 0.00003 | 3 | 678 | $.68 |
| Legacy, 2-output | 226 B | 0.0001 | 10 | 2260 | $2.26 |
| SegWit, 2-output | 144 B | 0.00001 | 1 | 144 | $.15 |
| SegWit, 2-output | 144 B | 0.00003 | 1 | 432 | $.43 |
| SegWit, 2-output | 144 B | 0.0001 | 1 | 1440 | $1.44 |
The default values (`mintxfee=0.00001` and `txconfirmtarget=6`) are fine for most real-world use as of this writing, where fees tend to average 1 sat/vB except over short periods (usually hours) of high blockchain usage. And of course those values are just the starting point for the Floating Fees calculation: they'll go higher if the calculations suggest that you need to pay more money to get a transaction in the next 6 blocks.
For testing, where a more immediate response is more important, and where you might not have enough data to calculate Floating Fees, you may want to push the values up, however, perhaps to:
```
fallbackfee=0.0001
mintxfee=0.0001
txconfirmtarget=6
```
However, under the theory that you don't want to wait around while working on a tutorial, we've adopted the following higher values:
```
mintxfee=0.001
txconfirmtarget=1
```
You should enter these into `~/.bitcoin/bitcoin.conf`, in the main section, toward the top of the file or if you want to be sure you never use it elsewhere, under the `[test]` section.
In order to get through this tutorial, we're willing to spend 100,000 satoshis per kB on every transaction (about $10!), and we want to get each transaction into the next block! (To put that in perspective, a typical transaction runs between .25 kB and 1 kB, so you'll actually be paying more like $2.50 than $10 ... if this were real money.)
In order to get through this tutorial, we're willing to spend 10,000 satoshis per kB on every transaction (about a buck and a half for common SegWit transactions), and we want to get each transaction into the next block! (Not recommended for real money!)
After you've edited your bitcoin.conf file, you'll want to kill and restart bitcoind.
```
@ -63,70 +62,182 @@ $ bitcoind -daemon
## Get an Address
You need somewhere to send your coins to. Usually, someone would send you an address, and perhaps give you a signature to prove they own that address. Alternatively, they might give you a QR code to scan, so that you can't make mistakes when typing in the address. In our case, we're going to send coins to `n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi`, which is a return address for an old Tesetnet faucet.
> :book: ***What is a QR code?*** A QR code is just an encoding of a Bitcoin address. Many wallets will generate QR codes for you, while some sites will convert from an address to a QR code. Obviously, you should only accept a QR code from a site that you absolutely trust. A payer can use a bar-code scanner to read in the QR code, then pay to it.
You need somewhere to send your coins to. Usually, someone would send you an address, and perhaps give you a signature to prove they own that address. Alternatively, they might give you a [QR code](03_6_Creating_QR_Codes_for_Addresses.md) to scan, so that you can't make mistakes when typing in the address. In our case, we're going to send coins to `tb1qg3lau83hm9e9tdvzr5k7aqtw3uv0dwkfct4xdn`, which is a return address for one of the Signet faucets.
## Send the Coins
You're now ready to send some coins. This is actually quite simple via the command line. You just use `bitcoin-cli sendtoaddress [address] [amount]`. So, to send a little coinage to the address `n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi` just requires:
You're now ready to send some coins. This is actually quite simple via the command line. You just use `bitcoin-cli sendtoaddress [address] [amount]`. So, to send a little coinage to the address `tb1qg3lau83hm9e9tdvzr5k7aqtw3uv0dwkfct4xdn` just requires:
```
$ txid=$(bitcoin-cli sendtoaddress n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi 0.001)
$ txid=$(bitcoin-cli sendtoaddress tb1qg3lau83hm9e9tdvzr5k7aqtw3uv0dwkfct4xdn 0.001)
$ echo $txid
93250d0cacb0361b8e21030ac65bc4c2159a53de1075425d800b2d7a8ab13ba8
cb48282e86c846b8357374d74e9ea24deeaeb48cf447634a8b951c98cfc559c5
```
> 🙏 To help keep signet faucets alive, try to use the return address of the same faucet you used in the previous chapter on receiving transactions.
Make sure the address you write in is where you want the money to go. Make _double_ sure. If you make mistakes in Bitcoin, there's no going back.
> 🙏 **Save the Faucets!** To help keep Signet faucets alive, try to use the return address of a Signet faucet if one is provided, once you're done testing with coins.
You'll receive a txid back when you issue this command.
> ❕ You may end up with an error code if you don't have enough funds in your wallet to send the transaction. Depending on your current balance `bitcoin-cli getbalance` you may need to adjust the amount to be sent to account for the amount being sent along with the transaction fee. If your current balance is 0.001, then you could try sending 0.0001. Alternatively, it would be better to instead subtract the expected fee given in the error message from your current balance. This is good practice as many wallets expect you to calculate your own amount + fees when withdrawing, even among popular exchanges.
> ⚠️ **WARNING: Picky Input.** The `bitcoin-cli` command actually generates JSON-RPC commands when it's talking to `bitcoind`. JSON-RPC can be really picky. This is an example: if you list the bitcoin amount without the leading zero (i.e. ".001" instead of "0.001"), then bitcoin-cli will fail with a mysterious message, currently `error: Error parsing JSON: .001`.
> :warning: **WARNING:** The `bitcoin-cli` command actually generates JSON-RPC commands when it's talking to the bitcoind. They can be really picky. This is an example: if you list the bitcoin amount without the leading zero (i.e. ".1" instead of "0.1"), then bitcoin-cli will fail with a mysterious message.
> ⚠️ **WARNING: Insufficient Funds.** You may end up with an error code if you don't have enough funds in your wallet to send the transaction. This may be non-intuitive, because you may see you have the funds to cover a transaction, but you could be forgetting about the transaction fee that `sendtoaddress` automatically calculates for you. Depending on your current balance of `bitcoin-cli getbalance`, you may therefore need to adjust the amount to be sent to account for the amount being sent along with the transaction fee.
> :warning: **WARNING:** Even if you're careful with your inputs, you could see "Fee estimation failed. Fallbackfee is disabled." Fundamentally, this means that your local `bitcoind` doesn't have enough information to estimate fees. You should really never see it if you've waited for your blockchain to sync and set up your system with Bitcoin Standup. But if you're not entirely synced, you may see this. It also could be that you're not using a standard `bitcoin.conf`: the entry `blocksonly=1` will cause your `bitcoind` to be unable to estimate fees.
> ⚠️ **WARNING: Insufficient Blocks.** If you see the error "Fee estimation failed. Fallbackfee is disabled" that means that your `bitcoind` doesn't have enough data to estimate fees, probably because the blockchain isn't synced yet. If so, set the `fallbackfee` value noted above, restart your `bitcoind` and try again.
## Examine Your Transaction
You can look at your transaction using your transaction id:
```
$ bitcoin-cli gettransaction $txid
{
"amount": -0.00100000,
"fee": -0.00022200,
"confirmations": 0,
"trusted": true,
"txid": "93250d0cacb0361b8e21030ac65bc4c2159a53de1075425d800b2d7a8ab13ba8",
"fee": -0.00001410,
"confirmations": 4,
"blockhash": "00000000b594f3a382e1b13fac4847d8790dda630f31335e0e0c42abaaaef7b6",
"blockheight": 293297,
"blockindex": 2,
"blocktime": 1772134375,
"txid": "cb48282e86c846b8357374d74e9ea24deeaeb48cf447634a8b951c98cfc559c5",
"wtxid": "f8f52643b864848b668307df03e192bedf0349ba3c067258c9fb698652061f82",
"walletconflicts": [
],
"time": 1592604194,
"timereceived": 1592604194,
"mempoolconflicts": [
],
"time": 1772133414,
"timereceived": 1772133414,
"bip125-replaceable": "no",
"details": [
{
"address": "n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi",
"address": "tb1qg3lau83hm9e9tdvzr5k7aqtw3uv0dwkfct4xdn",
"category": "send",
"amount": -0.00100000,
"vout": 1,
"fee": -0.00022200,
"vout": 0,
"fee": -0.00001410,
"abandoned": false
}
],
"hex": "0200000001e982921bb0189afc486e20bb05cc5825c71a0ba8868043ed04ece9ab0cb12a8e010000006a47304402200fc493a01c5c9d9574f7c321cee6880f7f1df847be71039e2d996f7f75c17b3d02203057f5baa48745ba7ab5f1d4eed11585bd8beab838b1ca03a4138516fe52b3b8012102fd5740996d853ea51a6904cf03257fc11204b0179f344c49739ec5b20b39c9bafeffffff02e8640d0000000000160014d37b6ae4a917bcc873f6395741155f565e2dc7c4a0860100000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac780b1b00"
"hex": "02000000000101356d1fee7ad60b61af6289b394394e83470b7eb31014533bca3753387b1a53af8702000000fdffffff02a086010000000000160014447fde1e37d97255b5821d2dee816e8f18f6bac9420c0300000000001600141026285b51dc0aa759119f4b5f63cb364a5aa8cd02473044022069e48cacbeabe4e83892d84380d2bc01ccb0d7bc253fb1d9e9198e7fbd26544702201e9b1eeb83f380a184f9f24882d8c8aa2a3516fb9013816038578869f8ce5b58012103abf1f9337ad039d7c80f34e9de656cf479de074251ae2601bca7f8c05e984a23ac790400",
"lastprocessedblock": {
"hash": "00000007d62a1ce40b164b7e8b909e743e1a43f1f0a740e5d4d4b776f40d841b",
"height": 293300
}
}
```
You can see not only the amount transferred (.001 BTC) but also a transaction fee (.000222 BTC), which is about a quarter of the .001 BTC/kB minimum fee that was set, which suggests that the transaction was about a quarter of a kB in size.
You can see not only the amount transferred (`0.001` BTC) but also a transaction fee (`0.00001410` BTC).
While you are waiting for this transaction to clear, you'll note that `bitcoin-cli getbalance` shows that all of your money is gone (or, at least, all of your money from a single incoming transaction). Similarly, `bitcoin-cli listunspent` will show that an entire transaction is gone, even if it was more than what you wanted to send. There's a reason for this: whenever you get money in, you have to send it _all_ out together, and you have to perform some gymnastics if you actually want to keep some of it! Once again, `sendtoaddress` takes care of this all for you, which means you don't have to worry about making change until you send a raw transaction. In this case, a new transaction will appear with your change when your spend is incorporated into a block.
If you look at `bitcoin-cli listunspent`, you will see that one of the transactions where you received money (probably from a faucet) is entirely gone. Don't panic! After your `sendtoaddress` has been confirmed, it will be replaced by a new transaction that's dated to the same time as the money you sent out:
```
{
"txid": "cb48282e86c846b8357374d74e9ea24deeaeb48cf447634a8b951c98cfc559c5",
"vout": 1,
"address": "tb1qzqnzsk63ms92wkg3na947c7txe9942xdlajgzs",
"scriptPubKey": "00141026285b51dc0aa759119f4b5f63cb364a5aa8cd",
"amount": 0.00199746,
"confirmations": 4,
"spendable": true,
"solvable": true,
"desc": "wpkh([b8309bae/84h/1h/0h/1/0]02af4466702f92acef7f9e333cfed298740c15ea0fbeaae0c307d41745792483c6)#up0l68qf",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/1/*)#eeegkjmk"
],
"safe": true
}
```
This is all expected. Cryptocurrency doesn't come in bills and coins, like physical money, but instead in singular blobs. If someone sends you 0.01798971 BTC, then that entire amount is stored in the transaction that sent you the money. When you pay someone else, you use that transactions, send part of it to your recipient _and_ send the rest back to yourself as "change", forming a new address. More on that in the next section. Fortunately, `sendtoaddress` takes care of this for you, generating a change address and looping the remaining funds back: that's the additional transaction you see in your wallet (and why a previous transaction disappeared). It'll just take a short time to show up (usually 10 minutes or less if you're using robust transaction-fee values on Signet).
## Send Coins the Even Easier Way
There's perhaps an even easier way to send coins in Bitcoin, though it has less applicability than `sendtoaddress`. It's `sendall` and it works like this:
```
$ bitcoin-cli sendall '["tb1qxe0nn84xxw76jfc0s93g8kuefu2llglcvscy28"]'
{
"txid": "593a8eec3302c76532f6cd5f2e2c0e2f5eb1b3bd9b45d72279ad23b23cf13005",
"complete": true
}
```
You give `sendall` a JSON array of address (just one here), and it'll send _all_ the money from your wallet to those addresses, equally split among them. There are some additional options, such as specifying amounts for certain addresses, with the balance of the funds then being divided among the rest.
If you start with a wallet with multiple transactions:
```
$ bitcoin-cli listunspent
[
{
"txid": "f2351b40729f714abd5eaeb4bd387b97268c89995c0d5f90fc3558954d5911c5",
"vout": 1,
"address": "tb1qxmx50fc06jt67nw6eqdcsm3rexgn6qvcet3rcm",
"label": "",
"scriptPubKey": "001436cd47a70fd497af4ddac81b886e23c9913d0198",
"amount": 0.01798971,
"confirmations": 9,
"spendable": true,
"solvable": true,
"desc": "wpkh([b8309bae/84h/1h/0h/0/2]033dbb8f06ec43956d9f177e43d9d3bb9b2021cf78feb2a48116a984a54ef5a7db)#q3jnn2nv",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/0/*)#gduft8tw"
],
"safe": true
},
{
"txid": "cb48282e86c846b8357374d74e9ea24deeaeb48cf447634a8b951c98cfc559c5",
"vout": 1,
"address": "tb1qzqnzsk63ms92wkg3na947c7txe9942xdlajgzs",
"scriptPubKey": "00141026285b51dc0aa759119f4b5f63cb364a5aa8cd",
"amount": 0.00199746,
"confirmations": 4,
"spendable": true,
"solvable": true,
"desc": "wpkh([b8309bae/84h/1h/0h/1/0]02af4466702f92acef7f9e333cfed298740c15ea0fbeaae0c307d41745792483c6)#up0l68qf",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/1/*)#eeegkjmk"
],
"safe": true
}
]
```
It'll be emptied out by this command:
```
$ bitcoin-cli listunspent
[
]
```
After sufficient blocks have been confirmed, the recipient should see the funds, minus transaction fees (which are by default set to 1 sat/vB, ignoring values such as `mintxfee`).
```
$ bitcoin-cli listunspent
[
{
"txid": "593a8eec3302c76532f6cd5f2e2c0e2f5eb1b3bd9b45d72279ad23b23cf13005",
"vout": 0,
"address": "tb1qxe0nn84xxw76jfc0s93g8kuefu2llglcvscy28",
"label": "",
"scriptPubKey": "0014365f399ea633bda9270f816283db994f15ffa3f8",
"amount": 0.01996947,
"confirmations": 1,
"spendable": true,
"solvable": true,
"desc": "wpkh([b8309bae/84h/1h/0h/0/3]02e60a25d4492c3ddd4a31cdba5d57df163359e623e3fb2eda15b8ffc050e0cc42)#wfg3yz80",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/0/*)#gduft8tw"
],
"safe": true
}
]
```
Why would you do this? Mainly to sweep a wallet.
> 📖 **What is Sweeping?** Sweeping means that you're emptying a wallet (or address) and moving everything to another wallet (or address). This might be done if a wallet's keys have been compromised, if some keys in a multisig have been lost, or if you're consolidating funds to a different location. `bitcoin-cli` is able to sweep your whole wallet because of its descriptor wallets: those function-like descriptions help `bitcoin-cli` to fund all the funds you prossess. There is of course always a fee for moving funds around on Bitcoin, even if you're transferring from one wallet you control to another.
## Summary: Sending Coins the Easy Way
To send coins the easy way, make sure your transaction defaults are rationale, get an address, and send coins there. That's why they call it easy!
To send coins the easy way, make sure your transaction defaults are rationale, get an address, and send coins there. That's why they call it easy! Besides using `sendtoaddress`, you can also use `sendall`, but only if you want to empty a wallet!
> :fire: ***What is the power of sending coins the easy way?***
> _The advantages._ It's easy. You don't have to worry about arcane things like UTXOs. You don't have to calculate transaction fees by hand, so you're not likely to make mistakes that cost you large amounts of money. If your sole goal is to sit down at your computer and send some money, this is the way to go.
> _The advantages._ It's easy. You don't have to worry about arcane things like UTXOs. You don't have to calculate transaction fees by hand, so you're not likely to make mistakes that cost you large amount`s of money. If your sole goal is to sit down at your computer and send some money, this is the way to go.
> _The disadvantages._ It's high level. You have very little control over what's happening, and you can't do anything fancy. If you're planning to write more complex Bitcoin software or want a deeper understanding of how Bitcoin works, then the easy way is just a dull diversion before you get to the real stuff.

View File

@ -1,12 +1,12 @@
# 4.2 Creating a Raw Transaction
You're now ready to create Bitcoin raw transactions. This allows you to send money but to craft the transactions as precisely as you want. This first section focuses on a simple one-input, one-output transaction. This sort of transaction _isn't_ actually that useful, because you're rarely going to want to send all of your money to one person (unless you're actually just forwarding it on, such as if you're moving things from one wallet to another). Thus, we don't label this section as a way to send money. It's just a foundational stepping stone to _actually_ sending money with a raw transaction.
You're now ready to create Bitcoin raw transactions. This allows you to send money but to craft the transactions as precisely as you want. This first section focuses on a simple one-input, one-output transaction. This sort of transaction _isn't_ actually that useful, because you're rarely going to want to send all of your money to one person (unless you're actually just forwarding it on, such as if you're sweeping things from one wallet to another). Therefore, we don't label this section as a way to send money. It's just a foundational stepping stone to _actually_ sending money with a raw transaction.
## Understand the Bitcoin Transaction
Before you dive into actually creating raw transactions, you should make sure you understand how a Bitcoin transaction works. It's all about the UTXOs.
> :book: ***What is a UTXO?*** 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 various payments were made to the same address or to multiple addresses: each incoming transaction remains distinct in your wallet as a UTXO.
> :book: ***What is a UTXO?*** When you receive cash in your Bitcoin wallet, it appears as an individual transaction: a singular blob. Each of these transactions is called a Unspent Transaction Output (UTXO). It doesn't matter if various payments were made to the same address or to multiple addresses: each incoming transaction remains distinct in your wallet as a UTXO.
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. You use these as inputs for a new transaction. Together their amount must equal what you want to spend _or more_. 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.
@ -14,86 +14,73 @@ Here's the trick: _all of the UTXOs that you gather are spent in full!_ That mea
## List Your Unspent Transactions
In order to create a new raw transaction, you must know what UTXOs you have on-hand to spend. You can determine this information with the `bitcoin-cli listunspent` command:
In order to create a new raw transaction, you must know what UTXOs you have on-hand to spend. You can determine this information by returning to an old favorite, `bitcoin-cli listunspent` command:
```
$ bitcoin-cli listunspent
[
{
"txid": "ca4898d8f950df03d6bfaa00578bd0305d041d24788b630d0c4a32debcac9f36",
"txid": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"vout": 0,
"address": "mi25UrzHnvn3bpEfFCNqJhPWJn5b77a5NE",
"label": "",
"scriptPubKey": "76a9141b72503639a13f190bf79acf6d76255d772360b788ac",
"amount": 0.00010000,
"confirmations": 20,
"address": "tb1qr2yek5wu6ce245uexcf624laphdwwu4qlhhggm",
"scriptPubKey": "00141a899b51dcd632aad3993613a557fd0ddae772a0",
"amount": 0.01895537,
"confirmations": 1,
"spendable": true,
"solvable": true,
"desc": "pkh([d6043800/0'/0'/1']02fd5740996d853ea51a6904cf03257fc11204b0179f344c49739ec5b20b39c9ba)#62rud39c",
"desc": "wpkh([b8309bae/84h/1h/0h/1/1]03c548187125947845c252fb14726ff3ce688d1b977235e9b8506c4ad64dfe1ea3)#dutca0cf",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/1/*)#eeegkjmk"
],
"safe": true
},
{
"txid": "61f3b7016bf1ecc3987b8805207e79362e4de8026682e149107999b779426e3a",
"txid": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"vout": 1,
"address": "mjehC2KHzXcBDcwTd4LhZ2GzyzrZ3Kd3ff",
"address": "tb1q8lpqzydarurhsqttvw2qkf2qjxrwdv0kkej2ux",
"label": "",
"scriptPubKey": "76a9142d573900aa357a38afd741fbf24b075d263ea6e088ac",
"amount": 0.00050000,
"confirmations": 3,
"scriptPubKey": "00143fc20111bd1f0778016b63940b25409186e6b1f6",
"amount": 0.00100000,
"confirmations": 1,
"spendable": true,
"solvable": true,
"desc": "pkh([d6043800/0'/0'/3']0278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132)#nhjc3f8y",
"safe": true
},
{
"txid": "91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c",
"vout": 0,
"address": "mjehC2KHzXcBDcwTd4LhZ2GzyzrZ3Kd3ff",
"label": "",
"scriptPubKey": "76a9142d573900aa357a38afd741fbf24b075d263ea6e088ac",
"amount": 0.00022000,
"confirmations": 3,
"spendable": true,
"solvable": true,
"desc": "pkh([d6043800/0'/0'/3']0278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132)#nhjc3f8y",
"desc": "wpkh([b8309bae/84h/1h/0h/0/4]02b412b4329e450c854293c4c4f9d6e716aa9b6f7c7aa622500ddb15f28f215e04)#av5hsrfr",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/0/*)#gduft8tw"
],
"safe": true
}
]
```
This listing shows three different UTXOs, worth .0001, .0005 and .00022 BTC. Note that each has its own distinct txid and remains distinct in the wallet, even the last two, which were sent to the same address.
When you want to spend a UTXO, it's not sufficient to just know the transaction id. That's because each transaction can have multiple outputs! Remember that first chunk of money that the faucet sent us? In the transaction, some money went to us and some went to someone else. The `txid` refers to the overall transaction, while a `vout` says which of multiple outputs you've received. In this list, each of these transactions is the 0th `vout` of a previous transaction, but _that doesn't have to be the case_.
So, txid+vout=UTXO. This will be the foundation of any raw transaction.
This listing shows two different UTXOs, worth .01895537 and .00100000 BTC. Each UTXO will be distinct in your wallet. Most will have different transaction IDs (`txid`), though in this case the funds came from the same transaction, but they're different outputs (`vout`). In other words `txid`+`vout`=UTXO. You'll need to know both of them to spend a transaction.
## Write a Raw Transaction with One Output
You're now ready to write a simple, example raw transaction that shows how to send the entirety of a UTXO to another party. As noted, this is not necessarily a very realistic real-world case.
> :warning: **WARNING:** It is very easy to lose money with a raw transaction. Consider all instructions on sending bitcoins via raw transactions to be _very_, _very_ dangerous. Whenever you're actually sending real money to other people, you should instead use one of the other methods explained in this chapter. Creating raw transactions is extremely useful if you're writing bitcoin programs, but _only_ when you're writing bitcoin programs. (For example: in writing this example for one version of this tutorial, we accidentally spent the wrong transaction, even though it had about 10x as much value. Almost all of that was lost to the miners.)
> ⚠️ **WARNING: Raw Transactions are Dangerous!** It is very easy to lose money with a raw transaction. Consider all instructions on sending Bitcoins via raw transactions to be _very_, _very_ dangerous. Whenever you're actually sending real money to other people, you should instead use one of the other methods explained in this chapter. Creating raw transactions is extremely useful if you're writing Bitcoin programs, but _only_ when you're writing Bitcoin programs. (For example: in writing this example for one version of this tutorial, we accidentally spent the wrong transaction, even though it had about 10x as much value. Almost all of that was lost to the miners.)
### 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 one worth .00050000 BTC because it's the only one with a decent value.
In this case, we're going to be spending the UTXO worth 0.00100000 BTC.
```
$ utxo_txid="61f3b7016bf1ecc3987b8805207e79362e4de8026682e149107999b779426e3a"
$ utxo_txid="f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd"
$ utxo_vout="1"
```
You should similarly record your recipient address, to make sure you have it right. We're again sending some money back to the TP faucet:
You should similarly record your recipient address, to make sure you have it right. This will send the funds to a new address:
```
$ recipient="n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi"
$ recipient="tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl"
```
As always, check your variables carefully, to make sure they're what you expect!
```
$ echo $utxo_txid
61f3b7016bf1ecc3987b8805207e79362e4de8026682e149107999b779426e3a
f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd
$ echo $utxo_vout
1
$ echo $recipient
n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi
tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl
```
That recipient is particularly important, because if you mess it up, your money is _gone_! (And as we already saw, choosing the wrong transaction can result in lost money!) So triple check it all.
@ -101,19 +88,25 @@ That recipient is particularly important, because if you mess it up, your money
Each transaction has a fee associated with. It's _implicit_ when you send a raw transaction: 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: **WARNING:** This is the very dangerous part of raw transactions!! 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_. Or better, don't use raw transactions except as part of a carefully considered and triple-checked program.
> ⚠️ **WARNING: Dangerous Calculations Ahead.** Calculating the transaction fee is a very dangerous part of raw transactions!! 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_. Or better, don't use raw transactions except as part of a carefully considered and triple-checked program.
> :book: ***How much should you spend on transaction fees?*** [Bitcoin Fees](https://bitcoinfees.21.co/) has a nice live assessment. It says that the "fastest and cheapest transaction fee is currently 42 satoshis/byte" and that "For the median transaction size of 224 bytes, this results in a fee of 9,408 satoshis".
> 📖 ***How much should you spend on transaction fees?*** [§4.1](04_1_Sending_Coins_The_Easy_Way.md#set-your-transaction-fee) contains extensive discussions of transaction fees. The TL;DR is that 1 sat/vB is usually sufficient in the modern day, though this course tends to use 10 sat/vB just to ensure that you don't have to sit around waiting for transactions to come back. A Bitcoin Explorer such as the [mempool explorer](https://mempool.space/) can alternatively show you what fees are currently being paid.
Currently Bitcoin Fees suggests a transaction fee of about 10,000 satoshis, which is the same as .0001 BTC. Yes, that's for the mainnet, not signet or testnet, but we want to test out things realistically, so that's what we're going to use.
Assuming a fee of 1 sat/vB and a SegWit transaction that's less than 250 Bytes would mean a fee of 250 satoshis, or 0.0000025 BTC, which would be a quarter if Bitcoin were worth $100,000 each. Not bad! (But we're going to move that up to 0.00001 for quick testing purposes.)
In this case, that means taking the .0005 BTC in the UTXO we're selected, reducing it by .0001 BTC for the transaction fee, and sending the remaining .0004 BTC. (And this is an example of why micropayments don't work on the Bitcoin network, because a $1 or so transaction fee is pretty expensive when you're sending $4, let alone if you were trying to make a micropayment of $0.50. But that's always why we have Lightning.)
You should either enter the amount you're going to be sending into a `$btc` variable or else install `bc` to run the calculation (and it's always better to let the computer do the calculation, as long as you're using a reliable calculator and not AI). Note that you'll probably have to engage in some `awk` tomfoolery to make sure your number has a leading `0`, because `bitcoin-cli` will choke otherwise.
```
$ sudo apt-get install bc
$ btc=$(echo "0.001-0.00001" | bc -l | awk '{printf "%.5f\n", $0}')
$ echo $btc
.00099
```
> :warning: **WARNING:** The lower that you set your transaction fee, the longer before your transaction is built into a block. The Bitcoin Fees site 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.
> :warning: **WARNING: Fee Slowdowns.** The lower that you set your transaction fee, the longer before your transaction is built into a block. Since blocks are built on average every 10 minutes, that could be the difference between a few minutes, a few hours, and never! So, choose a transaction fee that's appropriate for what you're sending.
### Write the Raw Transaction
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.
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 (and that we've touched on from time to time). This time, you're going to have to input a JSON array (`[]`) of objects (`{}`) to list the UTXOs that you're spending and a JSON object (`{}`) to list the outputs.
Here's the standard format:
```
@ -128,13 +121,13 @@ $ bitcoin-cli createrawtransaction
"'$your_recipient'": bitcoin_amount
}'''
```
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"`, but you don't need to protect normal numbers: `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"`, but you don't need to protect normal numbers: `0`. If they're variables, also insert single quotes, like `"'$this_word'"` and `'$this_num'`. (Whew. You'll get used to it.)
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.0004 }''')
$ rawtxhex=$(bitcoin-cli createrawtransaction '''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' '''{ "'$recipient'": '$btc' }''')
$ echo $rawtxhex
02000000013a6e4279b799791049e1826602e84d2e36797e2005887b98c3ecf16b01b7f3610100000000ffffffff01409c0000000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000
0200000001fd296670b9d95353a5a9c1659ef9ad563e714f6fb9e9cc3f4c265ecd9afd7ff60100000000fdffffff01b882010000000000160014f1ad72d46aa89d5e622e42bbbb75064eebd9d10100000000
```
### Verify Your Raw Transaction
@ -143,36 +136,34 @@ You should next verify your rawtransaction with `decoderawtransaction` to make s
```
$ bitcoin-cli decoderawtransaction $rawtxhex
{
"txid": "dcd2d8f0ec5581b806a1fbe00325e1680c4da67033761b478a26895380cc1298",
"hash": "dcd2d8f0ec5581b806a1fbe00325e1680c4da67033761b478a26895380cc1298",
"txid": "8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2",
"hash": "8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2",
"version": 2,
"size": 85,
"vsize": 85,
"weight": 340,
"size": 82,
"vsize": 82,
"weight": 328,
"locktime": 0,
"vin": [
{
"txid": "61f3b7016bf1ecc3987b8805207e79362e4de8026682e149107999b779426e3a",
"txid": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"vout": 1,
"scriptSig": {
"asm": "",
"hex": ""
},
"sequence": 4294967295
"sequence": 4294967293
}
],
"vout": [
{
"value": 0.00040000,
"value": 0.00099000,
"n": 0,
"scriptPubKey": {
"asm": "OP_DUP OP_HASH160 e7c1345fc8f87c68170b3aa798a956c2fe6a9eff OP_EQUALVERIFY OP_CHECKSIG",
"hex": "76a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac",
"reqSigs": 1,
"type": "pubkeyhash",
"addresses": [
"n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi"
]
"asm": "0 f1ad72d46aa89d5e622e42bbbb75064eebd9d101",
"desc": "addr(tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl)#tn6nft96",
"hex": "0014f1ad72d46aa89d5e622e42bbbb75064eebd9d101",
"address": "tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl",
"type": "witness_v0_keyhash"
}
}
]
@ -181,7 +172,7 @@ $ bitcoin-cli decoderawtransaction $rawtxhex
Check the `vin`. Are you spending the right transaction? Does it contain the expected amount of money? (Check with `bitcoin-cli gettransaction` and be sure to look at the right `vout`.) 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?
> :information_source: **NOTE - SEQUENCE:** You may note that each input has a sequence number, set here to 4294967295, which is 0xFFFFFFFF. This is the last frontier of Bitcoin transactions, because it's a standard field in transactions that was originally intended for a specific purpose, but was never fully implemented. So now there's this integer sitting around in transactions that could be repurposed for other uses. And, in fact, it has been. As of this writing there are three different uses for the variable that's called `nSequence` in the Bitcoin Core code: it enables RBF, `nLockTime`, and relative timelocks. If there's nothing weird going on, `nSequence` will be set to 4294967295. Setting it to a lower value signals that special stuff is going on.
> **NOTE: Sequence:** You may note that each input has a sequence number, set here to `4294967293`, which is `0xFFFFFFFF-2`. This is the last frontier of Bitcoin transactions, because it's a standard field in transactions that was originally intended for a specific purpose, but was never fully implemented. So now there's this integer sitting around in transactions that could be repurposed for other uses. And, in fact, it has been. As of this writing there are three different uses for the variable that's called `nSequence` in the Bitcoin Core code: it enables RBF, `nLockTime`, and relative timelocks. It used to always be set to `4294967295` (`0xFFFFFFFF`), which meant "nothing special", but nowadays it's set to `4294967293` (`0xFFFFFFFF-2`), which means "allow Replace-by-Fee by default", which is explained in [§5.2](05_2_Resending_a_Transaction_with_RBF.md). Other values mean other things.
### Sign the Raw Transaction
@ -192,10 +183,11 @@ First, you need to sign your raw transaction:
$ bitcoin-cli signrawtransactionwithwallet $rawtxhex
{
"hex": "02000000013a6e4279b799791049e1826602e84d2e36797e2005887b98c3ecf16b01b7f361010000006a4730440220335d15a2a2ca3ce6a302ce041686739d4a38eb0599a5ea08305de71965268d05022015f77a33cf7d613015b2aba5beb03088033625505ad5d4d0624defdbea22262b01210278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132ffffffff01409c0000000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000",
"hex": "02000000000101fd296670b9d95353a5a9c1659ef9ad563e714f6fb9e9cc3f4c265ecd9afd7ff60100000000fdffffff01b882010000000000160014f1ad72d46aa89d5e622e42bbbb75064eebd9d1010247304402202cc47fe2a529a14765010845eaf393becd91e95df7ba5c142f33a0246382c107022065d7abafe6144e6af899d3311ba59a7c3c9fe8b01df6f022f28ca81fc1eac181012102b412b4329e450c854293c4c4f9d6e716aa9b6f7c7aa622500ddb15f28f215e0400000000",
"complete": true
}
$ signedtx="02000000013a6e4279b799791049e1826602e84d2e36797e2005887b98c3ecf16b01b7f361010000006a4730440220335d15a2a2ca3ce6a302ce041686739d4a38eb0599a5ea08305de71965268d05022015f77a33cf7d613015b2aba5beb03088033625505ad5d4d0624defdbea22262b01210278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132ffffffff01409c0000000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000"
$ signedtx="02000000000101fd296670b9d95353a5a9c1659ef9ad563e714f6fb9e9cc3f4c265ecd9afd7ff60100000000fdffffff01b882010000000000160014f1ad72d46aa89d5e622e42bbbb75064eebd9d1010247304402202cc47fe2a529a14765010845eaf393becd91e95df7ba5c142f33a0246382c107022065d7abafe6144e6af899d3311ba59a7c3c9fe8b01df6f022f28ca81fc1eac181012102b412b4329e450c854293c4c4f9d6e716aa9b6f7c7aa622500ddb15f28f215e0400000000"
```
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, as we'll explain in an upcoming interlude.
@ -204,63 +196,53 @@ Note that we captured the signed hex by hand, rather than trying to parse it out
You've now got a ready-to-go raw transaction, but it doesn't count until you actually put it on the network, which you do with the `sendrawtransaction` command. You'll get back a txid:
```
$ bitcoin-cli sendrawtransaction $signedtx
a1fd550d1de727eccde6108c90d4ffec11ed83691e96e119d842b3f390e2f19a
8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2
```
You'll immediately see that the UTXO and its money have been removed from your wallet:
As usual, you'll immediately see that the UTXO and its money have been removed from your wallet (but you'll have a bit better understanding this time than in [§4.1](04_1_Sending_Coins_The_Easy_Way.m) since you explicitly chose the UTXO to be spent:
```
$ bitcoin-cli listunspent
[
{
"txid": "ca4898d8f950df03d6bfaa00578bd0305d041d24788b630d0c4a32debcac9f36",
"txid": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"vout": 0,
"address": "mi25UrzHnvn3bpEfFCNqJhPWJn5b77a5NE",
"label": "",
"scriptPubKey": "76a9141b72503639a13f190bf79acf6d76255d772360b788ac",
"amount": 0.00010000,
"confirmations": 23,
"address": "tb1qr2yek5wu6ce245uexcf624laphdwwu4qlhhggm",
"scriptPubKey": "00141a899b51dcd632aad3993613a557fd0ddae772a0",
"amount": 0.01895537,
"confirmations": 7,
"spendable": true,
"solvable": true,
"desc": "pkh([d6043800/0'/0'/1']02fd5740996d853ea51a6904cf03257fc11204b0179f344c49739ec5b20b39c9ba)#62rud39c",
"safe": true
},
{
"txid": "91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c",
"vout": 0,
"address": "mjehC2KHzXcBDcwTd4LhZ2GzyzrZ3Kd3ff",
"label": "",
"scriptPubKey": "76a9142d573900aa357a38afd741fbf24b075d263ea6e088ac",
"amount": 0.00022000,
"confirmations": 6,
"spendable": true,
"solvable": true,
"desc": "pkh([d6043800/0'/0'/3']0278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132)#nhjc3f8y",
"desc": "wpkh([b8309bae/84h/1h/0h/1/1]03c548187125947845c252fb14726ff3ce688d1b977235e9b8506c4ad64dfe1ea3)#dutca0cf",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/1/*)#eeegkjmk"
],
"safe": true
}
]
$ bitcoin-cli getbalance
0.00032000
```
Soon `listtransactions` should show a confirmed transaction of category 'send".
But soon `listtransactions` should show a confirmed transaction of category 'send".
```
{
"address": "n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi",
{
"address": "tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl",
"category": "send",
"amount": -0.00040000,
"amount": -0.00099000,
"label": "",
"vout": 0,
"fee": -0.00010000,
"confirmations": 1,
"fee": -0.00001000,
"confirmations": 0,
"trusted": true,
"txid": "a1fd550d1de727eccde6108c90d4ffec11ed83691e96e119d842b3f390e2f19a",
"txid": "8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2",
"wtxid": "f9cfb18a4683a03bae228f3e21a4939803655efaae51e67388673338103543bc",
"walletconflicts": [
],
"time": 1592608574,
"timereceived": 1592608574,
"bip125-replaceable": "no",
"mempoolconflicts": [
],
"time": 1772141891,
"timereceived": 1772141891,
"bip125-replaceable": "yes",
"abandoned": false
}
```
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.
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`, which is _hopefully_ what you intended (and indeed it matches the `0.00001` BTC that was planned, thanks to the wonders of `bc`).
Congratulations! You're now a few satoshis poorer!
@ -270,4 +252,4 @@ When money comes into your Bitcoin wallet, it remains as distinct amounts, calle
## What's Next?
Step Back from "Sending Bitcoin Transactions" with [Interlude: Using JQ](04_2__Interlude_Using_JQ.md).
Step Back from "Sending Bitcoin Transactions" with [Interlude: Using JQ](04_2a_Interlude_Using_JQ.md).

View File

@ -1,17 +1,18 @@
# Interlude: Using JQ
Creating a raw transaction revealed how more complex bitcoin-cli results can't easily be saved into command-line variables. The answer is JQ, which allows you to filter out individual elements from more complex JSON data.
Creating a raw transaction revealed how more complex `bitcoin-cli` results can't easily be saved into command-line variables. The answer is JQ, which allows you to filter out individual elements from more complex JSON data.
## Install JQ
For modern versions of Debian, you should be able to install JQ using `apt-get`:
```
# apt-get install jq
$ sudo apt-get install jq
```
> :book: ***What is JQ?*** The repository explains it best, saying "jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text."
If that works, you're done!
> :book: ***What is JQ?*** The repository explains it best, saying "jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text."
Otherwise, you can download JQ from a [Github repository](https://stedolan.github.io/jq/). Just download a binary for Linux, OS X, or Windows, as appropriate.
Once you've downloaded the binary, you can install it on your system. If you're working on a Debian VPS as we suggest, your installation will look like this:
@ -27,29 +28,29 @@ In the previous section, the use of `signrawtransaction` offered an example of n
```
$ bitcoin-cli signrawtransactionwithwallet $rawtxhex
{
"hex": "02000000013a6e4279b799791049e1826602e84d2e36797e2005887b98c3ecf16b01b7f361010000006a4730440220335d15a2a2ca3ce6a302ce041686739d4a38eb0599a5ea08305de71965268d05022015f77a33cf7d613015b2aba5beb03088033625505ad5d4d0624defdbea22262b01210278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132ffffffff01409c0000000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000",
"hex": "02000000000101fd296670b9d95353a5a9c1659ef9ad563e714f6fb9e9cc3f4c265ecd9afd7ff60100000000fdffffff01b882010000000000160014f1ad72d46aa89d5e622e42bbbb75064eebd9d1010247304402202cc47fe2a529a14765010845eaf393becd91e95df7ba5c142f33a0246382c107022065d7abafe6144e6af899d3311ba59a7c3c9fe8b01df6f022f28ca81fc1eac181012102b412b4329e450c854293c4c4f9d6e716aa9b6f7c7aa622500ddb15f28f215e0400000000",
"complete": true
}
```
Fortunately, JQ can easily capture data of that sort!
To use JQ, run `jq` at the backend of a pipe, and always use the standard invocation of `jq -r '.'`. The `-r` tells JQ to produce raw output, which will work for command-line variables, while the `.` tells jq to output. We protect that argument in `' '` because we'll need that protection later as our `jq` invocations get more complex.
To use JQ, run `jq` at the back end of a pipe, and always use the standard invocation of `jq -r '.'`. The `-r` tells JQ to produce raw output, which will work for command-line variables, while the `.` tells jq to output. We protect that argument in `' '` because we'll need that protection later as our `jq` invocations get more complex.
To capture a specific value from a JSON object, you just list the key after the `.`:
```
$ bitcoin-cli signrawtransactionwithwallet $rawtxhex | jq -r '.hex'
02000000013a6e4279b799791049e1826602e84d2e36797e2005887b98c3ecf16b01b7f361010000006a4730440220335d15a2a2ca3ce6a302ce041686739d4a38eb0599a5ea08305de71965268d05022015f77a33cf7d613015b2aba5beb03088033625505ad5d4d0624defdbea22262b01210278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132ffffffff01409c0000000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000
0200000001fd296670b9d95353a5a9c1659ef9ad563e714f6fb9e9cc3f4c265ecd9afd7ff60100000000fdffffff01b882010000000000160014f1ad72d46aa89d5e622e42bbbb75064eebd9d10100000000
```
With that tool in hand, you can capture information from JSON objects to command-line variables:
```
$ signedtx=$(bitcoin-cli signrawtransactionwithwallet $rawtxhex | jq -r '.hex')
$ echo $signedtx
02000000013a6e4279b799791049e1826602e84d2e36797e2005887b98c3ecf16b01b7f361010000006a4730440220335d15a2a2ca3ce6a302ce041686739d4a38eb0599a5ea08305de71965268d05022015f77a33cf7d613015b2aba5beb03088033625505ad5d4d0624defdbea22262b01210278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132ffffffff01409c0000000000001976a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac00000000
0200000001fd296670b9d95353a5a9c1659ef9ad563e714f6fb9e9cc3f4c265ecd9afd7ff60100000000fdffffff01b882010000000000160014f1ad72d46aa89d5e622e42bbbb75064eebd9d10100000000
```
You can then use those variables easily and without error:
```
$ bitcoin-cli sendrawtransaction $signedtx
3f9ccb6e16663e66dc119de1866610cc4f7a83079bfec2abf0598ed3adf10a78
8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2
```
## Use JQ to Access Single JSON Object Values in an Array by Key
@ -61,23 +62,26 @@ When working with a JSON array, the first thing you need to do is tell JQ which
```
$ bitcoin-cli listunspent | jq -r '.[1]'
{
"txid": "91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c",
"txid": "8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2",
"vout": 0,
"address": "mjehC2KHzXcBDcwTd4LhZ2GzyzrZ3Kd3ff",
"address": "tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl",
"label": "",
"scriptPubKey": "76a9142d573900aa357a38afd741fbf24b075d263ea6e088ac",
"amount": 0.00022,
"confirmations": 9,
"scriptPubKey": "0014f1ad72d46aa89d5e622e42bbbb75064eebd9d101",
"amount": 0.00099000,
"confirmations": 2,
"spendable": true,
"solvable": true,
"desc": "pkh([d6043800/0'/0'/3']0278608b54b8fb0d8379d3823d31f03a7c6ab0adffb07dd3811819fdfc34f8c132)#nhjc3f8y",
"desc": "wpkh([b8309bae/84h/1h/0h/0/5]027650c44c6f71d50a173f3f18858490cf26d2661a1d9929deba9aca57c76d1e5b)#7ss7jfnn",
"parent_descs": [
"wpkh([b8309bae/84h/1h/0h]tpubDDpSvPDUjstxFUEWzHkaL4qykf8vjNCspm8SZ26Z1wgPFbd63AdYrn4bDpEGPT1giJ6gcLW8Xou8fnhi35DJrUza9ikgu5dg2mDkd8jQpA6/0/*)#gduft8tw"
],
"safe": true
}
```
You can then capture an individual value from that selected array by (1) using a pipe _within_ the JQ arguments; and then (2) requesting the specific value afterward, as in the previous example. The following would capture the `txid` from the 1st JSON object in the JSON array produced by `listunspent`:
```
$ bitcoin-cli listunspent | jq -r '.[1] | .txid'
91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c
8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2
```
Carefully note how the `' 's` go around the whole JQ expression _including_ the pipe.
@ -86,7 +90,7 @@ This method can be used to fill in variables for a UTXO that you want to use:
$ newtxid=$(bitcoin-cli listunspent | jq -r '.[1] | .txid')
$ newvout=$(bitcoin-cli listunspent | jq -r '.[1] | .vout')
$ echo $newtxid
91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c
8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2
$ echo $newvout
0
```
@ -99,8 +103,8 @@ Voila! We could now create a new raw transaction using our 1st UTXO as an input,
Instead of accessing a single, specific value in a specific JSON object, you could instead access all of a specific value across all the JSON objects. This is done with `.[]`, where no index is specified. For example, this would list all unspent funds:
```
$ bitcoin-cli listunspent | jq -r '.[] | .amount'
0.0001
0.00022
0.01895537
0.00099000
```
## Use JQ for Simple Calculations by Key
@ -110,10 +114,11 @@ $ bitcoin-cli listunspent | jq -r '.[] | .amount'
At this point, you can start using JQ output for simple math. For example, adding up the values of those unspent transactions with a simple `awk` script would give you the equivalent of `getbalance`:
```
$ bitcoin-cli listunspent | jq -r '.[] | .amount' | awk '{s+=$1} END {print s}'
0.00032
0.0199454
$ bitcoin-cli getbalance
0.00032000
0.01994537
```
(Note the slight difference due to different numbers of significant digits! A `printf` in the `awk` could have improved that, but by default it only goes out to six significant digits; when `bitcoin-cli` offers a value natively, it'll be more accurate with less work!)
## Use JQ to Display Multiple JSON Object Values in an Array by Multiple Keys
@ -124,44 +129,45 @@ JQ can easily capture individual elements from JSON objects and arrays and place
For example, you might want to see a listing of all your UTXOs (`.[]`) and get a listing of all of their most important information (`.txid, .vout, .amount`):
```
$ bitcoin-cli listunspent | jq -r '.[] | .txid, .vout, .amount'
ca4898d8f950df03d6bfaa00578bd0305d041d24788b630d0c4a32debcac9f36
f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd
0
0.0001
91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c
0.01895537
8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2
0
0.00022
0.00099000
```
This makes it easy to decide which UTXOs to spend in a raw transaction, but it's not very pretty.
Fortunately, JQ also lets you be fancy. You can use `{}`s to create new JSON objects (either for additional parsing or for pretty output). You also get to define the name of the new key for each of your values. The resulting output should be much more intuitive and less prone to error (though obviously, less useful for dumping info straight into variables).
The following example shows the exact same parsing of `listunspent`, but with the each old JSON object rebuilt as a new, abridged JSON object, with all of the new values named with their old keys:
The following example shows the exact same parsing of `listunspent`, but with each old JSON object rebuilt as a new, abridged JSON object, with all of the new values named with their old keys:
```
$ bitcoin-cli listunspent | jq -r '.[] | { txid: .txid, vout: .vout, amount: .amount }'
{
"txid": "ca4898d8f950df03d6bfaa00578bd0305d041d24788b630d0c4a32debcac9f36",
"txid": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"vout": 0,
"amount": 0.0001
"amount": 0.01895537
}
{
"txid": "91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c",
"txid": "8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2",
"vout": 0,
"amount": 0.00022
"amount": 0.00099000
}
```
You could of course rename your new keys as you see fit. There's nothing magic in the original names:
```
$ bitcoin-cli listunspent | jq -r '.[] | { tx: .txid, output: .vout, bitcoins: .amount }'
{
"tx": "ca4898d8f950df03d6bfaa00578bd0305d041d24788b630d0c4a32debcac9f36",
"tx": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"output": 0,
"bitcoins": 0.0001
"bitcoins": 0.01895537
}
{
"tx": "91261eafae15ea53dedbea7c1db748c52bbc04a85859ffd0d839bda1421fda4c",
"tx": "8a0d9ab73d81a1ce043d1ede0e737136e6d3352d3e0bc9590f9e8bbd91036dc2",
"output": 0,
"bitcoins": 0.00022
"bitcoins": 0.00099000
}
```
## Use JQ to Access JSON Objects by Looked-Up Value
@ -266,7 +272,7 @@ $ echo ${usedvout[1]}
```
The only real trick here is how we saved the information using the bash shell. Rather than saving to a variable with `$(command)`, we instead saved to an array with `($(command))`. We were then able to access the individual bash array elements with a `${variable[n]}` construction. We could instead access the whole array with `${variable[@]}`. (Yeah, no one ever said bash was pretty.)
> :warning: **WARNING:** Always remember that a UTXO is a transaction _plus_ a vout. We missed the vout the first time we wrote this JQ example, and it stopped working when we ended up with a situation where we'd been sent two `vouts` from the same transaction.
> :warning: **WARNING: txid+vout=UTXO.** Always remember that a UTXO is a transaction _plus_ a vout. We missed the vout the first time we wrote this JQ example, and it stopped working when we ended up with a situation where we'd been sent two `vouts` from the same transaction.
### Retrieve the Related Object(s)
@ -361,7 +367,7 @@ $ bitcoin-cli decoderawtransaction $rawtxhex | jq -r '.vout [] | .value' | awk
```
To complete the transaction fee calculation, you subtract the .vout .amount (1.045) from the .vin .amount (1.3).
To do this, you'll need to install `bc`:
To do this, you'll need to install `bc` if you haven't already:
```
$ sudo apt-get install bc
```
@ -377,7 +383,7 @@ $ echo $(printf '%.8f-%.8f' $btcin $btcout_f) | /usr/bin/bc
```
And that's also a good example of why you double-check your fees: we'd intended to send a transaction fee of 5,000 satoshis, but sent 255,000 satoshis instead. Whoops!
> :warning: **WARNING:** The first time we wrote up this lesson, we genuinely miscalculated our fee and didn't see it until we ran our fee calculator. It's *that* easy, then your money is gone. (The example above is actually from our second iteration of the calculator, and that time we made the mistake on purpose.)
> :warning: **WARNING: Money Goes Poof.** The first time we wrote up this lesson, we genuinely miscalculated our fee and didn't see it until we ran our fee calculator. It's *that* easy, then your money is gone. (The example above is actually from our second iteration of the calculator, and that time we made the mistake on purpose.)
For more JSON magic (and if any of this isn't clear), please read the [JSON Manual](https://stedolan.github.io/jq/manual/) and the [JSON Cookbook](https://github.com/stedolan/jq/wiki/Cookbook). We'll be regularly using JQ in future examples.

View File

@ -1,7 +1,3 @@
TODO:
* Update to non-legayc addresses
* Also add args parameter
# 4.3 Creating a Raw Transaction with Named Arguments
It can sometimes be daunting to figure out the right order for the arguments to a bitcoin-cli command. Fortunately, you can use _named arguments_ as an alternative.
@ -16,7 +12,7 @@ As usual, that's for your ease of use, but we'll continue using the whole comman
## Test Out a Named Argument
To learn what the names are for the arguments of a command, consult `bitcoin-cli help`. It will list the arguments in their proper order, but will now also give names for each of them.
To learn what the names are for the arguments of a command, consult `bitcoin-cli help` for that command. It will list the arguments in their proper order, but will now also give names for each of them.
For example, `bitcoin-cli help getbalance` lists these arguments:
@ -25,7 +21,7 @@ For example, `bitcoin-cli help getbalance` lists these arguments:
3. include_watchonly
4. avoid_reuse
The following shows a traditional, unintuitive usage of `getbalance` using the minimum confirmation argument:
The following shows a traditional, unintuitive usage of `getbalance` using the minimum confirmation argument to only show the balance for transactions with at least one confirmation:
```
$ bitcoin-cli getbalance "*" 1
```
@ -40,41 +36,39 @@ Here's what the commands for sending a raw transaction would look like with name
```
$ utxo_txid=$(bitcoin-cli listunspent | jq -r '.[0] | .txid')
$ utxo_vout=$(bitcoin-cli listunspent | jq -r '.[0] | .vout')
$ recipient="n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi"
$ recipient="tb1qlw280hk7cf7r97sm896s83wysat4vrqzpalm7e"
$ rawtxhex=$(bitcoin-cli -named createrawtransaction inputs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' outputs='''{ "'$recipient'": 0.00001 }''')
$ rawtxhex=$(bitcoin-cli -named createrawtransaction inputs='''[ { "txid": "'$utxo_txid'", "vout": '$utxo_vout' } ]''' outputs='''{ "'$recipient'": 0.01895 }''')
$ bitcoin-cli -named decoderawtransaction hexstring=$rawtxhex
{
"txid": "2b59c31bc232c0399acee4c2a381b564b6fec295c21044fbcbb899ffa56c3da5",
"hash": "2b59c31bc232c0399acee4c2a381b564b6fec295c21044fbcbb899ffa56c3da5",
"txid": "615813d052e48b9761afed8732b78ff67f3ee26390de9e1274418629bd80e45c",
"hash": "615813d052e48b9761afed8732b78ff67f3ee26390de9e1274418629bd80e45c",
"version": 2,
"size": 85,
"vsize": 85,
"weight": 340,
"size": 82,
"vsize": 82,
"weight": 328,
"locktime": 0,
"vin": [
{
"txid": "ca4898d8f950df03d6bfaa00578bd0305d041d24788b630d0c4a32debcac9f36",
"txid": "f67ffd9acd5e264c3fcce9b96f4f713e56adf99e65c1a9a55353d9b9706629fd",
"vout": 0,
"scriptSig": {
"asm": "",
"hex": ""
},
"sequence": 4294967295
"sequence": 4294967293
}
],
"vout": [
{
"value": 0.00001000,
"value": 0.01895000,
"n": 0,
"scriptPubKey": {
"asm": "OP_DUP OP_HASH160 e7c1345fc8f87c68170b3aa798a956c2fe6a9eff OP_EQUALVERIFY OP_CHECKSIG",
"hex": "76a914e7c1345fc8f87c68170b3aa798a956c2fe6a9eff88ac",
"reqSigs": 1,
"type": "pubkeyhash",
"addresses": [
"n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi"
]
"asm": "0 f1ad72d46aa89d5e622e42bbbb75064eebd9d101",
"desc": "addr(tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl)#tn6nft96",
"hex": "0014f1ad72d46aa89d5e622e42bbbb75064eebd9d101",
"address": "tb1q7xkh94r24zw4uc3wg2amkagxfm4an5gpwrgsnl",
"type": "witness_v0_keyhash"
}
}
]
@ -82,15 +76,31 @@ $ bitcoin-cli -named decoderawtransaction hexstring=$rawtxhex
$ signedtx=$(bitcoin-cli -named signrawtransactionwithwallet hexstring=$rawtxhex | jq -r '.hex')
$ bitcoin-cli -named sendrawtransaction hexstring=$signedtx
e70dd2aa13422d12c222481c17ca21a57071f92ff86bdcffd7eaca71772ba172
615813d052e48b9761afed8732b78ff67f3ee26390de9e1274418629bd80e45c
```
Voila! You've sent out another raw transaction, but this time using named arguments for clarity and to reduce errors.
## Undestand Args Parameters
Many RPC commands also have one or more variables designated as "args", which allows them to be input into a `-named` command in the proper order without requiring the name.
For example, where traditionally you'd type this to designate the first two variables for `getbalance`:
```
$ bitcoin-cli -named getbalance dummy="*" minconf=1
```
You can instead type:
```
$ bitcoin-cli -named getbalance "*" minconf=1
```
Because the `dummy` variable is (somewhat inexplicably) defined as an `args` variable.
This technique will _not_ be used in this course because it obfuscates what you're doing and requires lookups in the documents to see what variables you're referring to.
## Summary: Creating a Raw Transaction with Named Arguments
By running `bitcoin-cli` with the `-named` flag, you can use named arguments rather than depending on ordered arguments. `bitcoin-cli help` will always show you the right name for each argument. This can result in more robust, easier-to-read, less error-prone code.
_These docs will use named arguments for all future examples, for clarity and to establish best practices. However, it will also show all arguments in the correct order. So, if you prefer not to use named args, just strip out the '-named' flag and all of the "name="s and the examples should continue to work correctly._
_These docs will use named arguments for all future examples, for clarity and to establish best practices. However, it will also show all arguments in the correct order. So, if you prefer not to use named args, just strip out the '-named' flag and all of the "name="s and the examples should continue to work correctly, except in cases where we've skipped arguments._
## What's Next?

View File

@ -158,6 +158,10 @@ $ bitcoin-cli listunspent
]
```
## Freeze Your Coins
[towrite]
## Summary: Sending Coins with Automated Raw Transactions
If you must send funds with raw transactions then `fundrawtransaction` gives you a nice alternative where fees, inputs, and outputs are calculated for you, so you don't accidentally lose a bunch of money.

View File

@ -39,8 +39,8 @@ If you'd like to make your own translation, please see [Contributing](https://gi
* [3.6: Creating QR Codes for Addresses](03_6_Creating_QR_Codes_for_Addresses.md)
* [3.7: Receiving a Transaction](03_7_Receiving_a_Transaction.md)
* [Interlude: Using Command-Line Variables](03_7a_Interlude_Using_Command-Line_Variables.md)
* [4.0: Sending Bitcoin Transactions](04_0_Sending_Bitcoin_Transactions.md) [**TO UPDATE FOR SEGWIT**]
* [4.1: Sending Coins the Easy Way](04_1_Sending_Coins_The_Easy_Way.md) [**TO UPDATE FOR SEGWIT**]
* [4.0: Sending Bitcoin Transactions](04_0_Sending_Bitcoin_Transactions.md)
* [4.1: Sending Coins the Easy Way](04_1_Sending_Coins_The_Easy_Way.md)
* [4.2: Creating a Raw Transaction](04_2_Creating_a_Raw_Transaction.md) [**TO UPDATE FOR SEGWIT**]
* [Interlude: Using JQ](04_2a_Interlude_Using_JQ.md) [**TO UPDATE FOR SEGWIT**]
* [4.3: Creating a Raw Transaction with Named Arguments](04_3_Creating_a_Raw_Transaction_with_Named_Arguments.md) [**TO UPDATE FOR SEGWIT**]

16
TODO.md
View File

@ -2,14 +2,16 @@
The following TODO items are intended for a 3.0 version of Learning Bitcoin from the Command Line
## Immediate TODO (for 2/19): Sending Transactions
## Immediate TODO (for 2/26): Sending Transactions
1. Change §4.1-4.5 to use P2WPKH (incorporate existing §4.6)
2. Remove legacy address references from the rest of the course
3. Add Freezing Coins to §4.4
4. Remove §4.6 on Segwit
5. Add Info On Sending to Other Addresses (no biggie)
6. Full Review of §4.1-4.5
1. <strike>Rewrite transaction fees in §4.1 to talk about vB, et al</strike>
2. <strike>Add sendall RPC to §4.1</strike>
3. <strike>Add args variable option to §4.3</strike>
4. Change §4.1-4.5 to use P2WPKH
5. Add Freezing Coins to §4.4
6. Remove §4.6 on Segwit
7. Add Info On Sending to Other Addresses (no biggie)
8. Full Review of §4.1-4.5
## Longer-Term TODO (Small Tasks)