Bitcoin Scripts and Advanced Spending Conditions
Most introductions to Bitcoin say something like this: Coins belong to an address, and the owner spends them with a signature.
That description is useful, but it hides an important detail. The blockchain does not really store balances or a table of addresses. Instead, each unspent transaction output contains a small program. This program describes the condition that must be satisfied for the coins in that output to be spent.
These programs are called scripts. They are written in a very simple, stack based language. When you spend an output, your transaction provides data and sometimes extra opcodes that are combined with the original script and executed. If the script finishes with a result that means “true”, the spend is valid.
Most outputs use standard templates such as “pay to the hash of a public key”. Bitcoin scripting can do more than that. It can express advanced conditions such as:
-
Multisignature rules where several keys must cooperate
Timelocks that enforce waiting periods or relative delays
Combinations like “this key now, or several keys together later”
This article first gives brief definitions of the core ideas. Then it goes deeper into multisignature and timelocks as examples of advanced spending conditions that are widely used in practice.
1. Core ideas in brief
1.1 Locking and unlocking scripts
Every transaction output has a locking script. This script describes the condition for spending that output. Historically this script was often called scriptPubKey.
Every transaction input that spends some previous output provides an unlocking script. This script supplies data, such as signatures and public keys, and sometimes additional opcodes. It was historically called scriptSig.
When a node checks an input that spends a given output, it conceptually does the following:
Takes the unlocking script from the input and the locking script from the output.
Concatenates them into a single script.
Executes that combined script using the transaction as context.
If the combined script finishes successfully and leaves a truthy value on top of the stack, the input is considered valid.
1.2 Standard script templates
In practice, most outputs follow a small set of standard templates. These templates are chosen because they are efficient, secure and widely supported.
Some important examples:
Pay to public key hash, often abbreviated as P2PKH
Pay to script hash, P2SH
Native Segregated Witness forms such as P2WPKH and P2WSH
These templates hide the messy parts of the script from users. Wallets present simple addresses and manage the script construction internally.
1.3 Script language properties
Bitcoin Script is intentionally limited. It has:
A stack of values
Simple arithmetic and comparison opcodes
Cryptographic checks such as signature verification
Conditional flow with OP_IF and OP_ELSE
It does not have loops that can run forever. It does not have variables in the usual sense. These restrictions make script evaluation predictable and prevent certain classes of denial of service attacks.
1.4 Advanced spending conditions
An advanced spending condition is anything more complex than “provide one signature from one key”. Common examples include:
-
Multisignature policies such as “any two of these three keys must sign”.
Timelocks that say “coins can only be spent after this time or height”.
Branching conditions such as “either X with path A or Y with path B”.
These are not separate features, they are patterns built from the same basic script language.
2. How a simple payment script works
Before exploring advanced conditions, it helps to understand the common pay to public key hash template in some detail. This template is still a foundation for many other constructions.
2.1 The locking script for a simple payment
A typical P2PKH locking script can be described conceptually as:
Take a public key from the stack.
Hash it.
Check that the hash equals the one stored in the script.
Check that the provided signature is valid for this public key and transaction.
The actual opcodes implement these steps. The important point is that the locking script contains a fixed hash of the expected public key, not the public key itself.
2.2 The unlocking script when spending
When you spend an output locked by that script, your wallet provides an unlocking script that:
Pushes a digital signature to the stack.
Pushes the full public key corresponding to your private key.
When the combined script executes, the public key is hashed and compared, and the signature is verified. If everything matches, the node accepts that you controlled the required private key at the time you signed.
// Example: P2PKH (Pay to Public Key Hash)
// Locking script (scriptPubKey)
// Concept: "Pay to the hash of a public key"
OP_DUP
OP_HASH160
<20-byte-pubKeyHash>
OP_EQUALVERIFY
OP_CHECKSIG
// Unlocking script (scriptSig)
// Concept: "Here is my signature and full public key"
<signature>
<full-public-key>
2.3 What this means conceptually
From a higher perspective, this simple template expresses the rule:
These coins belong to whoever can present a valid signature from the owner of the private key that matches this public key hash.
The blockchain does not know or care about names, accounts or passwords. It only enforces that rule via script.
3. Pay to script hash and hiding complexity
Advanced conditions often require longer scripts. Storing long scripts directly in every output would be inefficient, and it would reveal details of your spending policy even before you spend.
Pay to script hash introduces a useful indirection.
3.1 The basic idea of P2SH
Instead of putting the full spending script in the output, P2SH does the following:
Take a redeem script. This redeem script describes the full spending condition, which might involve several keys, timelocks or branches.
Hash this redeem script.
Use a standard short script template that only checks this hash.
The locking script in the output now simply says conceptually:
To spend this output, provide a script whose hash equals this value and then satisfy that script.
The redeem script itself only appears on the blockchain when the coins are actually spent.
3.2 Unlocking a P2SH output
To spend a P2SH output, the unlocking script must provide:
The data and signatures needed by the redeem script.
The redeem script itself.
When executed, the interpreter:
Collects the unlocking script data.
Reconstructs the redeem script.
Checks that the hash of the redeem script matches the hash in the P2SH locking script.
Executes the redeem script with the provided data.
This allows complex policies to be expressed, while keeping outputs short and hiding details until use.
// Example: P2SH 2-of-3 multisig
// 1. Redeem script (describes the full spending condition)
// "Any 2 of these 3 public keys must sign"
OP_2
<pubkey_A>
<pubkey_B>
<pubkey_C>
OP_3
OP_CHECKMULTISIG
// 2. Locking script in the UTXO (scriptPubKey)
// "Pay to the HASH160 of the redeem script"
OP_HASH160
<20-byte-redeemScriptHash>
OP_EQUAL
// 3. Unlocking script when spending this P2SH output (scriptSig)
// Note: The leading OP_0 fixes the historical CHECKMULTISIG bug
OP_0
<signature_from_A>
<signature_from_B>
<redeem_script>
3.3 Script hashes in Segregated Witness
Native Segregated Witness script types extend this idea. Pay to witness script hash, often called P2WSH, places a hash of the script in the witness program. The full script and witnesses are then provided separately in the witness data.
The overall pattern remains the same:
Outputs carry short hashes of scripts.
Full scripts are only revealed when spending.
This structure is very important for advanced conditions such as multisignature policies with many keys.
4. Multisignature conditions
Multisignature conditions let several keys jointly control the ability to spend coins. They are widely used for security, corporate governance and shared control scenarios.
4.1 What multisignature means
A multisignature policy specifies that at least M signatures are required from a set of N possible keys. This is often written as M of N.
Examples:
2 of 3 where any two directors out of three can release funds.
3 of 5 where any three out of five company officers must approve.
2 of 2 where two devices must sign every transaction.
No single key holder can spend the coins alone if M is greater than one.
4.2 Simple multisignature scripts
The script language has opcodes that directly support these patterns. A simplified bare multisignature script might:
Push N public keys to the stack.
Push the threshold M.
Use an opcode that checks that at least M valid signatures correspond to the N keys.
Bare multisignature scripts like this reveal all public keys and the threshold in the output. That is inefficient and exposes more information than necessary.
// Example: Bare 2-of-3 multisig output
// Locking script (scriptPubKey)
OP_2
<pubkey_A>
<pubkey_B>
<pubkey_C>
OP_3
OP_CHECKMULTISIG
// Unlocking script (scriptSig)
// Any 2 valid signatures that correspond to the 3 pubkeys above
OP_0
<signature_from_A>
<signature_from_C>
4.3 Multisignature with script hash wrappers
In practice, multisignature policies are usually written as redeem scripts and wrapped in P2SH or P2WSH.
The steps look like this:
Construct a redeem script that contains the M of N multisignature logic.
Compute the hash of this redeem script.
Use that hash inside a P2SH or P2WSH output.
The blockchain sees only the hash until the money is spent. When spending, the participants provide:
The required signatures in the correct format.
The full redeem script so nodes can check that its hash matches and then execute it.
This method:
Reduces output size, since hashes are shorter than full scripts.
Reduces information leakage about the exact policy before any spend.
4.4 Real world uses of multisignature
Multisignature policies support several important use cases.
4.4.1 Personal security with multiple devices
An individual who wants to reduce single device risk can set up a 2 of 3 scheme:
One key stored on a laptop wallet.
One key stored on a hardware device in a secure location.
One key stored on another device or backup.
To spend, the person must combine signatures from at least two of these keys. A single device compromise is not enough for an attacker to steal funds.
4.4.2 Shared control in organizations
Organizations can map their internal approval rules onto multisignature policies. For example:
Treasury funds require signatures from any two of three senior officers.
An emergency account requires signatures from three of five board members.
This reduces dependence on any single person and provides cryptographic enforcement of internal policies.
4.4.3 Custody and service models
Some custody services and financial products use multisignature to distribute responsibility:
The customer holds one key, the service holds one key and a third party trustee holds another.
Spending may require cooperation from at least two of these parties.
This creates arrangements where no single party can act alone, while still allowing recovery if one party disappears.
4.5 Multisignature and privacy considerations
Multisignature policies can also have privacy effects:
When a multisignature script is eventually revealed on chain, observers can see the number of keys and the threshold.
Using script hash forms delays this revelation until spending and keeps outputs more uniform.
Even with script hashing, a spent multisignature input can look different from a simple single signature input. Later script designs aim to hide these differences more completely, but this article focuses on the classical script model.
5. Timelocks and enforced waiting
Timelocks allow spending conditions to reference the passage of time or block height. They let scripts say “not yet” in a precise way.
There are two main categories:
Absolute timelocks that refer to a specific time or block height.
Relative timelocks that refer to a delay measured from a point in the past.
5.1 Absolute timelocks
Absolute timelocks specify that a transaction or script path can only be used once the chain has reached a certain height or time.
There are two mechanisms involved.
5.1.1 Transaction level locktime
Each transaction has a field that optionally specifies the minimum block height or time at which it becomes valid. Nodes will not accept the transaction into their mempool, and miners will not include it in a valid block, before this value is reached.
This is a coarse control. It applies to the entire transaction and does not express conditions inside script branches.
5.1.2 Script level absolute timelocks
An opcode can be used inside scripts to express conditions such as:
The current block height must be at least a specified value.
Or the current block time must be at least a specified value.
If the condition is not met, the script fails. To spend an output protected by such a condition, the transaction must also have a locktime consistent with the script requirement.
This combination ensures that coins cannot be spent before the intended time, regardless of miner preferences.
// Example: Absolute timelock with OP_CHECKLOCKTIMEVERIFY
// Policy: "Coins can only be spent after block height 800000
// and must be signed by this public key"
// Locking script (scriptPubKey)
800000 // locktime in block height
OP_CHECKLOCKTIMEVERIFY
OP_DROP
<pubkey_owner>
OP_CHECKSIG
// Unlocking script (scriptSig), valid only after height >= 800000
<signature_from_owner>
5.2 Relative timelocks
Relative timelocks express delays relative to the confirmation of a previous transaction rather than absolute times.
Instead of saying “no spending before block 800000”, a relative timelock might say “no spending until at least 100 blocks after the confirmation of the previous transaction”.
Script opcodes that support this idea allow inputs to specify conditions tied to the age of the output being spent. This is powerful for constructions where funds may move through a sequence of transactions with enforced waiting periods.
// Example: Relative timelock with OP_CHECKSEQUENCEVERIFY
// Policy: "This output can be spent only after it has been
// confirmed for at least 100 blocks, by this key"
// Locking script (scriptPubKey)
100 // relative locktime in blocks
OP_CHECKSEQUENCEVERIFY
OP_DROP
<pubkey_owner>
OP_CHECKSIG
// Unlocking script (scriptSig)
// Requires:
// - The input's nSequence to respect the 100-block delay
// - A valid signature from <pubkey_owner>
<signature_from_owner>
5.3 Uses of timelocks
Timelocks enable several practical and conceptual patterns.
5.3.1 Delayed recovery paths
A script can express a policy with two branches:
An immediate spend path that requires a strong combination of keys.
A delayed recovery path that requires a different key, but only after a long timelock.
An example would be:
A multisignature among three devices can spend at any time.
If those devices are lost, a separate backup key can recover funds, but only after a delay of one year.
This gives time to react if the backup is stolen and reinforces that the immediate path remains the primary method.
5.3.2 Two party protocols and safety valves
In protocols where two parties interact, such as payment channels, timelocks help ensure that coins are not trapped forever.
A common pattern is:
One script branch allows a cooperative close at any time with both parties signing.
Another branch allows a unilateral close by one party after a timelock expires.
This encourages cooperation while guaranteeing that either party can eventually reclaim funds if the other disappears or refuses to cooperate.
5.3.3 Trust reduced escrows
Consider a scenario with a buyer, a seller and an optional arbitrator.
A script could encode:
A spend path where buyer and seller cooperate to release funds when both are satisfied.
A path where buyer and arbitrator can refund after a certain time if goods never arrive.
A path where seller and arbitrator can release funds after a different time if the buyer refuses to cooperate.
Timelocks provide structure to these branches and prevent indefinite limbo.
6. Combining multisignature and timelocks
The real power of Bitcoin Script appears when you combine simple building blocks. Multisignature checks and timelocks can be composed to express policies that resemble legal contracts or corporate procedures.
6.1 Example: personal vault with staged access
Imagine an individual who wants a secure savings setup with the following goals:
-
Day to day spending should be difficult.
-
Long term savings should be resilient to device loss.
-
Theft of a single backup should not immediately compromise funds.
One possible script structure is:
-
Primary path
-
Requires signatures from two devices out of three.
-
No timelock.
-
Used for deliberate withdrawals.
-
-
Emergency recovery path
-
Requires one backup key plus a timelock of several months.
-
Used only if multiple primary devices fail.
-
In script form, the locking conditions might look like an OP_IF branch that checks for two of three signatures and an OP_ELSE branch that checks a timelock and a different key.
// Example: Personal vault with staged access
// Branch 1 (IF): 2-of-3 multisig, no timelock (normal spend)
// Branch 2 (ELSE): single backup key, but only after long timelock
// Locking script (scriptPubKey)
OP_IF
// Primary path: 2-of-3 multisig
OP_2
<primary_pubkey_1>
<primary_pubkey_2>
<primary_pubkey_3>
OP_3
OP_CHECKMULTISIG
OP_ELSE
// Emergency recovery path: timelocked single key
<locktime_value> // e.g. block height one year in the future
OP_CHECKLOCKTIMEVERIFY
OP_DROP
<backup_pubkey>
OP_CHECKSIG
OP_ENDIF
// --- Spending examples ---
// (1) Normal spend via 2-of-3 path
// Stack (from top to bottom):
// <...signatures...> 1
// In witness/scriptSig form (conceptually):
OP_0
<sig_from_primary_1>
<sig_from_primary_2>
OP_1 // "true" to select the OP_IF branch
// (2) Emergency recovery via timelock branch
// Stack (from top to bottom):
// <signature> 0
OP_0 // "false" to select the OP_ELSE branch
<sig_from_backup_key>
6.2 Example: corporate treasury with layers of control
A company might express a more complex governance structure:
-
Normal spending path
Two of three finance officers can sign for operational payments. -
High value path
Two of three finance officers plus one of two board members, detected by spending from a different set of outputs. -
Emergency path
A group of board members can move funds after a longer timelock if the finance department is compromised.
Careful use of script branches, separate UTXO sets and timelocks can encode these ideas directly in the blockchain, rather than relying only on internal policy documents.
6.3 Limitations and trade offs
Although script allows expressive combinations, there are practical constraints:
-
Longer scripts produce larger transactions, which increase fees.
-
Revealing complex scripts at spend time can leak information about internal policies.
-
Managing multiple keys and devices introduces operational complexity.
Designing advanced scripts therefore involves trade offs between security, privacy, cost and ease of use.
7. Why scripting is intentionally limited
At this point it is natural to ask why Bitcoin Script is so simple. If advanced conditions are useful, why not adopt a rich, general purpose language?
There are several reasons.
7.1 Predictable execution
Every full node must validate every transaction in every block. If scripts could run arbitrarily long or allocate unbounded resources, attackers could create transactions that are very expensive to validate. This would be a denial of service risk.
By limiting Script and prohibiting unbounded loops, the system ensures that each script can be evaluated quickly and safely.
7.2 Focused purpose
The primary purpose of Script is to express spending conditions. It does not need general computing abstractions. Conditions such as “require these signatures” and “enforce this waiting period” are enough for most financial use cases on the base layer.
More complex applications can be built at higher layers or on separate systems that connect to Bitcoin.
7.3 Conservatism and security
Bitcoin is intentionally conservative in changing its most fundamental rules. Adding powerful new scripting features would require rigorous analysis of security implications and compatibility issues.
Instead, the evolution has favored:
-
Introducing new script templates that are understood to be safe.
-
Refining opcodes for specific use cases, such as relative timelocks.
-
Encouraging advanced protocols to leverage existing primitives creatively.
This slow and careful approach matches the role of Bitcoin as a long term settlement layer.
8. How wallets interact with advanced scripts
From a user’s perspective, advanced scripts are usually hidden behind a wallet interface.
8.1 Template based construction
Wallets often implement a set of script templates:
-
Single signature payments.
-
Multisignature policies with configurable M of N parameters.
-
Various timelock based patterns.
The user chooses a template and fills in input fields such as “list of cosigner keys” or “delay in blocks”. The wallet then generates redeem scripts and addresses under the hood.
8.2 Device cooperation for multisignature
In realistic multisignature setups, different keys live on different devices. Wallets help coordinate the signing process:
-
One device constructs a transaction that references the relevant outputs and desired new outputs.
-
It shares an unsigned or partially signed transaction with the other devices.
-
Each device checks the transaction and adds its own signature.
-
When enough signatures have been collected, the fully signed transaction is broadcast.
Different software and hardware tools must agree on script templates and transaction formats to cooperate smoothly.
8.3 Handling timelocks safely
Wallets that use timelocks must represent them clearly to users. Misunderstanding a timelock can lead to frustrating situations where funds appear “stuck” for a period.
Good user interfaces:
-
Show the earliest block height or time when a timelocked path becomes available.
-
Warn users when they are about to send funds with long delays.
-
Explain in simple language what happens in different script branches.
Managing this complexity safely is an ongoing design challenge.
9. Looking ahead
The basic ingredients of Script have been present for many years. Advanced spending conditions built from multisignature rules and timelocks already support:
-
Secure personal and institutional storage.
-
Collaborative protocols that depend on mutual cooperation.
-
Structured recovery and emergency paths.
Future developments in the broader ecosystem continue to explore ways to:
-
Make complex policies easier to use without exposing users to mistakes.
-
Improve privacy so that script based spending looks similar on chain to simple payments.
-
Combine on chain script with off chain protocols that offer instant transactions and richer interaction patterns.
Even without diving into every new idea, understanding the classical script model provides a solid base. Once you see coins as locked by small programs, concepts such as multisignature rules and timelocks are no longer exotic features. They are natural ways to express who can spend and when spending is allowed.
10. Summary
Bitcoin Script is the mechanism that connects keys, signatures and the blockchain’s accounting of unspent outputs. It is a simple, stack based language that focuses on expressing spending conditions.
The key points from this article are:
-
Every output contains a locking script. Inputs that spend it provide unlocking scripts. Validation runs both together.
-
Standard templates hide script details behind familiar address formats.
-
Pay to script hash and native witness script hashes allow complex policies to be expressed compactly and revealed only when used.
-
Multisignature policies distribute control among several keys and are foundational for secure storage and shared governance.
-
Timelocks, both absolute and relative, allow scripts to enforce waiting periods and safety valves over time.
-
Combining multisignature and timelocks leads to rich spending policies that can mirror real world arrangements.
-
The scripting system is intentionally limited to keep validation predictable and to focus on financial conditions.
With this understanding of scripts and advanced spending conditions, you are better prepared to explore protocols that build on top of these primitives and to interpret on chain structures that go beyond simple one signature payments.
Other links
1. Blockchain and Bitcoin - Overview and Big Picture
https://shiluqi.blogspot.com/2025/11/blockchain-and-bitcoin-main-article.html
TODO
No comments:
Post a Comment