Research·Protocol

How Bitcoin Script Actually Works

Bitcoin Script is a stack language with no loops, no recursion and no way to call itself. That is not an unfinished feature. A validator must be able to bound the cost of a script before running it, and removing loops is what makes the bound trivial — which is why Bitcoin needs no concept of gas.

Level
Advanced
Reading
8 min
Published
2026-11-18
Reviewed
2026-11-18

Script is the part of Bitcoin that looks least like what people expect. It has no variables, no loops, no functions and no arithmetic worth the name. Every one of those absences is a decision, and the decisions are more interesting than the language.

How does a script actually run?

On a stack, left to right, with no jumps.

Each item in a script is either data, which is pushed onto the stack, or an opcode, which pops some number of items, does something, and pushes a result. Execution ends when the script ends. The spend is valid if the stack is left with a single true value on top.

A classic pay-to-public-key-hash output says: duplicate the top item, hash it, push this expected hash, verify the two are equal, then check a signature against what remains. The spender supplies the signature and the public key, which are the two items the script expects to find already there.

There is nothing else. No state carries between scripts, no script can read the blockchain, and no script can look at the transaction spending it beyond a few specific opcodes added later for timelocks.

Why is it evaluated in two halves?

Because combining them was a security hole, and the fix is instructive about how this code is maintained.

An output carries a locking script. A spend supplies an unlocking script. The original implementation concatenated the two and ran the result, which meant a spender could write an unlocking script that manipulated what followed — supplying opcodes rather than only data, and turning the lock into something it was not.

The fix was to run them separately: execute the unlocking script, carry the resulting stack over, then execute the locking script against it. The spender can therefore place values on the stack and cannot change the program that inspects them. Modern rules go further and require the unlocking half to contain only data pushes.

This is a small change with a large lesson. The vulnerability was not in the cryptography; it was in composing two pieces of code that each looked correct.

Why no loops?

Because a validator must know what a script will cost before it runs it, and every node on Earth runs every script.

With no loops and no recursion, execution time is bounded by script length. A node can refuse an oversized script up front and know the rest will terminate quickly. There is no halting problem to solve, no metering needed, and no way for a crafted script to consume unbounded resources.

This is why Bitcoin has nothing resembling gas. Systems with general-purpose execution need to price each operation and charge for it, because they cannot otherwise bound the work. Bitcoin charges for bytes, because bytes are the bound.

The cost is expressive power, and that cost is real. Arrangements that other systems express directly must be built here out of timelocks, pre-signed transactions and multi-party signing. Whether the trade is correct is a genuine design argument; that it is a trade rather than an oversight is not.

What else is deliberately missing?

A list of opcodes that existed and were turned off.

String concatenation, multiplication, division, substring extraction and several others were disabled in 2010 after bugs were found in their implementations. Rather than fix them, they were removed, because an incorrect opcode in a consensus system is not a bug in a program — it is a disagreement about what is valid.

They have never come back, and one of them is the centre of a current debate: re-enabling concatenation would make a wide class of covenant constructions possible, which is precisely why it is both wanted and resisted.

The other limits are numeric. A legacy script may contain a bounded number of non-push opcodes, individual stack elements are capped in size, and the whole script has a maximum length. These are not round numbers chosen for elegance; they are the bounds that make validation cheap.

What did pay-to-script-hash change?

It moved the script from the output to the spend, which changed who pays for complexity.

Before it, paying to a complicated arrangement meant putting the whole arrangement in the output — the payer had to know it, carry it, and pay for its size. A multisignature output listing three public keys was large, and the sender bore the cost of the recipient’s choices.

Pay-to-script-hash puts only a hash of the script in the output. The recipient reveals the actual script when spending, and pays for it then. A payer sends to a short address and needs to know nothing about what it encodes.

The pattern recurs throughout Bitcoin’s history: commit to something now, reveal it when used. SegWit and Taproot are both further refinements of the same idea, and Taproot’s script trees take it furthest by revealing only the branch actually used.

What was wrong with multisignature?

Two things, both inherited for over a decade.

The multisignature opcode pops one extra item from the stack that it does not use — an off-by-one bug in the original implementation. Because removing it would change what is valid, every multisignature spend in Bitcoin’s history has included a meaningless placeholder to satisfy it.

It also hard-caps the number of keys, and does not compose: you cannot easily build “two of these three, or one of these two after a delay” from it without awkward construction.

Tapscript replaced it with an opcode that adds to a running count, which composes naturally and has no placeholder. The old one remains valid in older script versions and will be carried forever, because nothing in Bitcoin is ever removed — only superseded.

What can a script know about its own transaction?

Very little, and the exceptions are the interesting part.

By default a script sees only the stack it was given. It cannot read the amount being spent, the outputs being created, the current block height, or anything else about the context. It is a pure predicate over the data the spender supplied.

Three opcodes break that, narrowly. Two check timelocks — one against an absolute height or time, one against the age of the output being spent — and fail the script if the spending transaction does not satisfy them. A third checks a signature, which indirectly commits to parts of the transaction through the signature hash, and which parts depends on a flag the signer chooses.

That is the whole window. Everything a script can learn about its own spend comes through those, and every proposal to widen it is what the covenant debate is about: letting a script look at where the money is going, rather than only at who authorised it.

Seen this way, the timelock opcodes are already covenants of a limited kind. They constrain when rather than where, and the argument is about whether the second is a difference in degree or in kind.

Can anyone actually write this safely?

Mostly not by hand, and that is the point of Miniscript.

Raw script is easy to get subtly wrong. A policy that looks correct can be unspendable under some conditions, or spendable under conditions the author did not intend, and neither is obvious from reading it. The failure is discovered when funds are already locked.

Miniscript is a structured subset with a compositional type system. Policies are written at a higher level, compiled into script, and — crucially — analysed: a tool can determine whether a given participant can spend, what the worst-case witness size is, and whether every branch is satisfiable. Descriptors then record the whole arrangement in a form a different wallet can reconstruct.

This matters most for the arrangements people actually want. A multisig with a timelocked recovery path is exactly the kind of thing that is easy to write and hard to verify, and it is also exactly the kind of thing whose failure is permanent.

Check it yourself

Scripts are visible in every transaction, and reading one against its address is the quickest way to make the model concrete.

# The script an address encodes, before anything is spent.
bitcoin-cli validateaddress bc1q...

# A real output's script, and the witness or scriptSig that satisfied it.
bitcoin-cli getrawtransaction <txid> true | grep -A4 'scriptPubKey\|txinwitness'

# Turn raw hex back into opcodes.
bitcoin-cli decodescript <hex>

decodescript is the useful one. Take the script from a pay-to-script-hash spend and decode it, and the arrangement the recipient chose — the quorum, the timelock, the fallback — becomes readable, having been invisible until the moment it was used.

What remains uncertain

Whether disabled opcodes return. Re-enabling concatenation is the cheapest route to general covenants and carries the least predictable consequences. The argument is live and the outcome is not forecastable.

Whether Miniscript adoption reaches ordinary wallets. The analysis it offers addresses the failure mode that actually loses money, and it is currently used mainly by people who could have managed without it.

How much the legacy limits still constrain. Tapscript removed several and replaced others with a budget. Whether the new bounds are correctly calibrated is a judgement nobody has revisited against measurement.

What a future script version should look like. Taproot made versioning cheap, which means the next change can be more ambitious than the last. Nobody has articulated what it should contain, and the debate so far is about individual opcodes rather than about the shape of the language.

Sources

Nearby