One of the trickiest things to code in Bitcoin is validating transactions. Another one is creating transactions. In this chapter, we’ll cover the exact steps to do both. Toward the end of the chapter, we’ll be creating a testnet transaction and broadcasting it.
Every node, when receiving transactions, makes sure that each transaction adheres to the network rules. This process is called transaction validation. Here are the main things that a node checks:
The inputs of the transaction are previously unspent.
The sum of the inputs is greater than or equal to the sum of the outputs.
The ScriptSig successfully unlocks the previous ScriptPubKey.
#1 prevents double-spending. Any input that’s been spent (that is, included in the blockchain) cannot be spent again.
#2 makes sure no new bitcoins are created (except in a special type of transaction called a coinbase transaction; more on that in Chapter 9).
#3 makes sure that the combined script is valid. In the vast majority of transactions, this means checking that the one or more signatures in the ScriptSig are valid.
Let’s look at how each condition is checked.
To prevent double-spending, a node checks that each input exists and has not been spent. This can be checked by any full node by looking at the UTXO set (see Chapter 5). We cannot determine from the transaction itself whether it’s double-spending, much like we cannot ...