Complex Scripts

Let's finish by learning about conditional clauses and flow control, and taking a look at some examples of complex scripts.

Scripts with Flow Control (Conditional Clauses)

One of the more powerful features of Bitcoin Script is flow control, also known as conditional clauses. You are probably familiar with flow control in various programming languages that use the construct IF...THEN...ELSE. Bitcoin conditional clauses look a bit different, but are essentially the same construct.

At a basic level, bitcoin conditional opcodes allow us to construct a redeem script that has two ways of being unlocked, depending on a TRUE/FALSE outcome of evaluating a logical condition. For example, if x is TRUE, the redeem script is A and the ELSE redeem script is B.

Additionally, bitcoin conditional expressions can be "nested" indefinitely, meaning that a conditional clause can contain another within it, which contains another, etc. Bitcoin Script flow control can be used to construct very complex scripts with hundreds or even thousands of possible execution paths. There is no limit to nesting, but consensus rules impose a limit on the maximum size, in bytes, of a script.

Bitcoin implements flow control using the IF, ELSE, ENDIF, and NOTIF opcodes. Additionally, conditional expressions can contain boolean operators such as BOOLAND, BOOLOR, and NOT.

At first glance, you may find the bitcoin's flow control scripts confusing. That is because Bitcoin Script is a stack language. The same way that 1 {plus} 1 looks "backward" when expressed as 1 1 ADD, flow control clauses in bitcoin also look "backward".


In most traditional (procedural) programming languages, flow control looks like this:

Pseudocode of flow control in most programming languages:

 code to run when condition istrue
 code to run when condition isfalse
code to run in either case


In a stack-based language like Bitcoin Script, the logical condition comes before the IF, which makes it look "backward," like this:

Bitcoin Script flow control:

 code to run when condition istrue
 code to run when condition isfalse
code to run in either case


When reading Bitcoin Script, remember that the condition being evaluated comes before the IF opcode.

Source: Andreas M. Antonopoulos,
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 License.