|
1 | | -# Work In Progress |
| 1 | +# OP_WITHIN |
2 | 2 |
|
3 | | -:::warning |
4 | | -This page has not yet been written. If you have experience with bitcoin Script and would like to contribute, please do! You can open a PR [on the repository for this website](https://github.com/thunderbiscuit/opcode-explained). |
| 3 | +:::info |
| 4 | +**Opcode number:** 165 |
| 5 | +**Byte representation:** `0xa5` |
| 6 | +**Short description:** Pop the top three items; if the first item is within the range specified by the second and third stack items, push 1, otherwise, push an empty array. |
5 | 7 | ::: |
| 8 | + |
| 9 | +`OP_WITHIN` checks if the top item on the stack is within a specified range. Specifically, it evaluates whether the first item is greater than or equal to the second item and less than the third item (min <= x < max). If true, it pushes 1 (true) onto the stack; otherwise, it pushes an empty array (false). |
| 10 | + |
| 11 | +### Operation |
| 12 | + |
| 13 | +1. Pop the top three items from the stack: |
| 14 | + - x (fist item): The value to check. |
| 15 | + - min (second item): The lower bound of the range. |
| 16 | + - max (third item): The upper bound of the range. |
| 17 | +2. Evaluate whether min <= x < max: |
| 18 | + - If true, push 1 (true) onto the stack. |
| 19 | + - If false, push an empty array (false) onto the stack. |
| 20 | + |
| 21 | +### Notes |
| 22 | + |
| 23 | +- The range is _inclusive_ of the lower bound (min <= x) and _exclusive_ of the upper bound (x < max). |
| 24 | +- Both items must be valid integers. Bitcoin Script interprets byte arrays up to **4 bytes** as integers. |
| 25 | +- An empty array (`[]`) is treated as 0 when compared. |
| 26 | +- If there are fewer than two items on the stack when `OP_GREATERTHAN` is executed, the script will fail. |
| 27 | + |
| 28 | +## Examples |
| 29 | + |
| 30 | +### Example 1: Value is within the range |
| 31 | + |
| 32 | +```shell |
| 33 | +# ASM script |
| 34 | +OP_2 OP_1 OP_3 OP_WITHIN |
| 35 | + |
| 36 | +# Raw script |
| 37 | +525153a5 |
| 38 | + |
| 39 | +# Stack (before OP_WITHIN) |
| 40 | +3 # max |
| 41 | +1 # min |
| 42 | +2 # x |
| 43 | + |
| 44 | +# Stack (after OP_WITHIN) |
| 45 | +1 # true, as 1 <= 2 < 3 |
| 46 | +``` |
| 47 | + |
| 48 | +### Example 3: Value is at the lower bound |
| 49 | + |
| 50 | +```shell |
| 51 | +# ASM script |
| 52 | +OP_1 OP_1 OP_3 OP_WITHIN |
| 53 | + |
| 54 | +# Raw script |
| 55 | +515153a5 |
| 56 | + |
| 57 | +# Stack (before OP_WITHIN) |
| 58 | +3 # top (max) |
| 59 | +1 # min |
| 60 | +1 # x |
| 61 | + |
| 62 | +# Stack (after OP_WITHIN) |
| 63 | +1 # true, as 1 <= 1 < 3 |
| 64 | +``` |
0 commit comments