A simple stack-based VM for executing smart contract bytecode, written in Rust.
Bytecode is just a sequence of numbers (bytes) that represent instructions.
Our VM reads these numbers and executes them:
Bytecode: [0x01, 0x0A, 0x01, 0x14, 0x02, 0x00]
Means:
0x01 0x0A → PUSH 10 (Note: 0x0A = 10 in Hexadecimal)
0x01 0x14 → PUSH 20 (Note: 0x14 = 20 in Hexadecimal)
0x02 → POP
0x00 → HALT
Execution trace:
Step 1: PUSH 10 Stack: [10]
Step 2: PUSH 20 Stack: [10, 20]
Step 3: POP Stack: [10] (removed 20 from top)
Step 4: HALT Stack: [10] (program halts)
Result: 10
Our VM supports three simple stack operations:
| Opcode | Byte | Arguments | Description |
|---|---|---|---|
| HALT | 0x00 |
none | Stop or halt the execution |
| PUSH | 0x01 |
1 byte | Push a number (0-255) onto the stack |
| POP | 0x02 |
none | Remove the top number from the stack |
| ADD | 0x03 |
none | Adds the top two numbers from the stack |
| SUB | 0x04 |
none | Subtracts the top two numbers from the stack |
| MUL | 0x05 |
none | Multiplies the top two numbers from the stack |
| DIV | 0x06 |
none | Divides the top two numbers from the stack |
| MSTORE | 0x20 |
none | Pop offset and value from stack. Write value to memory at offset. |
| MLOAD | 0x21 |
none | Pop offset from stack. Read value from memory at offset and push to stack. |