🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Bitcoin Scripting

Bitcoin Deep DiveđŸŸĸ Free Lesson

Bitcoin Scripting

Script opcodes, P2PKH, P2SH, P2WPKH, Timelock (CLTV, CSV), multisig scripts, and covenant proposals.

Overview

Bitcoin Script is the programmable language that enables Bitcoin's core functionality. Understanding it is essential for building on Bitcoin.

Script Opcodes

Bitcoin Script Opcode CategoriesConstantsOP_0 - OP_16OP_DATA_1-75OP_1NEGATEOP_RESERVEDOP_PUSHDATA1/2/4Flow ControlOP_IF / OP_NOTIFOP_ELSEOP_ENDIFOP_VERIFYOP_RETURNCryptoOP_SHA256OP_HASH160OP_HASH256OP_CHECKSIGOP_CHECKMULTISIGArithmeticOP_ADD / OP_SUBOP_MUL / OP_DIVOP_MOD / OP_ABSOP_MIN / OP_MAXOP_GREATERTHANTimelockOP_CHECKLOCKTIMEVERIFYOP_CHECKSEQUENCEVERIFYOP_NOP1-OP_NOP10Stack OperationsOP_DUP / OP_DROPOP_SWAP / OP_OVEROP_ROT / OP_PICKLocktimeOP_CHECKLOCKTIMEVERIFYOP_CHECKSEQUENCEVERIFYRelative/Absolute locksTotal: ~200+ opcodes | Disabled: OP_CAT, OP_MUL, OP_DIV (disabled for security)

P2PKH (Pay-to-Public-Key-Hash)

The original Bitcoin transaction type.

P2PKH Script Flow

python
# Locking Script (scriptPubKey)
locking_script = [
    "OP_DUP",
    "OP_HASH160",
    "pubkey_hash_20_bytes",
    "OP_EQUALVERIFY",
    "OP_CHECKSIG"
]

# Unlocking Script (scriptSig)
unlocking_script = [
    "signature_71_bytes",
    "public_key_33_bytes"
]

# Combined execution:
# Stack: [sig, pubkey]
# OP_DUP → [sig, pubkey, pubkey]
# OP_HASH160 → [sig, pubkey, pubkey_hash]
# <pubkey_hash> → [sig, pubkey, pubkey_hash, expected_hash]
# OP_EQUALVERIFY → [sig, pubkey] (verifies hashes match)
# OP_CHECKSIG → [TRUE] (verifies signature)

P2PKH Address Generation

Architecture Diagram
Address = Base58Check(version + Hash160(pubkey) + checksum)
Version: 0x00 (mainnet), 0x6F (testnet)

P2SH (Pay-to-Script-Hash)

Enables complex scripts by hiding the script behind a hash.

P2SH Multisig Example

python
# Redemption Script (redeemScript)
redeem_script = [
    "OP_2",           # 2-of-3 multisig
    "pubkey_A",
    "pubkey_B",
    "pubkey_C",
    "OP_3",
    "OP_CHECKMULTISIG"
]

# Locking Script
locking_script = [
    "OP_HASH160",
    hash160(redeem_script),  # 20-byte hash
    "OP_EQUAL"
]

# ScriptSig
script_sig = [
    "OP_0",           # dummy (CHECKMULTISIG bug)
    "sig_A",
    "sig_C"           # 2 signatures required
]

P2SH Benefits

FeatureP2PKHP2SH
Script ComplexitySimple onlyAny script
Sender ResponsibilityKnows full scriptOnly knows hash
Fee PaymentSenderSender
FlexibilityLowHigh

P2WPKH (Pay-to-Witness-Public-Key-Hash)

Native SegWit transaction type.

P2WPKH Structure

python
# Witness Program
witness_program = [
    "OP_0",                    # SegWit version 0
    hash160(pubkey)            # 20-byte public key hash
]

# Witness Data (in witness field, not scriptSig)
witness = [
    "signature",
    "public_key"
]

# Output Script (scriptPubKey)
output_script = [
    "OP_0",
    "20_bytes_hash"            # Push 20 bytes directly
]

P2WPKH vs P2PKH

AspectP2PKHP2WPKH
Address Format1...bc1q...
Signature LocationscriptSigWitness
MalleabilityVulnerableFixed
Fee (typical)~226 bytes~141 vB

P2WSH (Pay-to-Witness-Script-Hash)

SegWit version for complex scripts.

P2WSH Example

python
# Witness Script
witness_script = [
    "OP_2",
    "pubkey_A",
    "pubkey_B",
    "pubkey_C",
    "OP_3",
    "OP_CHECKMULTISIG"
]

# Output Script
output_script = [
    "OP_0",
    sha256(witness_script)     # 32-byte hash
]

# Witness
witness = [
    "OP_0",
    "sig_A",
    "sig_C",
    witness_script             # Full script revealed
]

Timelock Mechanisms

CLTV (CheckLockTimeVerify) - BIP-65

Absolute timelock: transaction cannot be mined before specific time/block.

python
# CLTV Script
cltv_script = [
    "OP_CHECKLOCKTIMEVERIFY",
    "OP_DROP",
    "OP_DUP",
    "OP_HASH160",
    "pubkey_hash",
    "OP_EQUALVERIFY",
    "OP_CHECKSIG"
]

# Transaction nLockTime field
nLockTime = 1700000000  # Unix timestamp
# OR
nLockTime = 800000     # Block height

CSV (CheckSequenceVerify) - BIP-112

Relative timelock: transaction cannot be mined until N blocks after UTXO confirmation.

python
# CSV Script
csv_script = [
    "OP_CHECKSEQUENCEVERIFY",
    "OP_DROP",
    "OP_DUP",
    "OP_HASH160",
    "pubkey_hash",
    "OP_EQUALVERIFY",
    "OP_CHECKSIG"
]

# nSequence field
nSequence = 0x00000001  # 1 block relative lock
# Bits 22-31: 0 = blocks, 1 = time
# Bits 0-15: lock value

Timelock Comparison

FeatureCLTVCSV
Lock TypeAbsoluteRelative
FieldnLockTimenSequence
GranularityBlock height or timestampBlocks or time units
Use CaseHTLCs, time-locked vaultsLightning, RBF
BIPBIP-65BIP-112

HTLC (Hash Time-Locked Contract)

python
# HTLC Script
htlc_script = [
    "OP_IF",
    "OP_SHA256",
    "hash_of_secret",
    "OP_EQUALVERIFY",
    <recipient_pubkey>,
    "OP_CHECKSIG",
    "OP_ELSE",
    <timelock_height>,
    "OP_CHECKLOCKTIMEVERIFY",
    "OP_DROP",
    <sender_pubkey>,
    "OP_CHECKSIG",
    "OP_ENDIF"
]

Multisig Scripts

Bare Multisig (Deprecated)

python
# 2-of-3 Multisig (bare, deprecated)
bare_multisig = [
    "OP_2",
    "pubkey_A",
    "pubkey_B",
    "pubkey_C",
    "OP_3",
    "OP_CHECKMULTISIG"
]
# Problem: Non-standard, most nodes won't relay

P2SH Multisig (Standard)

python
# 2-of-3 Multisig (P2SH)
# Redeem Script
redeem_script = [
    "OP_2",
    "pubkey_A",
    "pubkey_B",
    "pubkey_C",
    "OP_3",
    "OP_CHECKMULTISIG"
]

# Output: OP_HASH160 <hash(redeem_script)> OP_EQUAL
# Input: OP_0 <sig_A> <sig_C> <redeem_script>

P2WSH Multisig (Best Practice)

python
# 2-of-3 Multisig (P2WSH)
# Witness Script
witness_script = [
    "OP_2",
    "pubkey_A",
    "pubkey_B",
    "pubkey_C",
    "OP_3",
    "OP_CHECKMULTISIG"
]

# Output: OP_0 <sha256(witness_script)>
# Witness: OP_0 <sig_A> <sig_C> <witness_script>

Multisig Security

ConfigurationSecurityFlexibilityComplexity
1-of-2LowHighLow
2-of-3BalancedMediumMedium
3-of-5HighLowHigh
5-of-7Very HighVery LowVery High

Covenant Proposals

Covenants allow scripts to constrain how future transactions spend coins.

OP_CHECKTEMPLATEVERIFY (CTV) - BIP-119

python
# CTV allows committing to future spending conditions
ctv_script = [
    "OP_CHECKTEMPLATEVERIFY",
    "OP_DROP"
]

# Template hash includes:
# - Version
# - Locktime
# - Input count
# - Output count
# - Outputs hash
# - Input index

OP_VAULT (Vault Construction)

python
# Vault commit stage
vault_commit = [
    "OP_SHA256",
    "hash_of_vault_script",
    "OP_EQUAL"
]

# Vault recovery script
vault_recovery = [
    "OP_IF",
    # Normal path: requires timelock
    "OP_CHECKLOCKTIMEVERIFY",
    "OP_DROP",
    <recovery_pubkey>,
    "OP_CHECKSIG",
    "OP_ELSE",
    # Theft path: requires timelock + revault
    <timelock>,
    "OP_CHECKLOCKTIMEVERIFY",
    "OP_DROP",
    <cold_storage_pubkey>,
    "OP_CHECKSIG",
    "OP_ENDIF"
]

Covenant Comparison

ProposalFunctionalityComplexityStatus
CTV (BIP-119)Template commitmentLowDraft
APO (BIP-118)Input-indexed signingMediumDraft
VAULTPre-confirmed outputsHighResearch
ELEMENTSPegged sidechainsHighProduction

Real-World Script Usage

Lightning Network Scripts

python
# HTLC Script (Lightning)
htlc = [
    "OP_DUP",
    "OP_HASH160",
    <revocation_pubkey_hash>,
    "OP_EQUAL",
    "OP_IF",
    "OP_CHECKSIG",
    "OP_ELSE",
    <remote_htlc_pubkey>,
    "OP_SWAP",
    "OP_SIZE",
    32,
    "OP_EQUAL",
    "OP_NOTIF",
    # Payment hash missing
    "OP_DROP",
    2,
    "OP_SWAP",
    <remote_htlc_pubkey>,
    2,
    "OP_CHECKMULTISIG",
    "OP_ELSE",
    "OP_HASH160",
    <payment_hash>,
    "OP_EQUALVERIFY",
    "OP_CHECKSIG",
    "OP_ENDIF",
    "OP_ENDIF"
]

Pay-to-Anchor (P2A) - BIP-118

python
# P2A: Pay to Anchor
# Simple output that can only be spent via witness
p2a_output = [
    "OP_1",
    <32_byte_tweak>
]

Trade-offs

Script Complexity vs Security

ComplexitySecurityUse CaseCost
Simple P2PKHHighBasic paymentsLow
P2SH MultisigMedium-HighBusiness walletsMedium
P2WSH ComplexMediumDeFi protocolsHigh
Custom ScriptVariableSpecializedVariable

Timelock Trade-offs

Lock TypeFlexibilitySecurityPrivacy
CLTV (Absolute)LowHighMedium
CSV (Relative)MediumHighMedium
Both CombinedHighMediumLow

Interview Questions

  1. How does P2SH enable flexible scripts without burdening senders?

    • Answer: Senders only need to know the hash of the script, not the script itself. The full script is revealed only when spending, keeping transactions compact while enabling complex spending conditions.
  2. What prevents OP_CHECKMULTISIG from accepting fewer signatures than required?

    • Answer: A bug in Bitcoin's original implementation requires an extra OP_0 on the stack. OP_CHECKMULTISIG pops the m value, then m signatures, then n public keys, then n, then OP_0.
  3. How does CSV (relative timelock) differ from CLTV in Lightning Network channel closures?

    • Answer: CSV is used for HTLC outputs to allow time-based resolution without knowing the absolute block height when the channel was opened, enabling relative time-based security.

Quiz Questions

  1. What opcode creates a signature verification in P2PKH?

    • A) OP_HASH160
    • B) OP_CHECKSIG ✓
    • C) OP_EQUALVERIFY
    • D) OP_DUP
  2. In P2SH multisig, what must be included in the scriptSig?

    • A) The full script only
    • B) Signatures and the redeem script ✓
    • C) Just the script hash
    • D) Public keys only
  3. Which BIP introduced OP_CHECKLOCKTIMEVERIFY?

    • A) BIP-112
    • B) BIP-141
    • C) BIP-65 ✓
    • D) BIP-119

Practice

  1. Write a P2SH 2-of-3 multisig locking and unlocking scripts
  2. Implement a simple HTLC script with both CLTV and hash locks
  3. Create a timelocked vault script using CLTV
  4. Analyze a real Bitcoin transaction script on blockstream.info
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement