OP_DEPTH - Counting Stack Items
13. OP_DEPTH — Counting Stack Items
Overview
OP_DEPTH pushes the current number of items on the stack onto the top of the stack as a numeric value. It is an introspective opcode — it lets the script itself examine how many items are currently on the stack, which can then be used in comparisons or loop constructs.
Opcode Reference
Opcode: OP_DEPTH
Hex: 0x74
Word: DEPTH
Input: (nothing consumed)
Output: <stack_depth>
Stack Before: [ x1, x2, ..., xN ]
Stack After: [ x1, x2, ..., xN, N ]
Execution Trace
Script: OP_1 OP_2 OP_3 OP_DEPTH
After pushes: Stack: [ 1, 2, 3 ]
After OP_DEPTH: Stack: [ 1, 2, 3, 3 ] ← depth (3) pushed to top
Counting After OP_DEPTH
Note that OP_DEPTH does not count itself — it pushes the depth before its own execution:
Empty stack:
OP_DEPTH → Stack: [ 0 ]
Stack with 5 items:
OP_DEPTH → Stack: [ x1, x2, x3, x4, x5, 5 ]
Practical Use Cases
1. Input Validation:
Scripts can use OP_DEPTH to verify that exactly the right number of items were provided:
OP_DEPTH OP_3 OP_EQUALVERIFY
This asserts that there are exactly 3 items on the stack before proceeding.
2. Variable-Argument Scripts:
Some advanced scripts — particularly those built for Simplicity or Script extensions — use OP_DEPTH to handle variable numbers of arguments:
OP_DEPTH OP_0 OP_GREATERTHAN
OP_IF
<process first item>
OP_ENDIF
3. Debugging and Testing:
During development and testing of Bitcoin scripts, OP_DEPTH is used to assert stack state at specific execution points, catching incorrect operand counts early.
Security Implications
OP_DEPTH can be used to craft scripts that behave differently based on how many arguments were provided. Script authors must ensure that OP_DEPTH-based branching does not inadvertently enable bypass conditions:
OP_DEPTH OP_2 OP_EQUAL
OP_IF
<secure path> ← executes when exactly 2 items on stack
OP_ELSE
OP_1 ← DANGER: always returns TRUE with 0 or 1 items!
OP_ENDIF
The else branch must be carefully written to avoid unconditional success.
Failure Conditions
OP_DEPTH itself never fails — even on an empty stack, it pushes 0. However, scripts that subsequently use the depth value in comparisons may behave unexpectedly if assumptions about stack depth are wrong.
Summary
OP_DEPTH is a powerful introspection tool that exposes the current stack size to the script. It enables dynamic, depth-aware script logic but must be used carefully to avoid security vulnerabilities in conditional branches.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: