O'Reilly logo

Programming Bitcoin by Jimmy Song

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Transaction Creation and Validation

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.

Validating Transactions

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:

  1. The inputs of the transaction are previously unspent.

  2. The sum of the inputs is greater than or equal to the sum of the outputs.

  3. 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.

Checking the Spentness of Inputs

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required