dicerng

Generate random bytes on-chain

Generate random bytes on-chain using Mercury EVM's RNG precompile.

Overview

rng() and async_rng() call the RNG precompile at address 0x64 to generate cryptographically secure random bytes directly on the Seismic node. The random value is returned as a Python integer.

Signature

def rng(
    w3: Web3,
    *,
    num_bytes: int,
    pers: bytes = b"",
) -> int

async def async_rng(
    w3: AsyncWeb3,
    *,
    num_bytes: int,
    pers: bytes = b"",
) -> int

Parameters

Parameter
Type
Required
Description

w3

Web3 or AsyncWeb3

Yes

Web3 instance connected to a Seismic node

num_bytes

int

Yes

Number of random bytes to generate (1-32)

pers

bytes

No

Optional personalization bytes to seed the RNG

Returns

Type
Description

int

Random value as a Python integer (derived from num_bytes random bytes)

Examples

Basic Usage

With Personalization

Async Usage

Generate Multiple Random Values

Convert to Bytes

How It Works

  1. Encode parameters - num_bytes is encoded as a 4-byte big-endian integer, followed by optional pers bytes

  2. Call precompile - Issues an eth_call to address 0x64 with estimated gas

  3. Decode result - Result bytes are padded to 32 bytes and interpreted as a big-endian unsigned integer

Gas Cost

The gas cost is calculated as:

The base cost is 3500 gas, with 5 gas per 136-byte block for personalization and output.

Notes

  • num_bytes must be between 1 and 32 (inclusive)

  • The RNG uses Strobe128 internally for cryptographic security

  • Each call generates independent random values

  • Personalization string can be used to domain-separate random values

  • The returned integer represents the random bytes as a big-endian unsigned value

Warnings

  • Range validation - num_bytes outside 1-32 will raise ValueError

  • Node connectivity - Requires a working connection to a Seismic node

  • Not for consensus - Results may differ across nodes due to timing

See Also

  • ecdh - On-chain ECDH key exchange

  • hkdf - On-chain HKDF key derivation

  • Bytes32 - 32-byte value type

Last updated