Re: [kvm-unit-tests PATCH v3 1/7] lib: Add pseudo random functions

Nicholas Piggin
2024-06-25T03:08:37Z

On Fri Jun 21, 2024 at 12:16 AM AEST, Nina Schoetterl-Glausch wrote:
> Add functions for generating pseudo random 32 and 64 bit values.
> The implementation uses SHA-256 and so the randomness should have good
> quality.
> Implement the necessary subset of SHA-256.
> The PRNG algorithm is equivalent to the following python snippet:
>
> def prng32(seed):
> from hashlib import sha256
> state = seed.to_bytes(8, byteorder="big")
> while True:
> state = sha256(state).digest()
> for i in range(8):
> yield int.from_bytes(state[i*4:(i+1)*4], byteorder="big")
>

Nice, could use this for powerpc radom SPR value tests (and
probably other things too).

> Acked-by: Andrew Jones <andrew.jones@linux.dev>
> Signed-off-by: Nina Schoetterl-Glausch <nsg@linux.ibm.com>
> ---
>
> Notes:
> Since a PRNG with better quality was asked for I decided to use SHA-256
> because:
> * it is a standard, commonly used algorithm
> * high quality randomness is assured
> * the implementation can be checked against the spec
> * the implementation can be easily checked via comparison
>
> I tested the implementation in the following way:
>
> cat <<'EOF' > rand.py
> #!/usr/bin/python3
>
> def prng32(seed):
> from hashlib import sha256
> state = seed.to_bytes(8, byteorder="big")
> while True:
> state = sha256(state).digest()
> for i in range(8):
> yield int.from_bytes(state[i*4:(i+1)*4], byteorder="big")
>
> r = prng32(0)
> for i in range(100):
> print(f"{next(r):08x}")
>
> EOF
>
> cat <<'EOF' > rand.c
> #include <stdio.h>
> #include "rand.h"
>
> void main(void)
> {
> prng_state state = prng_init(0);
> for (int i = 0; i < 100; i++) {
> printf("%08x\n", prng32(&state));
> }
> }
> EOF
> cat <<'EOF' > libcflat.h
> #define ARRAY_SIZE(_a) (sizeof(_a)/sizeof((_a)[0]))
> EOF
> chmod +x rand.py
> ln -s lib/rand.c librand.c
> gcc -Ilib librand.c rand.c
> diff <(./a.out) <(./rand.py)

Cool... you made a unit test for the unit tests. We could start a
make check? :)

Acked-by: Nicholas Piggin <npiggin@gmail.com>

Thanks,
Nick