The stack-based Script language

Script

    lang

Bitcoin has its own programming language called Script. This language is used to define the conditions that lock satoshis to a public key or address and to express the necessary knowledge to unlock them.

Some of the most import properties of the Script language are:

Script is a stack-based language, i.e. there are no memory objects like variables or arrays that can be accessed by a program. All a program can do is manipulating the items of a data structure called the stack. The items of the stack are always accessed beginning from the top of the stack (last-in-first-out). Data can be pushed to the stack or popped off the stack and more complex operations can be executed on several items of the stack at a time. The language is very restricted and by design Turing incomplete. It does not allow a program to contain jumps or loops and during the existence of bitcoin even more basic operations like multiplication of two items of the stack have been disabled. All these are proactive security measures to keep programs as simply as possible. The execution of a program has no initial state outside the content of the program itself and the stack is cleared after validation.

Programs

 scripts

The programs written in the Script language are called scripts. A script consists of commands and is executed from left to right. There are only two kinds of commands allowed in a script:

Elements are byte arrays with raw data that are automatically pushed on to the stack when executed. An element can contain arbitrary data up to a length of 520 bytes encoding for example a public key or a hash. The other kind of commands are functions that operate on the stack called OpCodes. They are encoded in a single byte. It is not possible to include executable operators in an element. This restriction was upheld by the decision not to introduce mechanisms for adding an item of the stack back to the script itself.

Verification

     ⟨1⟩

A script can interrupt during execution caused by an error (e.g., accessing items of an empty stack or an unsuccessful OP_VERIFY operation). In this case the script validates as false. If a script executes without error the final state of the stack has to be examined to determine the status of validation. If the item on top of the stack is ⟨1⟩ the script validates as true. In all other cases it validates as false.

The commands of two scripts can be concatenated to create a new combined script. The verification of a transaction includes the validation of the unlock scripts of the inputs of the transaction combined with their respective lock scripts. If the combined script (unlock script + lock script) validates as true the locked amount of satoshis can be spend.