Blockchain By Example
上QQ阅读APP看书,第一时间看更新

Bitcoin scripting

One of the amazing features of the bitcoin system is the ability to set a script defining the conditions that a recipient should validate to spend the bitcoins later, making bitcoin a programmable currency. Fundamentally, all bitcoin transactions have scripts, written in the Bitcoin programming language, included in their inputs and outputs. This language is a Forth-like language offering a set of opcodes or instructions, evaluated from left to right using a stack to determine the success or failure of the script execution.

Normally, the transaction embeds into its inputs an unlocking script commonly called ScriptSig and a locking script called ScriptPubkey into its outputs. When a transaction is validated, the concatenation of both scripts  ScriptPubkey, which protects the output, and the ScriptSig provided by the recipient to prove ownership – must execute successfully (evaluated to true). The following diagram illustrates the location of both scripts and how they are validated:

Bitcoin scripting using different combinations of opcodes enables us to create a wide variety of transaction types. The following table summarizes the standard transaction types:

Lastly, it's worth mentioning that users can define their own locking scripts, but they should ask miners to mine them.

If  you're familiar with C++, you can understand how scripts work under the hood by looking at script interpreter code:  https://github.com/bitcoin/bitcoin/blob/master/src/script/interpreter.cpp .
Moreover, a transaction is considered as standard if it fulfills the requirement defined by  Bitcoin Core's IsStandard() and IsStandardTx() functions. 

We have now clarified the role of scripts but they will make more sense the more practice you get. Let's take a look at an example of how to build and send bitcoin transactions with custom scripts using JavaScript.