Welcome to first part of stories about Bitcoin script. And this article is just an introduction to bitcoin protocol and explains what bitcoin script actually is.
What is bitcoin script.
Bitcoin protocol uses stack-based script execution to prove spending UTXO. It’s quite simple. What is needed to understand is stack concept.
Stack is commonly used in programs’ execution flow to provide right sequence of function calls and rolling them back with certain order. To explain it, let’s imagine a pile of papers. When you put some new paper on top of this pile, you can easily get it back from the pile. But if you’ve put some amount of papers on the pile and you need to get certain paper which is obviously not on top of the pile, what should you do is retrieve papers one by one until needed paper is found. Stack works similar. Also, stack are known as LIFO (Last In — First Out) and has put/get commands known as Push/Pop. That’s it, stack concept explained. Figure 1 shows it graphically. You cant read this article to understand stack term more deeply.
Let’s use stack to perform some calculations, e.g. summarize two numbers. First number is 5, and second — 9. In terms of math it looks like: 5 + 9 = 14. But we want to perform this calculations with stack. And we should start from empty stack. Now we can put first number onto the stack. Let’s define name of put command OP_PUSH. So we will have the next expression: OP_PUSH 5. We can put second number onto the stack by the same way: OP_PUSH 9. Great, we have two numbers on the stack. Finally we can get sum of those two numbers. Let’s define name of sum command OP_ADD. As we assume that two numbers are already placed on the stack we should just call OP_ADD command.
Script looks like:
OP_PUSH 5 OP_PUSH 9 OP_ADD
In Bitcoin case we should put onto stack a bool value to make script valid. For this purpose let’s define OP_EQUAL command, which will check if two numbers on the stack are equal.
And final script is:
OP_PUSH 14 OP_PUSH 5 OP_PUSH 9 OP_ADD OP_EQUAL
Flow is simply like that: Put 14 on the stack, then put 5 on the stack and then put 9 on the stack. Summarize two numbers from top of the stack and put result on top of the stack. Check two numbers and put true if they’re equal and false otherwise.
This is the simplest explanation of Bitcoin script. All is needed to know is how stack works, and that’s it.
Next article is here.