diff --git a/ports/webassembly/library.h b/ports/webassembly/library.h index 47982e0640..21027c1372 100644 --- a/ports/webassembly/library.h +++ b/ports/webassembly/library.h @@ -29,3 +29,4 @@ extern void mp_js_write(const char *str, mp_uint_t len); extern int mp_js_ticks_ms(void); extern void mp_js_hook(void); +extern uint32_t mp_js_random_u32(void); diff --git a/ports/webassembly/library.js b/ports/webassembly/library.js index f554f681c9..4a17942bb4 100644 --- a/ports/webassembly/library.js +++ b/ports/webassembly/library.js @@ -63,4 +63,11 @@ mergeInto(LibraryManager.library, { } } }, + + // Node prior to v19 did not expose "crypto" as a global, so make sure it exists. + mp_js_random_u32__postset: + "if (globalThis.crypto === undefined) { globalThis.crypto = require('crypto'); }", + + mp_js_random_u32: () => + globalThis.crypto.getRandomValues(new Uint32Array(1))[0], }); diff --git a/ports/webassembly/mpconfigport.h b/ports/webassembly/mpconfigport.h index e0d1af0cce..43a029c530 100644 --- a/ports/webassembly/mpconfigport.h +++ b/ports/webassembly/mpconfigport.h @@ -49,6 +49,8 @@ #define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_DOUBLE) #define MICROPY_USE_INTERNAL_ERRNO (1) #define MICROPY_USE_INTERNAL_PRINTF (0) + +#define MICROPY_PY_RANDOM_SEED_INIT_FUNC (mp_js_random_u32()) #ifndef MICROPY_VFS #define MICROPY_VFS (1) #endif @@ -95,3 +97,5 @@ typedef long mp_off_t; // _GNU_SOURCE must be defined to get definitions of DT_xxx symbols from dirent.h. #define _GNU_SOURCE #endif + +uint32_t mp_js_random_u32(void);