Scripts and Script Language

Now we begin our deep dive into Bitcoin scripting! Let's start by reading these sections on scripting.

Script Construction (Lock + Unlock)

A simple script

Now let's apply what we've learned about scripts and stacks to some simple examples.

In Bitcoin's script validation doing simple math, the script 2 3 OP_ADD 5 OP_EQUAL demonstrates the arithmetic addition operator OP_ADD, adding two numbers and putting the result on the stack, followed by the conditional operator OP_EQUAL, which checks that the resulting sum is equal to 5. For brevity, the OP_ prefix is omitted in the step-by-step example.

Although most locking scripts refer to a public key hash (essentially, a bitcoin address), thereby requiring proof of ownership to spend the funds, the script does not have to be that complex. Any combination of locking and unlocking scripts that results in a TRUE value is valid. The simple arithmetic we used as an example of the scripting language is also a valid locking script that can be used to lock a transaction output.

Use part of the arithmetic example script as the locking script:

3 OP_ADD 5 OP_EQUAL

 

which can be satisfied by a transaction containing an input with the unlocking script:

2

 

The validation software combines the locking and unlocking scripts and the resulting script is:

23 OP_ADD 5 OP_EQUAL

 

As we saw in the step-by-step example in Bitcoin's script validation doing simple math, when this script is executed, the result is OP_TRUE, making the transaction valid. Not only is this a valid transaction output locking script, but the resulting UTXO could be spent by anyone with the arithmetic skills to know that the number 2 satisfies the script.

Tip: Transactions are valid if the top result on the stack is TRUE (noted as {0x01}), any other nonzero value, not OP_0, or if the stack is empty after script execution. Transactions are invalid if the top value on the stack is FALSE (a zero-length empty value, noted as {}) or if script execution is halted explicitly by an operator, such as OP_VERIFY, OP_RETURN, or a conditional terminator such as OP_ENDIF.

Figure 5. Bitcoin's script validation doing simple math

The following is a slightly more complex script, which calculates 2 + 7 - 3 + 1. Notice that when the script contains several operators in a row, the stack allows the results of one operator to be acted upon by the next operator:

27 OP_ADD 3 OP_SUB 1 OP_ADD 7 OP_EQUAL

 

Try validating the preceding script yourself using pencil and paper. When the script execution ends, you should be left with the value TRUE on the stack.