Script
Bitcoin Script¶
The Bitcoin transaction scripting language (hereinafter referred to as Script) is a Forth-like, reverse-Polish-notation, stack-based execution language. Both the locking scripts placed on UTXOs and the unlocking scripts are written in this scripting language. When a Bitcoin transaction is validated, the unlocking script in each input is executed simultaneously (without interfering with each other) with its corresponding locking script to determine whether the transaction meets the spending conditions.
Script is a very simple language, designed with intentional limitations in execution scope. It can run on limited hardware, potentially as simple as embedded devices. It requires only minimal processing and cannot perform many of the sophisticated operations that modern programming languages can. For validating programmable currency, this is a deliberately designed security feature.
Turing Incompleteness¶
The Bitcoin scripting language includes many opcodes, but is intentionally limited in one important way - aside from conditional flow control, there are no loops or complex flow control capabilities. This ensures the language's Turing incompleteness, meaning that scripts have limited complexity and a predictable number of execution steps. Script is not a general-purpose language; these limitations ensure that the language cannot be used to create infinite loops or other types of logic bombs that could be embedded in a transaction to cause a "denial of service" attack against the Bitcoin network. Remember, every transaction is verified by every full node in the network - a restricted language prevents the transaction verification mechanism from being exploited as a vulnerability.
Decentralized Verification¶
The Bitcoin transaction scripting language has no centralized authority - no central entity can override the script, and no central entity saves the script after it has been executed. All information needed to execute the script is already contained within the script itself. Predictably, a script can be executed identically on any system. If your system validates a script, you can be certain that every other system in the Bitcoin network will also validate it, meaning that a valid transaction is valid for everyone, and everyone knows this. This predictability of outcomes is a critically important beneficial feature of the Bitcoin system.
Script Construction¶
Bitcoin's transaction validation engine relies on two types of scripts to validate transactions: locking scripts and unlocking scripts.
A locking script is a spending condition placed on an output: it specifies the conditions that must be met in the future to spend that output.
Because locking scripts often contain a public key or Bitcoin address (public key hash), they were historically called scriptPubKey. In most Bitcoin applications, what we call a "locking script" appears as scriptPubKey in the source code.
An unlocking script is a script that "solves" or satisfies the spending conditions set by a locking script on an output, allowing the output to be consumed.
The unlocking script is part of every Bitcoin transaction input and typically contains a digital signature generated by the user's Bitcoin wallet (via the user's private key). Because unlocking scripts often contain a digital signature, they were historically called ScriptSig. In most Bitcoin application source code, ScriptSig refers to what we call the unlocking script. However, not all unlocking scripts necessarily contain a signature.
UTXOs are permanently recorded on the blockchain, are therefore immutable, and are unaffected by failed referencing attempts in new transactions. Only valid transactions that correctly satisfy the output conditions can treat the output as a "spending source," at which point the output is removed from the UTXO set.
Script Execution Stack¶
Bitcoin's scripting language is called a stack-based language because it uses a data structure known as a stack. A stack is a very simple data structure that can be visualized as a pile of cards. The stack allows two operations: push and pop. Push adds an item to the top of the stack. Pop removes the topmost item from the stack. Operations on the stack can only act on the topmost item. The stack data structure is also known as a "Last-In-First-Out" or "LIFO" queue.
The scripting language executes a script by processing each item from left to right. Numbers (data constants) are pushed onto the stack. Operators (opcodes) push or pop one or more parameters from the stack, operate on them, and may push results back onto the stack. For example, the opcode OP_ADD pops two items from the stack, adds them, and pushes the resulting sum onto the stack.
Conditional operators evaluate a condition and produce a boolean result of TRUE or FALSE. For example, OP_EQUAL pops two items from the stack and pushes TRUE (represented by the number 1) if they are equal, or FALSE (represented by the number 0) if they are not. Bitcoin transaction scripts typically contain conditional opcodes so they can produce a TRUE result indicating a valid transaction.

The vast majority of unlocking scripts point to a public key hash (which is essentially a Bitcoin address), requiring ownership verification to use the funds, but the script itself does not need to be that complex. Any combination of unlocking and locking scripts that results in TRUE is valid.
An example using arithmetic opcodes as a locking script: 3 OP_ADD 5 OP_EQUAL
This locking script can be satisfied by a transaction with this unlocking script as input: 2
The validation software combines the locking and unlocking scripts, resulting in:
When the script is executed, the result is OP_TRUE, and the transaction is valid. Not only is the output locking script of this transaction valid, but the UTXO can also be used by anyone who knows this arithmetic trick (knows the number is 2).
Separate Execution of Unlocking and Locking Scripts¶
In the original version of the Bitcoin client, unlocking and locking scripts existed in concatenated form and were executed sequentially. For security reasons, Bitcoin developers modified this behavior in 2010 due to a vulnerability that "allowed anomalous unlocking scripts to push data onto the stack and corrupt locking scripts."
First, the unlocking script is executed using the stack execution engine. If the unlocking script executes without errors (for example, no "dangling" opcodes), the main stack (not the alternate stack) is copied and the locking script is executed. If the stack data copied from the unlocking script results in "TRUE" when executing the locking script, then the unlocking script has successfully met the conditions set by the locking script, and the input is a valid authorization to use that UTXO. If the result after combining scripts is anything other than "TRUE," the input is invalid because it does not satisfy the conditions set in the UTXO for using those funds.
P2PKH (Pay-to-Public-Key-Hash)¶
Most transactions processed by the Bitcoin network spend outputs locked by "Pay-to-Public-Key-Hash" (P2PKH) scripts. These outputs contain a locking script that locks the input to a public key hash value, commonly known as a Bitcoin address. Outputs locked by P2PKH scripts can be unlocked (spent) by providing a public key and a digital signature created by the corresponding private key.
For example, Alice issues a payment instruction to pay 0.015 bitcoin to Bob's cafe Bitcoin address. The output of this transaction contains a locking script in the following form:
The Cafe Public Key Hash in the script is the cafe's Bitcoin address, but this address is not Base58Check encoded. In fact, the public key hash of most Bitcoin addresses is displayed in hexadecimal, rather than the well-known Base58Check-encoded Bitcoin address starting with 1.
The corresponding unlocking script for the above locking script is:
Combining the two scripts forms the following combined validation script:
<Cafe Signature> <Cafe Public Key> OP_DUP OP_HASH160
<Cafe Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG
Only when the unlocking script matches the conditions set by the locking script will the combined validation script produce a TRUE result. In other words, the transaction execution result will pass (result is TRUE) only when the unlocking script has a valid signature from the recipient - a valid signature obtained from the recipient's private key that matches the public key hash.
Reference: https://wizardforcel.gitbooks.io/masterbitcoin2cn/content/ch06.html