setupBackendRng static method

void setupBackendRng({
  1. bool seal = false,
})

Routes generateRandom through the active backend RNG (blockchainUtils.api.rng, seeded below when necessary).

Falls back to the Fortuna _prng whenever the active backend has no global RNG (pure-Dart backend), so callers keep working across setRustApi/setDartApi switches. Prefer BlockchainUtils.setRustApi (which calls this) and BlockchainUtils.setDartApi (which restores setupRandom null) over calling this directly.

Implementation

static void setupBackendRng({bool seal = false}) {
  _checkNotSealed('setupBackendRng');
  final backend = blockchainUtils.api.rng;
  if (backend is NativeRngApi && !backend.isSeeded) {
    // `dart test` runs files in concurrent isolates sharing one process
    // (and one native library): two files can both observe an unseeded
    // RNG and race to seed it. Losing is fine as long as *someone* won —
    // re-check the seeded state before treating a failed seed as fatal.
    try {
      backend.seed(seed32: generateRandom(length: 32));
    } on BuError {
      if (!backend.isSeeded) rethrow;
    }
  }
  _generateRandom = (length) {
    if (length == 0) return <int>[].asBytes;
    final active = blockchainUtils.api.rng;
    if (active is NativeRngApi) return active.fill(length: length).asBytes;
    return _prng.nextBytes(length);
  };
  if (seal) QuickCrypto.seal();
}