BTC#: The Stack

Series: BTC# – Learning to Program Bitcoin in C#

« Previous: Script Parsing

Next: Stack Machine Operations »

Before getting into the content of the chapter on Bitcoin script, let’s have a quick refresher on the stack.


Bitcoin Script is a stack-oriented language. So just remind me again exactly what a stack is and how it works…

A stack is a last-in-first-out (LIFO) filing system. It’s like a stack of papers and books on a desk that have been piled up in whatever order they’ve been used. The oldest thing is at the bottom and the most recent thing is at the top.

The reason it’s referred to as a last-in-first-out system is that the most accessible item is the last one to be added. It has to be removed first to get to those underneath.


In computing, a stack is an area of memory where numbers can be temporarily stored while something else happens and then recovered when that task is complete.

For example, a program may have a set of numbers in the CPU’s registers and need to call a subroutine. Before calling the subroutine it pushes the current state of the registers onto the stack and then, once the subroutine completes, it pops the values back off into the original registers.

In a stack-oriented language like PostScript or Bitcoin script the operands are pushed onto the stack and the operator pops them off to perform its operation. An addition might be expressed something like

2 3 ADD

Putting the operator at the end, after all the operands, is called postfix notation.

Program execution proceeds from left to right. The first two things encountered are numbers. They’re not operators so they’re pushed onto the stack. When the ADD instruction is encountered that instruction is executed. The ADD operator takes two arguments, which it pops from the stack. It adds them together and then pushes the result to the stack so that some other calculation can use it later.


Subsequent calculations can carry on using whatever’s been put on the stack by previous operations.


In Bitcoin, transactions are validated by combining scripts from transaction inputs with scripts from the transaction outputs (UTXOs) they’re spending from. The two script parts are concatenated and run together. Typically the input script will put values on to the stack that satisfy the spending conditions in the output script.

« Previous: Script Parsing

Next: Stack Machine Operations »

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s