RandomX is intended to be run efficiently and easily on a general-purpose CPU. The virtual machine (VM) which runs RandomX code attempts to simulate a generic CPU using the following set of components:
The VM has access to 4 GiB of external memory in read-only mode. The DRAM memory blob is generated from the hash of the previous block using AES encryption (TBD). The contents of the DRAM blob change on average every 2 minutes. The DRAM blob is read with a maximum rate of 2.5 GiB/s per thread.
*CPUs without hardware AES support can use a GPU to generate the DRAM blob quickly. Dual channel DDR4 memory has enough bandwidth to support up to 16 mining threads.*
The memory management unit (MMU) interfaces the CPU with the DRAM blob. The purpose of the MMU is to translate the random memory accesses generated by the random program into a DRAM-friendly access pattern, where memory reads are not bound by access latency. The MMU accepts a 32-bit address `addr` and outputs a 64-bit value from DRAM. The DRAM blob is read mostly sequentially. After an average of 8192 sequential reads, a random read is performed. An average program reads a total of 4 MiB of DRAM and has 64 random reads.
The MMU uses two internal registers:
* **ma** - Address of the next quadword to be read from memory (32-bit, 8-byte aligned).
* **mx** - A 32-bit counter that determines if the next read is sequential or random. After each read, the read address is mixed with the counter: `mx ^= addr`. If the right-most 13 bits of the register are zero: `(mx & 0x1FFF) == 0`, the value of the `mx` register is copied into register `ma`.
*When the value of the `ma` register is changed to a random address, the memory location can be preloaded into CPU cache using the x86 `PREFETCH` instruction or ARM `PRFM` instruction. Implicit prefetch should ensure that sequentially accessed memory is already in the cache.*
The VM contains a 256 KiB scratchpad, which is accessed randomly both for reading and writing. The scratchpad is split into two segments (16 KiB and 240 KiB). 75% of accesses are into the first 16 KiB.
*The scratchpad access pattern mimics the usual CPU cache structure. The first 16 KiB should be covered by the L1 cache, while the remaining accesses should hit the L2 cache. In some cases, the read address can be calculated in advance, which should limit the impact of L1 cache misses.*
The actual program is stored in a 8 KiB ring buffer structure. Each program consists of 512 random 128-bit instructions. The ring buffer structure makes sure that the program forms a closed infinite loop.
*For high-performance mining, the program should be translated directly into machine code. The whole program should fit into the L1 instruction cache and hot execution paths should stay in the µOP cache that is used by newer x86 CPUs. This should limit the number of front-end stalls and keep the CPU busy most of the time.*
The control unit (CU) controls the execution of the program. It reads instructions from the program buffer and sends commands to the other units. The CU contains 3 internal registers:
* **pc** - Address of the next instruction in the program buffer to be executed (64-bit, 8 byte aligned).
* **sp** - Address of the top of the stack (64-bit, 8 byte aligned).
* **ic** - Instruction counter contains the number of instructions to execute before terminating. The register is decremented after each instruction and the program execution stops when `ic` reaches `0`.
To simulate function calls, the VM uses a stack structure. The program interacts with the stack using the CALL and RET instructions. The stack has unlimited size and each stack element is 64 bits wide.
*Although there is no explicit limit of the stack size, the maximum theoretical size of the stack is 16 MiB for a program that contains only unconditional CALL instructions (the probability of randomly generating such program is about 5×10<sup>-912</sup>). In reality, the stack size will rarely exceed 1 MiB.*
The arithmetic logic unit (ALU) performs integer operations. The ALU can perform binary integer operations from 7 groups (addition, subtraction, multiplication, division, bitwise operations, shift, rotation) with operand sizes of 64 or 32 bits.
The floating-point unit performs IEEE-754 compliant math using 64-bit double precision floating point numbers. Five basic operations are available: addition, subtraction, multiplication, division and square root.
There are 256 opcodes, which are distributed between various operations depending on their weight (how often they will occur in the program on average). The distribution of opcodes is following:
The second operand is loaded either from a register or from an immediate value encoded within the instruction. The `reg(b)` flag encodes an integer register (ALU operations) or a floating point register (FPU operations).
`imm1` is a 32-bit immediate value which is used for most operations. For operands larger than 32 bits, the value is zero-extended for unsigned instructions and sign-extended for signed instructions. For FPU instructions, the value is first left-shifted by 32 bits, treated as a signed 64-bit integer and converted to a double precision floating point format.
The `reg(c)` flag encodes an integer register (ALU operations) or a floating point register (FPU operations). For writing to the scratchpad, an integer register is always used and the write address is calculated as:
Instructions ADD_32, SUB_32, AND_32, OR_32, XOR_32 only use the low-order 32 bits of the input operands. The result of these operations is 32 bits long and bits 32-63 of C are zero.
There are 5 different multiplication operations. MUL_64 and MULH_64 both take 64-bit unsigned operands, but MUL_64 produces the low 64 bits of the result and MULH_64 produces the high 64 bits. MUL_32 and IMUL_32 use only the low-order 32 bits of the operands and produce a 64-bit result. The signed variant interprets the arguments as signed integers. IMULH_64 takes two 64-bit signed operands and produces the high-order 64 bits of the result.
The following table shows an example of the output of the 5 multiplication instructions for inputs `A = 0xBC550E96BA88A72B` and `B = 0xF5391FA9F18D6273`:
For the division instructions, the dividend is 64 bits long and the divisor 32 bits long. The IDIV_64 instruction interprets both operands as signed integers. In case of division by zero or signed overflow, the result is equal to the dividend `A`.
*Division by zero can be handled without branching by conditional move (`IF B == 0 THEN B = 1`). Signed overflow happens only for the signed variant when the minimum negative value is divided by -1. In this extremely rare case, ARM produces the "correct" result, but x86 throws a hardware exception, which must be handled.*
The shift/rotate instructions use just the bottom 6 bits of the `B` operand (`imm0` is used as the immediate value). All treat `A` as unsigned except SAR_64, which performs an arithmetic right shift by copying the sign bit.
FPU instructions conform to the IEEE-754 specification, so they must give correctly rounded results. Initial rounding mode is RN (Round to Nearest). Denormal values may not be produced by any operation.
Operands loaded from memory are treated as signed 64-bit integers and converted to double precision floating point format. Operands loaded from floating point registers are used directly.
Both instructions are conditional in 75% of cases. The jump is taken only if `B <= imm1`. For the 25% of cases when `B` is equal to `imm1`, the jump is unconditional. In case the branch is not taken, both instructions become "arithmetic no-op" `C = A`.
Taken CALL instruction pushes the values `A` and `pc` (program counter) onto the stack and then performs a forward jump relative to the value of `pc`. The forward offset is equal to `16 * (imm0[6:0] + 1)`. Maximum jump distance is therefore 128 instructions forward (this means that at least 4 correctly spaced CALL instructions are needed to form a loop in the program).
The RET instruction behaves like "not taken" when the stack is empty. Taken RET instruction pops the return address `raddr` from the stack (it's the instruction following the previous CALL), then pops a return value `retval` from the stack and sets `C = A ^ retval`. Finally, the instruction jumps back to `raddr`.
The primary cryptographically secure hash function used by RandomX is [Blake2b](https://blake2.net/) with an output size of 256 bits. Blake2b was specifically designed to be fast in software, especially on modern 64-bit processors, where it's around three times faster than SHA-3 and can run at a speed of around 3 clock cycles per byte of input.
`Blake2b(X)` refers to the 256-bit plain hash and `Blake2b(K, X)` refers to the 256-bit keyed hash.
#### HighwayHash
[HighwayHash](https://github.com/google/highwayhash) is a fast keyed pseudorandom function, which can take advantage of SIMD instructions available in modern CPUs. It's used to calculate the scratchpad digest. HighwayHash can run at a speed of about 0.3 clocks per byte using SSE 4.1.
The function is called as `HighwayHash(K, X)`, where `K` is a 256-bit key.
### Pseudo-random number generator
RandomX uses a permuted congruential generator (PCG) for VM initialization. A minimal C implementation is available [here](http://www.pcg-random.org/download.html#minimal-c-implementation). The generator has an internal state of 64 bits and additional 63 bits are used to select the output stream. The generator produces 32 random bits per call.
### DRAM blob initialization
TBD
### VM initialization
#### Scratchpad initialization
The scratchpad is initialized by copying a 256 KiB block from the DRAM blob. The starting offset of the block is `262144 * i`, where `i` is a 14-bit input parameter.
1. The PCG random number generator is initialized with state `S[63:0]` and increment `S[127:64] | 1` (odd number).
2. The generator is used to generate 8324 random bytes.
3. The integer registers `r0`-`r7` are initialized with bytes 0-63.
4. Floating point registers `f0`-`f7` are initialized with bytes 64-127 interpreted as 8 64-bit signed integers converted to a double precision floating point format.
5. The program buffer is initialized with bytes 128-8319.
6. The initial value of the `ma` register is set to bytes 8320-8323, XORed with `S[159:128]` and the last 3 bits are cleared (8-byte aligned).
7. The value of the `mx` register is initialized as `S[191:160]`.
8. The remaining registers are initialized with constant values: `pc = 0`, `sp = 0`, `ic = 1048576`.
RandomX produces a 256-bit final hash value to be used for a Hashcash-style proof evaluation.
The hash of the input (block header for a cryptocurrency) is used for the first VM initiazation. The program initialization and program execution are chained three times to discourage mining strategies that search for programs with particular properties. The scratchpad is preserved between the 3 program executions.
*An average program takes roughly 2.5 ms to execute on a recent CPU (preliminary tests). VM initialization and result calculation should take less than 0.1 ms. The total time to calculate the PoW should be under 10 ms (depends on the overhead of translating RandomX code into machine code).*
## Test code
A python generator is available to generate a random program and output its C source code.