Problem using getrandom

I need to generate random numbers. For that, I define in my Cargo.toml file the following:

name = "dice"
version = "0.1.0"
description = "Created with Anchor"
edition = "2018"

crate-type = ["cdylib", "lib"]
name = "dice"
doctest = false

no-entrypoint = []
no-idl = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []

rand = "0.8.5"

When I run anchor build in console, I get the following error:

BPF SDK: /home/krl/.local/share/solana/install/releases/1.9.13/solana-release/bin/sdk/bpf
cargo-build-bpf child: rustup toolchain list -v
cargo-build-bpf child: cargo +bpf build --target bpfel-unknown-unknown --release
   Compiling getrandom v0.2.6
error: target is not supported, for more information see:
   --> ~.cargo/registry/src/
240 | /         compile_error!("target is not supported, for more information see: \
241 | |               ");
    | |_________________________________________________________________________^

error[E0433]: failed to resolve: use of undeclared crate or module `imp`
   --> ~/.cargo/registry/src/
262 |     imp::getrandom_inner(dest)
    |     ^^^ use of undeclared crate or module `imp`

For more information about this error, try `rustc --explain E0433`.

After a search, I found the same problem in, whose solution is to add in Cargo.toml:

getrandom = { version = "0.2", features = ["js"] }

However, it doesn't work for me.

That solution is only for the wasm32-unknown-unknown target, as it's a bit special. In your case, that target is simple not supported. You may be able to use the register_custom_getrandom! macro.

I'd normally suggest making an issue or PR to support your target, but I don't see bpfel-unknown-unknown in the target list, so I'm not sure if getrandom could support it.

Is there another way in rust to generate random numbers without going through the rand library?

Certainly. The solution depends on what quality of randomness you are looking for.

Implementing a basic random number generator is fairly simple (cryptographic, not so much). The larger issue is seeding it randomly. Seeding from the system clock is not directly possible on wasm-unknown-unknown because that platform doesn't support one. In the past I've created a simple binding to pull in the time via javascript in order to seed the generator.

Edit: Sorry, I didn't catch that this was for bpf. I just saw the mention of wasm and assumed a web scenario.

It's hard to use traditional RNGs in eBPF environment. RNGs are stateful but only state eBPF functions can have between calls are those maps. That's why the bpf-helpers provides bpf_get_prandom_u32 function. You should use it instead.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.