The Scripting Context (CScript)
The Scripting Context (CScript)
Bitcoin Script is a stack-based language that handles numbers in a very specific way. To save space, it uses a Variable-Length Little Endian format for integers placed on the stack.
1. Minimally Encoded Integers
In most programming languages, an integer is always 4 or 8 bytes.
In Bitcoin Script, the number 1 is stored as a single byte: 0x01.
-
The number
128is stored as0x80 0x00. -
The number
256is stored as0x00 0x01.
2. Little Endian Signed Magnitude
Bitcoin Script uses Little Endian for its math, but it also uses a "Sign Bit."
-
If the highest bit of the last byte is
1, the number is negative. -
Example: The number
-1is represented as0x81. -
Example: The number
1is represented as0x01.
3. The "Arithmetic" Rule
When you use an opcode like OP_ADD:
-
The node pops two items off the stack.
-
It interprets them as Little Endian integers.
-
It performs the addition.
-
It pushes the result back to the stack as a Minimally Encoded Little Endian integer.
4. Opcodes and Data
It's important to distinguish between the OpCode and the Data.
-
OpCodes: Like
OP_DUP(0x76), are single bytes. Endianness does not exist for single bytes. -
PushData: If you want to push a public key, you use a length byte (e.g.,
0x21for 33 bytes) followed by the data. The data inside a push is typically Big Endian (if it's a key or signature).
5. Why this matters for Developers
If you are writing a script manually, you must ensure your numbers are encoded correctly.
-
If you want to check a sequence number, that number in the transaction is 4-byte Little Endian.
-
If you want to use that same number in a script for comparison, it must be converted to the script's minimal-length format.
| Value | Standard Int (4-byte LE) | Script Int (Minimal LE) |
|---|---|---|
| 1 | 01 00 00 00 |
01 |
| 127 | 7F 00 00 00 |
7F |
| 128 | 80 00 00 00 |
80 00 |
In the final section, we will build a Python Context Auditor.
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: