Skip to content

util_random ​

Summary. Write cryptographically derived random bytes to the Hook's own linear WASM memory. This API is provided by the featureRNG amendment.

Signature.

c
int64_t util_random(uint32_t write_ptr, uint32_t write_len);

Parameters.

NameTypeDescription
write_ptruint32_tDestination offset in the Hook's linear WASM memory.
write_lenuint32_tNumber of bytes to write; must be from 1 through 512.

Return value. Returns write_len on success. The requested bytes are written beginning at write_ptr. Errors:

CodeValueCause
OUT_OF_BOUNDS-1The destination region is outside WASM memory.
TOO_SMALL-4write_len == 0.
TOO_BIG-3write_len > 512.
TOO_LITTLE_ENTROPY-46The current ledger has no usable random seed, is not sufficiently seeded, or has no qualifying entropy contribution.
TOO_MANY_NONCES-12More than 256 RNG draws in one Hook execution.

Common failure patterns.

  • Requesting 0 bytes → TOO_SMALL; requesting more than 512 → TOO_BIG.
  • A destination buffer that runs past the end of WASM memory → OUT_OF_BOUNDS.
  • Drawing in a ledger that has no usable entropy → TOO_LITTLE_ENTROPY.
  • Drawing more than 256 times in one execution → TOO_MANY_NONCES.

Caveats / notes.

  • Requires the featureRNG amendment; without it the function is not available.
  • Each successful call consumes one RNG draw, regardless of write_len, from the 256 draws shared with dice.
  • The draw limit reuses the existing TOO_MANY_NONCES return code.

Minimal example.

c
uint8_t bytes[32];
int64_t written = util_random((uint32_t)bytes, sizeof(bytes));
if (written < 0)
    rollback(SBUF("random bytes unavailable"), 1);

Related APIs. dice returns a uniformly distributed integer.