Skip to content

Random Number Generation

More...

Functions

Name
int wc_InitNetRandom(const char * configFile, wnr_hmac_key hmac_cb, int timeout)
Init global Whitewood netRandom context.
int wc_FreeNetRandom(void )
Free global Whitewood netRandom context.
int wc_InitRng(WC_RNG * rng)
Gets the seed (from OS) and key cipher for rng. rng_>drbg (deterministic random bit generator) allocated (should be deallocated with wc_FreeRng). This is a blocking operation.
int wc_RNG_GenerateBlock(WC_RNG * rng, byte * output, word32 sz)
Copies a sz bytes of pseudorandom data to output. Will reseed rng if needed (blocking).
int wc_RNG_GenerateByte(WC_RNG * rng, byte * b)
Calls wc_RNG_GenerateBlock to copy a byte of pseudorandom data to b. Will reseed rng if needed.
int wc_FreeRng(WC_RNG * rng)
Should be called when RNG no longer needed in order to securely free drgb. Zeros and XFREEs rng-drbg.
int wc_RNG_HealthTest(int reseed, const byte * seedA, word32 seedASz, const byte * seedB, word32 seedBSz, byte * output, word32 outputSz)
Creates and tests functionality of drbg.
int wc_GenerateSeed(OS_Seed * os, byte * output, word32 sz)
Generates seed from OS entropy source. Lower-level function used internally by wc_InitRng.
WC_RNG * wc_rng_new(byte * nonce, word32 nonceSz, void * heap)
Allocates and initializes new WC_RNG with optional nonce.
int wc_rng_new_ex(WC_RNG ** rng, byte * nonce, word32 nonceSz, void * heap, int devId)
Allocates and initializes WC_RNG with extended parameters.
void wc_rng_free(WC_RNG * rng)
Frees WC_RNG allocated with wc_rng_new.
int wc_InitRng_ex(WC_RNG * rng, void * heap, int devId)
Initializes WC_RNG with extended parameters.
int wc_InitRngNonce(WC_RNG * rng, const byte * nonce, word32 nonceSz)
Initializes WC_RNG with nonce.
int wc_InitRngNonce_ex(WC_RNG * rng, const byte * nonce, word32 nonceSz, void * heap, int devId)
Initializes WC_RNG with nonce and extended parameters.
int wc_SetSeed_Cb(wc_RngSeed_Cb cb)
Sets callback for custom seed generation.
int wc_RNG_DRBG_Reseed(WC_RNG * rng, const byte * seed, word32 seedSz)
Reseeds DRBG with new entropy.
int wc_RNG_TestSeed(const byte * seed, word32 seedSz)
Tests seed validity for DRBG.
int wc_RNG_HealthTest_ex(int reseed, const byte * nonce, word32 nonceSz, const byte * seedA, word32 seedASz, const byte * seedB, word32 seedBSz, byte * output, word32 outputSz, void * heap, int devId)
RNG health test with extended parameters.
int wc_RNG_HealthTest_SHA512(int reseed, const byte * seedA, word32 seedASz, const byte * seedB, word32 seedBSz, byte * output, word32 outputSz)
Runs the SHA_512 Hash_DRBG Known Answer Test (KAT) per SP 800-90A. Instantiates a SHA-512 DRBG with seedA, optionally reseeds with seedB, generates output, and compares against known test vectors. Available when WOLFSSL_DRBG_SHA512 is defined.
int wc_RNG_HealthTest_SHA512_ex(int reseed, const byte * nonce, word32 nonceSz, const byte * persoString, word32 persoStringSz, const byte * seedA, word32 seedASz, const byte * seedB, word32 seedBSz, const byte * additionalA, word32 additionalASz, const byte * additionalB, word32 additionalBSz, byte * output, word32 outputSz, void * heap, int devId)
Extended SHA-512 Hash_DRBG health test with nonce, personalization string, and additional input support. Suitable for full ACVP / CAVP test vector validation. Available when WOLFSSL_DRBG_SHA512 is defined.
int wc_Sha256Drbg_Disable(void )
Disables the SHA_256 Hash_DRBG at runtime. When disabled, newly initialized WC_RNG instances will not use the SHA_256 DRBG. If the SHA_512 DRBG is enabled (WOLFSSL_DRBG_SHA512), new RNG instances will use SHA-512 instead. Requires HAVE_HASHDRBG.
int wc_Sha256Drbg_Enable(void )
Re_enables the SHA_256 Hash_DRBG at runtime after a prior call to wc_Sha256Drbg_Disable(). Requires HAVE_HASHDRBG.
int wc_Sha256Drbg_IsDisabled(void )
Returns whether the SHA-256 Hash_DRBG is currently disabled. Requires HAVE_HASHDRBG.
int wc_Sha512Drbg_Disable(void )
Disables the SHA-512 Hash_DRBG at runtime. When disabled, newly initialized WC_RNG instances will not use the SHA-512 DRBG. If the SHA-256 DRBG is still enabled, new RNG instances will fall back to SHA-256. Available when WOLFSSL_DRBG_SHA512 is defined. Requires HAVE_HASHDRBG.
int wc_Sha512Drbg_Enable(void )
Re_enables the SHA_512 Hash_DRBG at runtime after a prior call to wc_Sha512Drbg_Disable(). Available when WOLFSSL_DRBG_SHA512 is defined. Requires HAVE_HASHDRBG.
int wc_Sha512Drbg_IsDisabled(void )
Returns whether the SHA-512 Hash_DRBG is currently disabled. Available when WOLFSSL_DRBG_SHA512 is defined. Requires HAVE_HASHDRBG.
int wc_InitRng_ex2(WC_RNG * rng, void * heap, int devId, word32 flags)
Initialize a WC_RNG with instantiation_time security attributes. Identical to wc_InitRng_ex(), with a flags argument fixing attributes at birth: WC_RNG_INIT_FLAG_LOCK_REQUIRED latches the sticky lock_required policy bit, so there is no reachable state in which the instance serves without its lock policy; WC_RNG_INIT_FLAG_LOCK_INITIALLY constructs into a held lease, to be released with wc_RNG_lock_put(); WC_RNG_INIT_FLAG_USE_FULL_MUTEX layers a blocking wolfSSL_Mutex outermost around the lock latch, for user_mode sharing of one instance among threads (requires WC_RNG_HAVE_LOCK_FULL_MUTEX).
int wc_InitRngNonce_ex2(WC_RNG * rng, const byte * nonce, word32 nonceSz, const byte * perso, word32 persoSz, void * heap, int devId, word32 flags)
Initialize a WC_RNG with a caller_supplied nonce and instantiation_time security attributes. The nonce semantics are those of wc_InitRngNonce_ex(); the flags semantics are those of wc_InitRng_ex2().
int wc_RNG_GetStatus(const WC_RNG * rng)
Read_only accessor for the RNG health status. Returns the instance's enum wc_RngHealthState value (WC_DRBG_NOT_INIT, WC_DRBG_OK, WC_DRBG_FAILED, WC_DRBG_CONT_FAILED).
int wc_RNG_DRBG_Present(const WC_RNG * rng)
Returns 1 if rng has an instantiated DRBG, else 0. An in_service WC_RNG can lack one: instantiation bypasses the DRBG when the CPU has RDRAND (HAVE_INTEL_RDRAND). DRBG_specific services (commanded reseed, banked next seeds, RBG chains) are unavailable on such instances.
int wc_RNG_DRBG_GetReseedCtr(const WC_RNG * rng, wc_drbg_reseed_ctr_t * reseedCtr)
Report the DRBG's current reseed counter – the number of generate operations since the last credited (re)seed, starting at 1.
int wc_RNG_DRBG_ScheduleReseed(WC_RNG * rng)
Mark rng due for reseed: the next generate operation reseeds from the module's built-in or registered seed source before producing output. This can only shorten the current seed's remaining lifetime, never extend it.
int wc_RNG_DRBG_Reseed_Now(WC_RNG * rng, const byte * nonce, word32 nonceSz)
Immediately reseed rng from the module's built-in or registered seed source, with an optional nonce as additional input. The credited reseed resets the reseed counter.
int wc_RNG_DRBG_Reseed_Nonce(WC_RNG * rng, const byte * seed, word32 seedSz, const byte * nonce, word32 nonceSz)
Reseed rng's DRBG with caller-supplied seed material and an optional nonce as additional input. The material is credited as entropy: the reseed counter resets.
int wc_RNG_DRBG_Stir(WC_RNG * rng, const byte * seed, word32 seedSz)
Similar to wc_RNG_DRBG_Reseed(), except the caller-supplied material is mixed through the reseed derivation function without being credited as entropy: the reseed counter is not reset, so only the module's own seed source ever extends the instance's seed lifetime.
int wc_RNG_DRBG_Stir_Nonce(WC_RNG * rng, const byte * seed, word32 seedSz, const byte * nonce, word32 nonceSz)
The nonce_bearing form of wc_RNG_DRBG_Stir().
int wc_InitRngRBGC(WC_RNG * child, WC_RNG * parent, word32 flags)
Instantiate child as an SP 800_90C RBG_chain member subordinate to parent, drawing its seed material from parent's generate function in place of the module's seed source. Every other aspect of instantiation is wc_InitRng_ex2()'s. The child is tagged with stratum (parent's stratum + 1), sticky for the instance's lifetime even across subsequent source reseeds; its claimable security strength is capped by parent's, and it has no prediction resistance. The caller must hold exclusive access to parent for the duration of the call; the spawn debits parent's reseed counter by one generate.
int wc_InitRngNonceRBGC(WC_RNG * child, WC_RNG * parent, const byte * nonce, word32 nonceSz, word32 flags)
The nonce_bearing form of wc_InitRngRBGC(): the nonce is used as additional instantiation input, as in wc_InitRngNonce_ex2().
int wc_InitRngRBGC_New(WC_RNG ** child, WC_RNG * parent, word32 flags)
The allocating form of wc_InitRngRBGC(): the child is allocated from parent's heap and returned through child. Release with wc_rng_free().
int wc_InitRngNonceRBGC_New(WC_RNG ** child, WC_RNG * parent, const byte * nonce, word32 nonceSz, word32 flags)
The allocating, nonce_bearing form of wc_InitRngRBGC().
int wc_RNG_DRBG_ReseedRBGC(WC_RNG * rng, WC_RNG * root, const byte * nonce, word32 nonceSz)
Reseed rng from root's generate output – the SP 800_90C chain reseed – with an optional nonce as additional input. The reseed is credited (the reseed counter resets) and rng acquires root's stratum plus one. The caller must hold exclusive access to both instances.
int wc_RNG_DRBG_StirRBGC(WC_RNG * rng, WC_RNG * root, const byte * nonce, word32 nonceSz)
The uncredited form of wc_RNG_DRBG_ReseedRBGC(): material from root is mixed in without resetting rng's reseed counter.
int wc_RNG_DRBG_GetRBGCStratum(const WC_RNG * rng)
Report rng's RBG_chain stratum: 0 for a root (never chain_seeded), n for a member seeded from a stratum_(n_1) parent. The stratum is sticky for the instance's lifetime, even across subsequent source reseeds.
int wc_RNG_DRBG_GetNextSeedRBGCStratum(const WC_RNG * rng)
Report the RBG-chain stratum of rng's banked next seed – race-free via the aperture protocol – for provenance-aware consumers.
int wc_RNG_DRBG_NextSeedGenerate(WC_RNG * rng, word32 n)
Bank up to n more bytes of next-seed material from the module's seed source, health-testing and publishing the bank when it completes. The fill is incremental and in-boundary; a scheduling daemon may call this without owning the instance – the single-writer fill and the atomic aperture hand-off make it safe alongside a concurrent consumer.
int wc_RNG_DRBG_NextSeedGenerate_RBGC(WC_RNG * rng, WC_RNG * root, word32 n)
The chain_sourced form of wc_RNG_DRBG_NextSeedGenerate(): the banked material is drawn from root's generate function, and the bank is tagged with root's stratum plus one for provenance-aware consumption.
int wc_RNG_DRBG_NextSeedCurrent(WC_RNG * rng, WC_ATOMIC_INT_ARG * n)
Report the raw next_seed aperture value: a non_negative banked byte count (filling), WC_DRBG_NEXT_SEED_READY, or WC_DRBG_NEXT_SEED_CONSUMING. The snapshot is racy by design; use it for scheduling and diagnostics, not for hand-off decisions.
int wc_RNG_DRBG_NextSeedNow(WC_RNG * rng)
Claim a ready next_seed bank and perform a source_free credited reseed with it – safe in atomic context. The bank empties (use_once) and the reseed counter resets. The caller must own the instance.
int wc_RNG_DRBG_NextSeedNow_Nonce(WC_RNG * rng, const byte * nonce, word32 nonceSz)
The nonce_bearing form of wc_RNG_DRBG_NextSeedNow(): the nonce is mixed in as uncredited additional input alongside the banked seed.
int wc_RNG_DRBG_NextStirStore(WC_RNG * rng, const byte * nonce, word32 nonceSz)
Bank caller_supplied material (up to WC_DRBG_NEXT_STIR_LEN bytes) in the uncredited accumulator beside the banked next seed. Writer_safe without a lease (read_copy_store); if the accumulator is already full, the material is absorbed by xor. Harvested entropy deposited here improves the instance without claiming credit.
int wc_RNG_DRBG_NextStirNow(WC_RNG * rng)
Stir the banked uncredited accumulator into the DRBG as an uncredited, source-free mix-in – safe in atomic context; the reseed counter is not reset. The caller must own the instance.
int wc_RNG_lock_get(WC_RNG * rng, WC_RNG_lock_arg_t extra_bits)
Acquire rng's exclusive-ownership lock latch, spinning on the CAS until acquired, and or the caller's extra bits into the lock word. On an instance without the lock-required policy the call is a successful no-op unless extra bits are supplied.
int wc_RNG_lock_get_conditional(WC_RNG * rng, WC_RNG_lock_arg_t expected_extra_bits, WC_RNG_lock_arg_t want_extra_bits)
The conditional form of wc_RNG_lock_get(): acquire only if the current extra bits equal expected_extra_bits, atomically replacing them with want_extra_bits on success. Non-blocking with respect to the condition: a mismatch fails immediately rather than spinning.
int wc_RNG_lock_put(WC_RNG * rng, WC_RNG_lock_arg_t extra_bits)
Release rng's lock latch, clearing the supplied extra bits atomically with the release.
int wc_RNG_lock_put_conditional(WC_RNG * rng, WC_RNG_lock_arg_t expected_extra_bits, WC_RNG_lock_arg_t want_extra_bits)
The conditional form of wc_RNG_lock_put(): release only if the current extra bits equal expected_extra_bits, atomically replacing them with want_extra_bits on success.
int wc_RNG_lock_read(WC_RNG * rng, WC_RNG_lock_arg_t * state)
Read rng's lock word: the held/required latch bits, the entropy-invalidated bit, and any caller extra bits. The snapshot is racy by design.
int wc_RNG_lock_set_extra(WC_RNG * rng, WC_RNG_lock_arg_t extra_bits)
Atomically set (or) the supplied caller extra bits in rng's lock word. The caller should hold the latch.
int wc_RNG_lock_add_extra(WC_RNG * rng, WC_RNG_lock_arg_t extra_bits)
Atomically add the supplied value to the caller extra-bits field of rng's lock word – for counters carried above WC_RNG_LOCK_EXTRA_SHIFT.
int wc_RNG_lock_clear_extra(WC_RNG * rng, WC_RNG_lock_arg_t extra_bits)
Atomically clear the supplied caller extra bits in rng's lock word.
int wc_RNG_invalidate_entropy(WC_RNG * rng)
Mark rng's seed material untrusted – for VM fork/resume and similar duplication events – opening a new invalidation epoch: banked and pooled pre_event material is purged and wiped first, then the entropy_invalidated bit is latched in the lock word. An invalidated instance refuses service (NEEDS_RECOVERY_E) until recovery_reseeded. Latch or condemn: on any error return the latch is down, and the instance is instead condemned (status DRBG_FAILED). A condemned bank instance is retired and recovered by the entropy daemon; a condemned leaf gets no daemon rescue – its owner sees RNG_FAILURE_E from subsequent operations and recovers it with wc_FreeRng() then wc_InitRng*().
int wc_RNG_register_free_hook(WC_RNG * rng, wc_RNG_free_hook_cb_t free_hook, void * arg)
Register a callback fired by wc_FreeRng() at teardown – for external registries (e.g. a kernel_module registry that must reach every live RNG on a VM duplication event) that need to drop their reference when the object dies.
int wc_RNG_Pool_Alloc(WC_RNG * rng, word32 size)
Attach a random pool to rng: a buffer of size bytes of pre_generated output, filled by wc_RNG_Pool_Collect() and drained atomic_context_safely by wc_RNG_Pool_Extract(). The pool is released with the instance.
int wc_RNG_Pool_Collect(WC_RNG * rng, word32 n)
Generate up to n bytes into rng's pool from rng itself. The collect/extract hand-off is arbitrated by an atomic aperture word, so a single collector is safe alongside concurrent extractors.
int wc_RNG_Pool_Collect2(WC_RNG * rng_dest, WC_RNG * rng_src, word32 n)
The two_instance form of wc_RNG_Pool_Collect(): fill rng_dest's pool with output drawn from rng_src – so a service instance's pool can be topped up by a daemon-owned generator.
int wc_RNG_Pool_Extract(WC_RNG * rng, byte * out, word32 * n)
Drain up to n bytes from rng's pool into out – atomic-context-safe. On success n reports the bytes actually delivered; on any error return *n is left unmodified.
int wc_RNG_Pool_Current(WC_RNG * rng, word32 * n)
Report the pool's current fill in bytes. The snapshot is racy by design.
int wc_rng_debug_stats_snap(struct wc_rng_debug_stats_snapshot * s, const WC_RNG * rng)
Snapshot the global RNG debug counters (WC_RNG_DEBUG_STATS) – seeds and reseeds by provenance, generates, pool and bank traffic – into s, for later delta accounting with wc_rng_debug_stats_sum().
int wc_rng_debug_stats_restore(const struct wc_rng_debug_stats_snapshot * s, WC_RNG * rng)
Restore the global RNG debug counters from a snapshot – so a test can unwind its own accounting.
int wc_rng_debug_stats_sum(struct wc_rng_debug_stats_snapshot * s, const WC_RNG * rng)
Accumulate the current global RNG debug counters into s – combined with a prior wc_rng_debug_stats_snap(), a delta accounting of the interval's RNG activity.
int wc_rng_bank_new(struct wc_rng_bank * ctx, int n_rngs, word32 flags, int timeout_secs, void * heap, int devId)
Allocate and initialize a bank of n_rngs pre_instantiated WC_RNG instances, checked out and back in by consumers (wc_rng_bank_checkout() et al.). The bank is allocated from heap; release with wc_rng_bank_free(). Bank_level flags (WC_RNG_BANK_FLAG_
) fix the bank's posture at initialization: e.g. _CAN_WAIT admits sleeping, _QUIET suppresses seeding-degradation warnings, _NO_CHECKOUT_REFCOUNTING suppresses per-checkout refcount traffic for container-guaranteed lifetimes, _PREDICTION_RESISTANCE imposes a bank-wide fresh-reseed posture on every sleepable lease.
int wc_rng_bank_init(struct wc_rng_bank * ctx, int n_rngs, word32 flags, int timeout_secs, void * heap, int devId)
Initialize a caller_provided bank object. Semantics of wc_rng_bank_new(), without the allocation; release with wc_rng_bank_fini().
int wc_rng_bank_init_nonce(struct wc_rng_bank * ctx, int n_rngs, word32 flags, int timeout_secs, void * heap, int devId, const byte * nonce, word32 nonceSz, const byte * perso, word32 persoSz)
The nonce_bearing form of wc_rng_bank_init(): the nonce is used as additional instantiation input for each instance.
int wc_rng_bank_first_failover_inst_set(struct wc_rng_bank * ctx, int first_failover_inst)
Designate the first instance of the failover pool: checkouts without a targeted preference rotate through instances at and above first_failover_inst, reserving the lower offsets for targeted (affinity or daemon) use.
int wc_rng_bank_set_affinity_handlers(struct wc_rng_bank * ctx, wc_affinity_lock_fn_t affinity_lock_cb, wc_affinity_get_id_fn_t affinity_get_id_cb, wc_affinity_unlock_fn_t affinity_unlock_cb, void * cb_arg)
Install affinity handlers: callbacks that pin the caller to an execution context (e.g. disable preemption or migration), report its id for instance affinity, and unpin. With handlers installed, WC_RNG_BANK_FLAG_PREFER_AFFINITY_INST checkouts prefer the instance matching the caller's affinity id, and WC_RNG_BANK_FLAG_AFFINITY_LOCK holds the pin across the lease.
int wc_rng_bank_fini(struct wc_rng_bank * ctx)
Tear down a bank initialized with wc_rng_bank_init(): once the refcount and per-instance lease gates pass, fires any registered free hook and frees every instance. Never waits: a referenced or leased bank is refused with BUSY_E, and the caller quiesces its consumers and retries.
int wc_rng_bank_free(struct wc_rng_bank ** ctx)
Tear down and release a bank allocated with wc_rng_bank_new().
int wc_rng_bank_default_set(struct wc_rng_bank * bank)
Register bank as the process_default bank, retrievable with wc_rng_bank_default_checkout().
int wc_rng_bank_default_checkout(struct wc_rng_bank ** bank)
Take a reference on the process-default bank.
int wc_rng_bank_default_checkin(struct wc_rng_bank ** bank)
Release a reference taken with wc_rng_bank_default_checkout().
int wc_rng_bank_default_clear(struct wc_rng_bank * bank)
Unregister the process-default bank.
int wc_rng_bank_checkout(struct wc_rng_bank * bank, struct wc_rng_bank_inst ** rng_inst, int preferred_inst_offset, int timeout_secs, word32 flags)
Lease an in_service instance from the bank: either the preferred (or affinity_matched) instance, or – with WC_RNG_BANK_FLAG_CAN_FAIL_OVER_INST – the first available failover instance. On success the caller owns the instance's lock; access the WC_RNG with WC_RNG_BANK_INST_TO_RNG() and return the lease with wc_rng_bank_inst_checkin(). WC_RNG_BANK_FLAG_CONSUME_NEXT_SEED consumes a ready banked next seed in an immediate source_free credited reseed before returning; WC_RNG_BANK_FLAG_PREDICTION_RESISTANCE (per_call, requires _CAN_WAIT) freshly credited-reseeds the lease before the caller's first draw.
int wc_rng_bank_checkin(struct wc_rng_bank * bank, struct wc_rng_bank_inst ** rng_inst)
Return a lease through the bank object, validating that rng_inst belongs to bank. Prefer wc_rng_bank_inst_checkin() when only the instance pointer is at hand.
int wc_rng_bank_inst_checkin(struct wc_rng_bank_inst ** rng_inst)
Return a lease by instance pointer alone.
int wc_rng_bank_get_inst_id(struct wc_rng_bank_inst * rng_inst)
Report the instance's offset within its bank.
int wc_rng_bank_next_seed_generate(struct wc_rng_bank * bank, int inst_offset, word32 n)
Bank next_seed material for the instance at inst_offset –wc_RNG_DRBG_NextSeedGenerate() through the bank, without taking the instance lock; the daemon-side serialization word arbitrates against concurrent whole-instance reinitialization.
int wc_rng_bank_next_seed_generate_rbgc(struct wc_rng_bank * bank, int inst_offset, word32 n)
The chain_sourced form of wc_rng_bank_next_seed_generate(): the banked material is drawn from root's generate function and tagged with its provenance.
int wc_rng_bank_inst_reinit(struct wc_rng_bank * bank, struct wc_rng_bank_inst * rng_inst, int timeout_secs, word32 flags)
Free and reinstantiate a leased instance in place. The caller must hold the lease; the daemon-side serialization word excludes concurrent lockless banking during the cycle.
int wc_rng_bank_recover_inst(struct wc_rng_bank * bank, int inst_offset, int timeout_secs, word32 flags)
Patrol helper: check out the instance at inst_offset with WC_RNG_BANK_FLAG_FOR_RECOVERY, recover it iff it needs recovery, and check it back in. Two recovery arms: an out_of_service instance (wc_RNG_GetStatus() != WC_DRBG_OK) is reinitialized in place; an in_service but entropy_invalidated (quarantined) instance takes one credited reseed, which clears the quarantine while preserving instance identity. A healthy instance is a success no-op, so callers can invoke this unconditionally on state observed locklessly.
int wc_rng_bank_spawn(struct wc_rng_bank * bank, WC_RNG * child_rng, byte * nonce, word32 nonceSz, const byte * perso, word32 persoSz, int preferred_inst_offset, int timeout_secs, word32 flags)
Spawn an SP 800_90C chain RNG from a bank instance: check out a parent instance (honoring the usual selection flags), instantiate child_rng as its chain child (wc_InitRngNonceRBGC()), and check the parent back in. The child's lifetime is thereafter decoupled from the parent and its bank; release it with wc_FreeRng() (or wc_rng_free() for the heap form, wc_rng_bank_spawn_new()). The child's RBGC stratum is one plus the parent's stratum at instantiation.
int wc_rng_bank_spawn_new(struct wc_rng_bank * bank, WC_RNG ** child_rng, byte * nonce, word32 nonceSz, const byte * perso, word32 persoSz, int preferred_inst_offset, int timeout_secs, word32 flags)
The allocating form of wc_rng_bank_spawn(): the child is allocated from the bank's heap and returned through child_rng; release with wc_rng_free().
int wc_rng_bank_seed(struct wc_rng_bank * bank, const byte * seed, word32 seedSz, const byte * nonce, word32 nonceSz, int timeout_secs, word32 flags)
Reseed every instance with caller-supplied seed material. WC_RNG_BANK_FLAG_STIR mixes the material in without crediting it.
int wc_rng_bank_seed_range(struct wc_rng_bank * bank, int first_inst, int last_inst, const byte * seed, word32 seedSz, const byte * nonce, word32 nonceSz, int timeout_secs, word32 flags)
The range form of wc_rng_bank_seed(): seed instances first_inst through last_inst inclusive.
int wc_rng_bank_reseed(struct wc_rng_bank * bank, const byte * nonce, word32 nonceSz, int timeout_secs, word32 flags)
Reseed every instance from the module's seed source.
int wc_rng_bank_reseed_range(struct wc_rng_bank * bank, int first_inst, int last_inst, const byte * nonce, word32 nonceSz, int timeout_secs, word32 flags)
The range form of wc_rng_bank_reseed().
int wc_rng_bank_invalidate_entropy(struct wc_rng_bank * bank, word32 flags)
Set the entropy_invalidated latch on every instance (see wc_RNG_invalidate_entropy()): cached entropy products are discarded, and each instance is forced through a credited reseed before its next generate serves output. Lock_free and constant_time per instance; safe from a state_invalidation event context (VM fork/resume).
int wc_rng_bank_daemon_reserve(struct wc_rng_bank * bank, WC_ATOMIC_UINT_ARG magic)
Reserve the bank's daemon slot with a caller-chosen nonzero magic word, admitting exactly one scheduling daemon per bank. The lifecycle is strictly ordered: _reserve, then _register, then _unregister, then _release.
int wc_rng_bank_daemon_register(struct wc_rng_bank * bank, void * daemon, WC_ATOMIC_UINT_ARG magic)
Register the daemon object in a slot reserved with the same magic word.
int wc_rng_bank_daemon_unregister(struct wc_rng_bank * bank, void ** daemon, WC_ATOMIC_UINT_ARG magic)
Unregister the daemon object, returning it through daemon.
int wc_rng_bank_daemon_release(struct wc_rng_bank * bank, WC_ATOMIC_UINT_ARG magic)
Release the daemon slot claimed with magic, returning it to the free sentinel.
int wc_rng_bank_register_free_hook(struct wc_rng_bank * bank, wc_rng_bank_free_hook_cb_t free_hook, void * arg)
Register a callback fired by wc_rng_bank_fini() once its refcount and leak gates pass – i.e. once teardown is committed – for external registries that must drop their reference when the bank dies. One-shot: the hook is cleared before firing. A null free_hook unregisters.
int wc_InitRng_BankRef(struct wc_rng_bank * bank, WC_RNG * rng)
Initialize rng as a bank reference: a WC_RNG with no DRBG of its own, whose wc_RNG_GenerateBlock() transparently checks an instance out of bank, generates, and checks it back in. Release with wc_FreeRng().
int wc_BankRef_Release(WC_RNG * rng)
Release a bank reference. wc_FreeRng() calls this automatically for bank references; direct use is rarely needed.
int wc_rng_new_bankref(struct wc_rng_bank * bank, WC_RNG ** rng)
The allocating form of wc_InitRng_BankRef(): the reference is allocated from the bank's heap; release with wc_rng_free().
int wc_rng_bank_debug_stats_snap(struct wc_rng_debug_stats_snapshot * s, struct wc_rng_bank * bank)
Snapshot the RNG debug counters (WC_RNG_DEBUG_STATS) with bank-level context.

Detailed Description

Makes the unguessable numbers used for keys and other secrets. It takes a little true randomness from an entropy source and stretches it into as much output as you ask for.

When that source is wolfEntropy, see Entropy Source - wolfEntropy (MemUse).

Functions Documentation

function wc_InitNetRandom

int wc_InitNetRandom(
    const char * configFile,
    wnr_hmac_key hmac_cb,
    int timeout
)

Init global Whitewood netRandom context.

Parameters:

  • configFile Path to configuration file
  • hmac_cb Optional to create HMAC callback.
  • timeout A timeout duration.

See: wc_FreeNetRandom

Return:

  • 0 Success
  • BAD_FUNC_ARG Either configFile is null or timeout is negative.
  • RNG_FAILURE_E There was a failure initializing the rng.

Example

char* config = "path/to/config/example.conf";
int time = // Some sufficient timeout value;

if (wc_InitNetRandom(config, NULL, time) != 0)
{
    // Some error occurred
}

function wc_FreeNetRandom

int wc_FreeNetRandom(
    void 
)

Free global Whitewood netRandom context.

Parameters:

  • none No returns.

See: wc_InitNetRandom

Return:

  • 0 Success
  • BAD_MUTEX_E Error locking mutex on wnr_mutex

Example

int ret = wc_FreeNetRandom();
if(ret != 0)
{
    // Handle the error
}

function wc_InitRng

int wc_InitRng(
    WC_RNG * rng
)

Gets the seed (from OS) and key cipher for rng. rng->drbg (deterministic random bit generator) allocated (should be deallocated with wc_FreeRng). This is a blocking operation.

Parameters:

  • rng random number generator to be initialized for use with a seed and key cipher

See:

Return:

  • 0 on success.
  • MEMORY_E XMALLOC failed
  • WINCRYPT_E wc_GenerateSeed: failed to acquire context
  • CRYPTGEN_E wc_GenerateSeed: failed to get random
  • BAD_FUNC_ARG wc_RNG_GenerateBlock input is null or sz exceeds MAX_REQUEST_LEN
  • DRBG_CONT_FIPS_E wc_RNG_GenerateBlock: Hash_gen returned DRBG_CONT_FAILURE
  • RNG_FAILURE_E wc_RNG_GenerateBlock: Default error. rng’s status originally not ok, or set to DRBG_FAILED

Example

RNG  rng;
int ret;

#ifdef HAVE_CAVIUM
ret = wc_InitRngCavium(&rng, CAVIUM_DEV_ID);
if (ret != 0){
    printf(“RNG Nitrox init for device: %d failed”, CAVIUM_DEV_ID);
    return -1;
}
#endif
ret = wc_InitRng(&rng);
if (ret != 0){
    printf(“RNG init failed”);
    return -1;
}

function wc_RNG_GenerateBlock

int wc_RNG_GenerateBlock(
    WC_RNG * rng,
    byte * output,
    word32 sz
)

Copies a sz bytes of pseudorandom data to output. Will reseed rng if needed (blocking).

Parameters:

  • rng random number generator initialized with wc_InitRng
  • output buffer to which the block is copied
  • sz size of output in bytes

See:

Return:

  • 0 on success
  • BAD_FUNC_ARG an input is null or sz exceeds MAX_REQUEST_LEN
  • DRBG_CONT_FIPS_E Hash_gen returned DRBG_CONT_FAILURE
  • RNG_FAILURE_E Default error. rng’s status originally not ok, or set to DRBG_FAILED

Example

RNG  rng;
int  sz = 32;
byte block[sz];

int ret = wc_InitRng(&rng);
if (ret != 0) {
    return -1; //init of rng failed!
}

ret = wc_RNG_GenerateBlock(&rng, block, sz);
if (ret != 0) {
    return -1; //generating block failed!
}

function wc_RNG_GenerateByte

int wc_RNG_GenerateByte(
    WC_RNG * rng,
    byte * b
)

Calls wc_RNG_GenerateBlock to copy a byte of pseudorandom data to b. Will reseed rng if needed.

Parameters:

  • rng random number generator initialized with wc_InitRng
  • b one byte buffer to which the block is copied

See:

Return:

  • 0 on success
  • BAD_FUNC_ARG an input is null or sz exceeds MAX_REQUEST_LEN
  • DRBG_CONT_FIPS_E Hash_gen returned DRBG_CONT_FAILURE
  • RNG_FAILURE_E Default error. rng’s status originally not ok, or set to DRBG_FAILED

Example

RNG  rng;
int  sz = 32;
byte b[1];

int ret = wc_InitRng(&rng);
if (ret != 0) {
    return -1; //init of rng failed!
}

ret = wc_RNG_GenerateByte(&rng, b);
if (ret != 0) {
    return -1; //generating block failed!
}

function wc_FreeRng

int wc_FreeRng(
    WC_RNG * rng
)

Should be called when RNG no longer needed in order to securely free drgb. Zeros and XFREEs rng-drbg.

Parameters:

  • rng random number generator initialized with wc_InitRng

See:

Return:

  • 0 on success
  • BAD_FUNC_ARG rng or rng->drgb null
  • RNG_FAILURE_E Failed to deallocated drbg

Example

RNG  rng;
int ret = wc_InitRng(&rng);
if (ret != 0) {
    return -1; //init of rng failed!
}

int ret = wc_FreeRng(&rng);
if (ret != 0) {
    return -1; //free of rng failed!
}

function wc_RNG_HealthTest

int wc_RNG_HealthTest(
    int reseed,
    const byte * seedA,
    word32 seedASz,
    const byte * seedB,
    word32 seedBSz,
    byte * output,
    word32 outputSz
)

Creates and tests functionality of drbg.

Parameters:

  • int reseed: if set, will test reseed functionality
  • seedA seed to instantiate drgb with
  • seedASz size of seedA in bytes
  • seedB If reseed set, drbg will be reseeded with seedB
  • seedBSz size of seedB in bytes
  • output initialized to random data seeded with seedB if seedrandom is set, and seedA otherwise
  • outputSz length of output in bytes

See:

Return:

  • 0 on success
  • BAD_FUNC_ARG seedA and output must not be null. If reseed set seedB must not be null
  • -1 test failed

Example

byte output[SHA256_DIGEST_SIZE * 4];
const byte test1EntropyB[] = ....; // test input for reseed false
const byte test1Output[] = ....;   // testvector: expected output of
                               // reseed false
ret = wc_RNG_HealthTest(0, test1Entropy, sizeof(test1Entropy), NULL, 0,
                    output, sizeof(output));
if (ret != 0)
    return -1;//healthtest without reseed failed

if (XMEMCMP(test1Output, output, sizeof(output)) != 0)
    return -1; //compare to testvector failed: unexpected output

const byte test2EntropyB[] = ....; // test input for reseed
const byte test2Output[] = ....;   // testvector expected output of reseed
ret = wc_RNG_HealthTest(1, test2EntropyA, sizeof(test2EntropyA),
                    test2EntropyB, sizeof(test2EntropyB),
                    output, sizeof(output));

if (XMEMCMP(test2Output, output, sizeof(output)) != 0)
    return -1; //compare to testvector failed

function wc_GenerateSeed

int wc_GenerateSeed(
    OS_Seed * os,
    byte * output,
    word32 sz
)

Generates seed from OS entropy source. Lower-level function used internally by wc_InitRng.

Parameters:

  • os Pointer to OS_Seed structure
  • output Buffer to store seed
  • sz Size of seed in bytes

See: wc_InitRng

Return:

  • 0 On success
  • WINCRYPT_E Failed to acquire context (Windows)
  • CRYPTGEN_E Failed to generate random (Windows)
  • RNG_FAILURE_E Failed to read entropy

Example

OS_Seed os;
byte seed[32];
int ret = wc_GenerateSeed(&os, seed, sizeof(seed));

function wc_rng_new

WC_RNG * wc_rng_new(
    byte * nonce,
    word32 nonceSz,
    void * heap
)

Allocates and initializes new WC_RNG with optional nonce.

Parameters:

  • nonce Nonce buffer (can be NULL)
  • nonceSz Nonce size
  • heap Heap hint (can be NULL)

See: wc_rng_free

Return:

  • Pointer to WC_RNG on success
  • NULL on failure

Example

WC_RNG* rng = wc_rng_new(NULL, 0, NULL);
wc_rng_free(rng);

function wc_rng_new_ex

int wc_rng_new_ex(
    WC_RNG ** rng,
    byte * nonce,
    word32 nonceSz,
    void * heap,
    int devId
)

Allocates and initializes WC_RNG with extended parameters.

Parameters:

  • rng Pointer to store WC_RNG pointer
  • nonce Nonce buffer (can be NULL)
  • nonceSz Nonce size
  • heap Heap hint (can be NULL)
  • devId Device ID (INVALID_DEVID for software)

See: wc_rng_new

Return:

  • 0 On success
  • BAD_FUNC_ARG If rng is NULL
  • MEMORY_E Memory allocation failed

Example

WC_RNG* rng;
int ret = wc_rng_new_ex(&rng, NULL, 0, NULL, INVALID_DEVID);
wc_rng_free(rng);

function wc_rng_free

void wc_rng_free(
    WC_RNG * rng
)

Frees WC_RNG allocated with wc_rng_new.

Parameters:

  • rng WC_RNG to free

See: wc_rng_new

Example

WC_RNG* rng = wc_rng_new(NULL, 0, NULL);
wc_rng_free(rng);

function wc_InitRng_ex

int wc_InitRng_ex(
    WC_RNG * rng,
    void * heap,
    int devId
)

Initializes WC_RNG with extended parameters.

Parameters:

  • rng WC_RNG to initialize
  • heap Heap hint (can be NULL)
  • devId Device ID (INVALID_DEVID for software)

See: wc_InitRng

Return:

  • 0 On success
  • BAD_FUNC_ARG If rng is NULL
  • RNG_FAILURE_E Initialization failed

Example

WC_RNG rng;
int ret = wc_InitRng_ex(&rng, NULL, INVALID_DEVID);
wc_FreeRng(&rng);

function wc_InitRngNonce

int wc_InitRngNonce(
    WC_RNG * rng,
    const byte * nonce,
    word32 nonceSz
)

Initializes WC_RNG with nonce.

Parameters:

  • rng WC_RNG to initialize
  • nonce Nonce buffer
  • nonceSz Nonce size

See: wc_InitRng

Return:

  • 0 On success
  • BAD_FUNC_ARG If rng is NULL
  • RNG_FAILURE_E Initialization failed

Example

WC_RNG rng;
byte nonce[16];
int ret = wc_InitRngNonce(&rng, nonce, sizeof(nonce));
wc_FreeRng(&rng);

function wc_InitRngNonce_ex

int wc_InitRngNonce_ex(
    WC_RNG * rng,
    const byte * nonce,
    word32 nonceSz,
    void * heap,
    int devId
)

Initializes WC_RNG with nonce and extended parameters.

Parameters:

  • rng WC_RNG to initialize
  • nonce Nonce buffer
  • nonceSz Nonce size
  • heap Heap hint (can be NULL)
  • devId Device ID (INVALID_DEVID for software)

See: wc_InitRngNonce

Return:

  • 0 On success
  • BAD_FUNC_ARG If rng is NULL
  • RNG_FAILURE_E Initialization failed

Example

WC_RNG rng;
byte nonce[16];
int ret = wc_InitRngNonce_ex(&rng, nonce, sizeof(nonce), NULL,
                             INVALID_DEVID);
wc_FreeRng(&rng);

function wc_SetSeed_Cb

int wc_SetSeed_Cb(
    wc_RngSeed_Cb cb
)

Sets callback for custom seed generation.

Parameters:

  • cb Seed callback function

See: wc_GenerateSeed

Return:

  • 0 On success
  • BAD_FUNC_ARG If cb is NULL

Example

int my_cb(OS_Seed* os, byte* out, word32 sz) { return 0; }
wc_SetSeed_Cb(my_cb);

function wc_RNG_DRBG_Reseed

int wc_RNG_DRBG_Reseed(
    WC_RNG * rng,
    const byte * seed,
    word32 seedSz
)

Reseeds DRBG with new entropy.

Parameters:

  • rng WC_RNG to reseed
  • seed Seed buffer
  • seedSz Seed size

See: wc_InitRng

Return:

  • 0 On success
  • BAD_FUNC_ARG If rng or seed is NULL
  • RNG_FAILURE_E Reseed failed

Example

WC_RNG rng;
byte seed[32];
wc_InitRng(&rng);
int ret = wc_RNG_DRBG_Reseed(&rng, seed, sizeof(seed));

function wc_RNG_TestSeed

int wc_RNG_TestSeed(
    const byte * seed,
    word32 seedSz
)

Tests seed validity for DRBG.

Parameters:

  • seed Seed to test
  • seedSz Seed size

See: wc_InitRng

Return:

  • 0 If valid
  • BAD_FUNC_ARG If seed is NULL
  • ENTROPY_RT_E || ENTROPY_APT_E Validation failed
  • ENTROPY_APT_E The adaptive proportion test failed.
  • MEMORY_E Allocation failed.

Example

byte seed[32];
int ret = wc_RNG_TestSeed(seed, sizeof(seed));

function wc_RNG_HealthTest_ex

int wc_RNG_HealthTest_ex(
    int reseed,
    const byte * nonce,
    word32 nonceSz,
    const byte * seedA,
    word32 seedASz,
    const byte * seedB,
    word32 seedBSz,
    byte * output,
    word32 outputSz,
    void * heap,
    int devId
)

RNG health test with extended parameters.

Parameters:

  • reseed Non-zero to test reseeding
  • nonce Nonce buffer (can be NULL)
  • nonceSz Nonce size
  • seedA Initial seed
  • seedASz Initial seed size
  • seedB Reseed buffer (required if reseed set)
  • seedBSz Reseed size
  • output Output buffer
  • outputSz Output size
  • heap Heap hint (can be NULL)
  • devId Device ID (INVALID_DEVID for software)

See: wc_RNG_HealthTest

Return:

  • 0 On success
  • BAD_FUNC_ARG If required params NULL
  • -1 Test failed

Example

byte seedA[32], seedB[32], out[64];
int ret = wc_RNG_HealthTest_ex(1, NULL, 0, seedA, 32, seedB, 32,
                               out, 64, NULL, INVALID_DEVID);

function wc_RNG_HealthTest_SHA512

int wc_RNG_HealthTest_SHA512(
    int reseed,
    const byte * seedA,
    word32 seedASz,
    const byte * seedB,
    word32 seedBSz,
    byte * output,
    word32 outputSz
)

Runs the SHA-512 Hash_DRBG Known Answer Test (KAT) per SP 800-90A. Instantiates a SHA-512 DRBG with seedA, optionally reseeds with seedB, generates output, and compares against known test vectors. Available when WOLFSSL_DRBG_SHA512 is defined.

Parameters:

  • reseed Non-zero to test reseeding
  • seedA Initial entropy seed
  • seedASz Size of seedA in bytes
  • seedB Reseed entropy (required if reseed is set)
  • seedBSz Size of seedB in bytes
  • output Buffer to receive generated output
  • outputSz Size of output in bytes

See:

Return:

  • 0 On success
  • BAD_FUNC_ARG If seedA or output is NULL, or if reseed is set and seedB is NULL
  • -1 Test failed

Example

byte output[WC_SHA512_DIGEST_SIZE * 4];
const byte seedA[] = { ... };
const byte seedB[] = { ... };

ret = wc_RNG_HealthTest_SHA512(0, seedA, sizeof(seedA), NULL, 0,
                               output, sizeof(output));
if (ret != 0)
    return -1;

ret = wc_RNG_HealthTest_SHA512(1, seedA, sizeof(seedA),
                               seedB, sizeof(seedB),
                               output, sizeof(output));
if (ret != 0)
    return -1;

function wc_RNG_HealthTest_SHA512_ex

int wc_RNG_HealthTest_SHA512_ex(
    int reseed,
    const byte * nonce,
    word32 nonceSz,
    const byte * persoString,
    word32 persoStringSz,
    const byte * seedA,
    word32 seedASz,
    const byte * seedB,
    word32 seedBSz,
    const byte * additionalA,
    word32 additionalASz,
    const byte * additionalB,
    word32 additionalBSz,
    byte * output,
    word32 outputSz,
    void * heap,
    int devId
)

Extended SHA-512 Hash_DRBG health test with nonce, personalization string, and additional input support. Suitable for full ACVP / CAVP test vector validation. Available when WOLFSSL_DRBG_SHA512 is defined.

Parameters:

  • reseed Non-zero to test reseeding
  • nonce Nonce buffer (can be NULL)
  • nonceSz Nonce size
  • persoString Personalization string (can be NULL)
  • persoStringSz Personalization string size
  • seedA Initial entropy seed
  • seedASz Initial seed size
  • seedB Reseed entropy (required if reseed is set)
  • seedBSz Reseed size
  • additionalA Additional input for first generate (can be NULL)
  • additionalASz Additional input A size
  • additionalB Additional input for second generate (can be NULL)
  • additionalBSz Additional input B size
  • output Output buffer
  • outputSz Output size
  • heap Heap hint (can be NULL)
  • devId Device ID (INVALID_DEVID for software)

See:

Return:

  • 0 On success
  • BAD_FUNC_ARG If required params are NULL
  • -1 Test failed

Example

byte output[WC_SHA512_DIGEST_SIZE * 4];
const byte seedA[] = { ... };
const byte nonce[] = { ... };

int ret = wc_RNG_HealthTest_SHA512_ex(0, nonce, sizeof(nonce),
                                      NULL, 0,
                                      seedA, sizeof(seedA),
                                      NULL, 0,
                                      NULL, 0, NULL, 0,
                                      output, sizeof(output),
                                      NULL, INVALID_DEVID);

function wc_Sha256Drbg_Disable

int wc_Sha256Drbg_Disable(
    void 
)

Disables the SHA-256 Hash_DRBG at runtime. When disabled, newly initialized WC_RNG instances will not use the SHA-256 DRBG. If the SHA-512 DRBG is enabled (WOLFSSL_DRBG_SHA512), new RNG instances will use SHA-512 instead. Requires HAVE_HASHDRBG.

See:

Return: 0 On success

Example

wc_Sha256Drbg_Disable();
// New WC_RNG instances will now use SHA-512 DRBG if available
WC_RNG rng;
wc_InitRng(&rng);

function wc_Sha256Drbg_Enable

int wc_Sha256Drbg_Enable(
    void 
)

Re-enables the SHA-256 Hash_DRBG at runtime after a prior call to wc_Sha256Drbg_Disable(). Requires HAVE_HASHDRBG.

See:

Return: 0 On success

Example

wc_Sha256Drbg_Disable();
// ... use SHA-512 DRBG only ...
wc_Sha256Drbg_Enable();
// New WC_RNG instances can use SHA-256 DRBG again

function wc_Sha256Drbg_IsDisabled

int wc_Sha256Drbg_IsDisabled(
    void 
)

Returns whether the SHA-256 Hash_DRBG is currently disabled. Requires HAVE_HASHDRBG.

See:

Return:

  • 1 SHA-256 DRBG is disabled
  • 0 SHA-256 DRBG is enabled (not disabled)

Example

if (wc_Sha256Drbg_IsDisabled()) {
    printf("SHA-256 DRBG is off\n");
}

function wc_Sha512Drbg_Disable

int wc_Sha512Drbg_Disable(
    void 
)

Disables the SHA-512 Hash_DRBG at runtime. When disabled, newly initialized WC_RNG instances will not use the SHA-512 DRBG. If the SHA-256 DRBG is still enabled, new RNG instances will fall back to SHA-256. Available when WOLFSSL_DRBG_SHA512 is defined. Requires HAVE_HASHDRBG.

See:

Return: 0 On success

Example

wc_Sha512Drbg_Disable();
// New WC_RNG instances will now use SHA-256 DRBG
WC_RNG rng;
wc_InitRng(&rng);

function wc_Sha512Drbg_Enable

int wc_Sha512Drbg_Enable(
    void 
)

Re-enables the SHA-512 Hash_DRBG at runtime after a prior call to wc_Sha512Drbg_Disable(). Available when WOLFSSL_DRBG_SHA512 is defined. Requires HAVE_HASHDRBG.

See:

Return: 0 On success

Example

wc_Sha512Drbg_Disable();
// ... use SHA-256 DRBG only ...
wc_Sha512Drbg_Enable();
// New WC_RNG instances can use SHA-512 DRBG again

function wc_Sha512Drbg_IsDisabled

int wc_Sha512Drbg_IsDisabled(
    void 
)

Returns whether the SHA-512 Hash_DRBG is currently disabled. Available when WOLFSSL_DRBG_SHA512 is defined. Requires HAVE_HASHDRBG.

See:

Return:

  • 1 SHA-512 DRBG is disabled
  • 0 SHA-512 DRBG is enabled (not disabled)

Example

if (wc_Sha512Drbg_IsDisabled()) {
    printf("SHA-512 DRBG is off\n");
}

function wc_InitRng_ex2

int wc_InitRng_ex2(
    WC_RNG * rng,
    void * heap,
    int devId,
    word32 flags
)

Initialize a WC_RNG with instantiation-time security attributes. Identical to wc_InitRng_ex(), with a flags argument fixing attributes at birth: WC_RNG_INIT_FLAG_LOCK_REQUIRED latches the sticky lock_required policy bit, so there is no reachable state in which the instance serves without its lock policy; WC_RNG_INIT_FLAG_LOCK_INITIALLY constructs into a held lease, to be released with wc_RNG_lock_put(); WC_RNG_INIT_FLAG_USE_FULL_MUTEX layers a blocking wolfSSL_Mutex outermost around the lock latch, for user_mode sharing of one instance among threads (requires WC_RNG_HAVE_LOCK_FULL_MUTEX).

Parameters:

  • rng The RNG object to initialize.
  • heap Heap hint for dynamic allocation.
  • devId Device id, or INVALID_DEVID.
  • flags Bitwise-or of WC_RNG_INIT_FLAG_* attributes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • NOT_COMPILED_IN A requested flag is not compiled in.

Example

WC_RNG rng;
if (wc_InitRng_ex2(&rng, NULL, INVALID_DEVID,
                   WC_RNG_INIT_FLAG_LOCK_REQUIRED |
                   WC_RNG_INIT_FLAG_LOCK_INITIALLY) != 0) {
    // error handling
}
// caller holds the lease from birth

function wc_InitRngNonce_ex2

int wc_InitRngNonce_ex2(
    WC_RNG * rng,
    const byte * nonce,
    word32 nonceSz,
    const byte * perso,
    word32 persoSz,
    void * heap,
    int devId,
    word32 flags
)

Initialize a WC_RNG with a caller-supplied nonce and instantiation-time security attributes. The nonce semantics are those of wc_InitRngNonce_ex(); the flags semantics are those of wc_InitRng_ex2().

Parameters:

  • rng The RNG object to initialize.
  • nonce Optional nonce used as additional instantiation input.
  • nonceSz Length of nonce in bytes.
  • heap Heap hint for dynamic allocation.
  • devId Device id, or INVALID_DEVID.
  • perso Optional personalization string (may be null).
  • persoSz Length of perso in bytes.
  • flags Bitwise-or of WC_RNG_INIT_FLAG_* attributes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • NOT_COMPILED_IN A requested flag is not compiled in.

function wc_RNG_GetStatus

int wc_RNG_GetStatus(
    const WC_RNG * rng
)

Read-only accessor for the RNG health status. Returns the instance's enum wc_RngHealthState value (WC_DRBG_NOT_INIT, WC_DRBG_OK, WC_DRBG_FAILED, WC_DRBG_CONT_FAILED).

Parameters:

  • rng The RNG object to interrogate.

See:

Return:

  • WC_DRBG_OK The instance is in service.
  • BAD_FUNC_ARG rng is null.

Example

if (wc_RNG_GetStatus(&rng) != WC_DRBG_OK) {
    // instance is not serviceable
}

function wc_RNG_DRBG_Present

int wc_RNG_DRBG_Present(
    const WC_RNG * rng
)

Returns 1 if rng has an instantiated DRBG, else 0. An in-service WC_RNG can lack one: instantiation bypasses the DRBG when the CPU has RDRAND (HAVE_INTEL_RDRAND). DRBG-specific services (commanded reseed, banked next seeds, RBG chains) are unavailable on such instances.

Parameters:

  • rng The RNG object to interrogate.

See:

Return:

  • 1 rng has a live DRBG.
  • 0 rng is null or has no DRBG.

function wc_RNG_DRBG_GetReseedCtr

int wc_RNG_DRBG_GetReseedCtr(
    const WC_RNG * rng,
    wc_drbg_reseed_ctr_t * reseedCtr
)

Report the DRBG's current reseed counter – the number of generate operations since the last credited (re)seed, starting at 1.

Parameters:

  • rng The RNG object to interrogate.
  • reseedCtr Receives the counter.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or reseedCtr is null.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).

function wc_RNG_DRBG_ScheduleReseed

int wc_RNG_DRBG_ScheduleReseed(
    WC_RNG * rng
)

Mark rng due for reseed: the next generate operation reseeds from the module's built-in or registered seed source before producing output. This can only shorten the current seed's remaining lifetime, never extend it.

Parameters:

  • rng The RNG object to schedule.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.) – a commanded reseed that cannot happen is not a success.

function wc_RNG_DRBG_Reseed_Now

int wc_RNG_DRBG_Reseed_Now(
    WC_RNG * rng,
    const byte * nonce,
    word32 nonceSz
)

Immediately reseed rng from the module's built-in or registered seed source, with an optional nonce as additional input. The credited reseed resets the reseed counter.

Parameters:

  • rng The RNG object to reseed.
  • nonce Optional additional input.
  • nonceSz Length of nonce in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null, or nonce is null with nonceSz nonzero.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).
  • DRBG_CONT_FIPS_E The continuous test failed; the DRBG is out of service.
  • RNG_FAILURE_E The DRBG is out of service or reseeding failed.

function wc_RNG_DRBG_Reseed_Nonce

int wc_RNG_DRBG_Reseed_Nonce(
    WC_RNG * rng,
    const byte * seed,
    word32 seedSz,
    const byte * nonce,
    word32 nonceSz
)

Reseed rng's DRBG with caller-supplied seed material and an optional nonce as additional input. The material is credited as entropy: the reseed counter resets.

Parameters:

  • rng The RNG object to reseed.
  • seed Seed material.
  • seedSz Length of seed in bytes.
  • nonce Optional additional input.
  • nonceSz Length of nonce in bytes.

See:

Return:

  • 0 Success
  • RNG_FAILURE_E rng is condemned (status DRBG_FAILED): a condemned instance does not accept a credited reseed; recover with wc_FreeRng() then wc_InitRng*().
  • BAD_FUNC_ARG rng or seed is null.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).

function wc_RNG_DRBG_Stir

int wc_RNG_DRBG_Stir(
    WC_RNG * rng,
    const byte * seed,
    word32 seedSz
)

Similar to wc_RNG_DRBG_Reseed(), except the caller-supplied material is mixed through the reseed derivation function without being credited as entropy: the reseed counter is not reset, so only the module's own seed source ever extends the instance's seed lifetime.

Parameters:

  • rng The RNG object to stir.
  • seed Material to mix in.
  • seedSz Length of seed in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or seed is null.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).

function wc_RNG_DRBG_Stir_Nonce

int wc_RNG_DRBG_Stir_Nonce(
    WC_RNG * rng,
    const byte * seed,
    word32 seedSz,
    const byte * nonce,
    word32 nonceSz
)

The nonce-bearing form of wc_RNG_DRBG_Stir().

Parameters:

  • rng The RNG object to stir.
  • seed Material to mix in.
  • seedSz Length of seed in bytes.
  • nonce Optional additional input.
  • nonceSz Length of nonce in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or seed is null.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).

function wc_InitRngRBGC

int wc_InitRngRBGC(
    WC_RNG * child,
    WC_RNG * parent,
    word32 flags
)

Instantiate child as an SP 800-90C RBG-chain member subordinate to parent, drawing its seed material from parent's generate function in place of the module's seed source. Every other aspect of instantiation is wc_InitRng_ex2()'s. The child is tagged with stratum (parent's stratum + 1), sticky for the instance's lifetime even across subsequent source reseeds; its claimable security strength is capped by parent's, and it has no prediction resistance. The caller must hold exclusive access to parent for the duration of the call; the spawn debits parent's reseed counter by one generate.

Parameters:

  • child The caller-provided WC_RNG to instantiate (uninitialized).
  • parent The chain parent to draw seed material from.
  • flags Bitwise-or of WC_RNG_INIT_FLAG_* attributes for the child.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG child or parent is null, or child equals parent.
  • SEQ_OVERFLOW_E parent's stratum is at the representable maximum.

Example

WC_RNG root, child;
wc_InitRng(&root);
if (wc_InitRngRBGC(&child, &root, WC_RNG_INIT_FLAG_NONE) == 0) {
    // child serves independently; release with wc_FreeRng(&child)
}

function wc_InitRngNonceRBGC

int wc_InitRngNonceRBGC(
    WC_RNG * child,
    WC_RNG * parent,
    const byte * nonce,
    word32 nonceSz,
    word32 flags
)

The nonce-bearing form of wc_InitRngRBGC(): the nonce is used as additional instantiation input, as in wc_InitRngNonce_ex2().

Parameters:

  • child The caller-provided WC_RNG to instantiate (uninitialized).
  • parent The chain parent to draw seed material from.
  • nonce Additional instantiation input.
  • nonceSz Length of nonce in bytes.
  • flags Bitwise-or of WC_RNG_INIT_FLAG_* attributes for the child.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG child or parent is null, child equals parent, or nonce is null with nonceSz nonzero.
  • SEQ_OVERFLOW_E parent's stratum is at the representable maximum.

function wc_InitRngRBGC_New

int wc_InitRngRBGC_New(
    WC_RNG ** child,
    WC_RNG * parent,
    word32 flags
)

The allocating form of wc_InitRngRBGC(): the child is allocated from parent's heap and returned through child. Release with wc_rng_free().

Parameters:

  • child Receives the allocated, instantiated WC_RNG.
  • parent The chain parent to draw seed material from.
  • flags Bitwise-or of WC_RNG_INIT_FLAG_* attributes for the child.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG child or parent is null.
  • MEMORY_E Allocation failed.
  • SEQ_OVERFLOW_E parent's stratum is at the representable maximum.

function wc_InitRngNonceRBGC_New

int wc_InitRngNonceRBGC_New(
    WC_RNG ** child,
    WC_RNG * parent,
    const byte * nonce,
    word32 nonceSz,
    word32 flags
)

The allocating, nonce-bearing form of wc_InitRngRBGC().

Parameters:

  • child Receives the allocated, instantiated WC_RNG.
  • parent The chain parent to draw seed material from.
  • nonce Additional instantiation input.
  • nonceSz Length of nonce in bytes.
  • flags Bitwise-or of WC_RNG_INIT_FLAG_* attributes for the child.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG child or parent is null, or nonce is null with nonceSz nonzero.
  • MEMORY_E Allocation failed.
  • SEQ_OVERFLOW_E parent's stratum is at the representable maximum.

function wc_RNG_DRBG_ReseedRBGC

int wc_RNG_DRBG_ReseedRBGC(
    WC_RNG * rng,
    WC_RNG * root,
    const byte * nonce,
    word32 nonceSz
)

Reseed rng from root's generate output – the SP 800-90C chain reseed – with an optional nonce as additional input. The reseed is credited (the reseed counter resets) and rng acquires root's stratum plus one. The caller must hold exclusive access to both instances.

Parameters:

  • rng The chain member to reseed.
  • root The chain parent to draw seed material from.
  • nonce Optional additional input.
  • nonceSz Length of nonce in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or root is null, rng equals root, or the no-downgrade rule refuses root as a chain parent (see
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).
  • SEQ_OVERFLOW_E root's stratum is at the representable maximum.

Credited chain reseeds obey a no-downgrade rule: a primary-seeded (stratum-0) root is always accepted, and a chained (stratum > 0) root is accepted only when its stratum is strictly less than rng's – the acquired stratum never increases, so reseed cycles are impossible by construction, consistent with SP 800-90C 7.1.2.2. Lateral (equal-stratum) and downgrading reseeds are refused with BAD_FUNC_ARG. Building WC_RNG_NO_RBGC_RESEED restricts credited chain reseeds to primary-seeded roots. Uncredited chain stirs (wc_RNG_DRBG_StirRBGC()) are exempt from all of this: they are stirs, claim nothing, and leave rng's stratum untouched.

).

function wc_RNG_DRBG_StirRBGC

int wc_RNG_DRBG_StirRBGC(
    WC_RNG * rng,
    WC_RNG * root,
    const byte * nonce,
    word32 nonceSz
)

The uncredited form of wc_RNG_DRBG_ReseedRBGC(): material from root is mixed in without resetting rng's reseed counter.

Parameters:

  • rng The chain member to stir.
  • root The chain parent to draw material from.
  • nonce Optional additional input.
  • nonceSz Length of nonce in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or root is null, or rng equals root.
  • WRONG_TYPE_OBJECT_E rng has no DRBG (RDRAND et al.).

Unrestricted by the credited no-downgrade rule: any source stratum is accepted, and rng's reseed counter, stratum, and entropy-invalidated state are all left untouched – an uncredited chain reseed is a stir, and a stir must never masquerade as recovery or promotion.

function wc_RNG_DRBG_GetRBGCStratum

int wc_RNG_DRBG_GetRBGCStratum(
    const WC_RNG * rng
)

Report rng's RBG-chain stratum: 0 for a root (never chain-seeded), n for a member seeded from a stratum-(n-1) parent. The stratum is sticky for the instance's lifetime, even across subsequent source reseeds.

Parameters:

  • rng The RNG object to interrogate.

See:

Return:

  • 0 rng is a chain root.
  • n The stratum, positive for a chain member.
  • BAD_FUNC_ARG rng is null.

function wc_RNG_DRBG_GetNextSeedRBGCStratum

int wc_RNG_DRBG_GetNextSeedRBGCStratum(
    const WC_RNG * rng
)

Report the RBG-chain stratum of rng's banked next seed – race-free via the aperture protocol – for provenance-aware consumers.

Parameters:

  • rng The RNG object to interrogate.

See:

Return:

  • 0 The banked seed has root (source) provenance.
  • n The banked seed's stratum, positive for chain provenance.
  • BAD_FUNC_ARG rng is null or has no DRBG.
  • NOT_READY_E No banked seed is ready.

function wc_RNG_DRBG_NextSeedGenerate

int wc_RNG_DRBG_NextSeedGenerate(
    WC_RNG * rng,
    word32 n
)

Bank up to n more bytes of next-seed material from the module's seed source, health-testing and publishing the bank when it completes. The fill is incremental and in-boundary; a scheduling daemon may call this without owning the instance – the single-writer fill and the atomic aperture hand-off make it safe alongside a concurrent consumer.

Parameters:

  • rng The RNG object whose bank to fill.
  • n Maximum bytes to bank this call (clamped to space remaining).

See:

Return:

  • 0 Bytes were banked (bank may or may not yet be complete).
  • ALREADY_E The bank is ready or being consumed.
  • NOT_READY_E The health test could not run; simply retry.
  • BAD_FUNC_ARG rng is null or n is 0.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).

Example

// scheduling daemon: fill incrementally until published
int ret = wc_RNG_DRBG_NextSeedGenerate(rng, 16);
if (ret == ALREADY_E) {
    // bank is ready; nothing to do until a consumer claims it
}

function wc_RNG_DRBG_NextSeedGenerate_RBGC

int wc_RNG_DRBG_NextSeedGenerate_RBGC(
    WC_RNG * rng,
    WC_RNG * root,
    word32 n
)

The chain-sourced form of wc_RNG_DRBG_NextSeedGenerate(): the banked material is drawn from root's generate function, and the bank is tagged with root's stratum plus one for provenance-aware consumption.

Parameters:

  • rng The RNG object whose bank to fill.
  • root The chain parent to draw material from.
  • n Maximum bytes to bank this call.

See:

Return:

  • 0 Bytes were banked.
  • ALREADY_E The bank is ready or being consumed.
  • NOT_READY_E The health test could not run; simply retry.
  • BAD_FUNC_ARG rng or root is null, or n is 0.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).
  • SEQ_OVERFLOW_E root's stratum is at the representable maximum.

Banking is bound for credited redemption, so the credited no-downgrade rule applies at bank time: a primary-seeded (stratum-0) root is always accepted, and a chained root only when its stratum is strictly less than rng's – banking whose redemption would raise rng's stratum is refused with BAD_FUNC_ARG. The banked material records root's stratum plus one, observable via wc_RNG_DRBG_GetNextSeedRBGCStratum(), and redemption (wc_RNG_DRBG_NextSeedNow()) carries it onto rng.

function wc_RNG_DRBG_NextSeedCurrent

int wc_RNG_DRBG_NextSeedCurrent(
    WC_RNG * rng,
    WC_ATOMIC_INT_ARG * n
)

Report the raw next-seed aperture value: a non-negative banked byte count (filling), WC_DRBG_NEXT_SEED_READY, or WC_DRBG_NEXT_SEED_CONSUMING. The snapshot is racy by design; use it for scheduling and diagnostics, not for hand-off decisions.

Parameters:

  • rng The RNG object to interrogate.
  • n Receives the aperture value.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or n is null.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).

function wc_RNG_DRBG_NextSeedNow

int wc_RNG_DRBG_NextSeedNow(
    WC_RNG * rng
)

Claim a ready next-seed bank and perform a source-free credited reseed with it – safe in atomic context. The bank empties (use-once) and the reseed counter resets. The caller must own the instance.

Parameters:

  • rng The RNG object to reseed.

See:

Return:

  • 0 Success
  • NOT_READY_E No bank is ready.
  • BAD_FUNC_ARG rng is null.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).

Example

// atomic-context consumer
if (wc_RNG_DRBG_NextSeedNow(rng) == 0) {
    // freshly reseeded without touching the seed source
}

function wc_RNG_DRBG_NextSeedNow_Nonce

int wc_RNG_DRBG_NextSeedNow_Nonce(
    WC_RNG * rng,
    const byte * nonce,
    word32 nonceSz
)

The nonce-bearing form of wc_RNG_DRBG_NextSeedNow(): the nonce is mixed in as uncredited additional input alongside the banked seed.

Parameters:

  • rng The RNG object to reseed.
  • nonce Additional input.
  • nonceSz Length of nonce in bytes.

See: wc_RNG_DRBG_NextSeedNow

Return:

  • 0 Success
  • NEEDS_RECOVERY_E A purge crossed the consume (an invalidation epoch boundary): no material is adopted, the entropy-invalidated latch is re-asserted, and a recovery reseed is scheduled.
  • NOT_READY_E No bank is ready.
  • BAD_FUNC_ARG rng is null, or nonce is null with nonceSz nonzero.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).
  • DRBG_CONT_FIPS_E The continuous test failed; the DRBG is out of service.
  • RNG_FAILURE_E The DRBG is out of service.

function wc_RNG_DRBG_NextStirStore

int wc_RNG_DRBG_NextStirStore(
    WC_RNG * rng,
    const byte * nonce,
    word32 nonceSz
)

Bank caller-supplied material (up to WC_DRBG_NEXT_STIR_LEN bytes) in the uncredited accumulator beside the banked next seed. Writer-safe without a lease (read-copy-store); if the accumulator is already full, the material is absorbed by xor. Harvested entropy deposited here improves the instance without claiming credit.

Parameters:

  • rng The RNG object whose accumulator to feed.
  • nonce Material to bank.
  • nonceSz Length of nonce in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or nonce is null, or nonceSz is 0.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).

function wc_RNG_DRBG_NextStirNow

int wc_RNG_DRBG_NextStirNow(
    WC_RNG * rng
)

Stir the banked uncredited accumulator into the DRBG as an uncredited, source-free mix-in – safe in atomic context; the reseed counter is not reset. The caller must own the instance.

Parameters:

  • rng The RNG object to stir.

See: wc_RNG_DRBG_NextStirStore

Return:

  • 0 Success
  • NOT_READY_E The accumulator is empty or still accumulating, or the stir is refused (reseed interval, entropy-invalidated quarantine).
  • BUSY_E The accumulator was claimed by a racing consumer – the stir is happening by another hand.
  • BAD_FUNC_ARG rng is null.
  • MISSING_RNG_E rng has no DRBG (RDRAND et al.).
  • RNG_FAILURE_E The DRBG is out of service, or its hash failed mid-stir leaving a half-applied update – the instance is then condemned (status DRBG_FAILED).

function wc_RNG_lock_get

int wc_RNG_lock_get(
    WC_RNG * rng,
    WC_RNG_lock_arg_t extra_bits
)

Acquire rng's exclusive-ownership lock latch, spinning on the CAS until acquired, and or the caller's extra bits into the lock word. On an instance without the lock-required policy the call is a successful no-op unless extra bits are supplied.

Parameters:

  • rng The RNG object to lock.
  • extra_bits Caller-defined bits (above WC_RNG_LOCK_EXTRA_SHIFT) to set atomically with the acquisition, or 0.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • BUSY_E The lock is held.
  • NEEDS_RECOVERY_E The instance's entropy is invalidated (see wc_RNG_invalidate_entropy()); recover with a credited reseed before use.
  • BAD_MUTEX_E (WC_RNG_HAVE_LOCK_FULL_MUTEX) The outer mutex failed.
  • UNEXPECTED_STATE_E Spurious acquisition failure; retry.

Example

if (wc_RNG_lock_get(rng, 0) == 0) {
    ret = wc_RNG_GenerateBlock(rng, out, sizeof(out));
    wc_RNG_lock_put(rng, 0);
}

function wc_RNG_lock_get_conditional

int wc_RNG_lock_get_conditional(
    WC_RNG * rng,
    WC_RNG_lock_arg_t expected_extra_bits,
    WC_RNG_lock_arg_t want_extra_bits
)

The conditional form of wc_RNG_lock_get(): acquire only if the current extra bits equal expected_extra_bits, atomically replacing them with want_extra_bits on success. Non-blocking with respect to the condition: a mismatch fails immediately rather than spinning.

Parameters:

  • rng The RNG object to lock.
  • expected_extra_bits The extra bits required for acquisition.
  • want_extra_bits The extra bits to install on acquisition.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • BUSY_E The lock is held, or the extra bits do not match expected_extra_bits.
  • NEEDS_RECOVERY_E Entropy-invalidated and WC_RNG_LOCK_ENTROPY_INVALIDATED is not in expected_extra_bits.
  • BAD_MUTEX_E (WC_RNG_HAVE_LOCK_FULL_MUTEX) The outer mutex failed.
  • UNEXPECTED_STATE_E Spurious acquisition failure; retry.

function wc_RNG_lock_put

int wc_RNG_lock_put(
    WC_RNG * rng,
    WC_RNG_lock_arg_t extra_bits
)

Release rng's lock latch, clearing the supplied extra bits atomically with the release.

Parameters:

  • rng The RNG object to unlock.
  • extra_bits Caller-defined bits to clear with the release, or 0.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • OBJECT_NOT_LOCKED_E The latch is not held.
  • NEEDS_RECOVERY_E Released successfully; informational notice that the instance is entropy-invalidated.

function wc_RNG_lock_put_conditional

int wc_RNG_lock_put_conditional(
    WC_RNG * rng,
    WC_RNG_lock_arg_t expected_extra_bits,
    WC_RNG_lock_arg_t want_extra_bits
)

The conditional form of wc_RNG_lock_put(): release only if the current extra bits equal expected_extra_bits, atomically replacing them with want_extra_bits on success.

Parameters:

  • rng The RNG object to unlock.
  • expected_extra_bits The extra bits required for release.
  • want_extra_bits The extra bits to install on release.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.
  • BUSY_E The extra bits did not match expected_extra_bits.
  • OBJECT_NOT_LOCKED_E The latch is not held.
  • NEEDS_RECOVERY_E Released successfully; informational notice that the instance is entropy-invalidated.
  • UNEXPECTED_STATE_E Spurious release failure.

function wc_RNG_lock_read

int wc_RNG_lock_read(
    WC_RNG * rng,
    WC_RNG_lock_arg_t * state
)

Read rng's lock word: the held/required latch bits, the entropy-invalidated bit, and any caller extra bits. The snapshot is racy by design.

Parameters:

  • rng The RNG object to interrogate.
  • state Receives the lock word.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or state is null.

function wc_RNG_lock_set_extra

int wc_RNG_lock_set_extra(
    WC_RNG * rng,
    WC_RNG_lock_arg_t extra_bits
)

Atomically set (or) the supplied caller extra bits in rng's lock word. The caller should hold the latch.

Parameters:

  • rng The RNG object to modify.
  • extra_bits The bits to set.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.

function wc_RNG_lock_add_extra

int wc_RNG_lock_add_extra(
    WC_RNG * rng,
    WC_RNG_lock_arg_t extra_bits
)

Atomically add the supplied value to the caller extra-bits field of rng's lock word – for counters carried above WC_RNG_LOCK_EXTRA_SHIFT.

Parameters:

  • rng The RNG object to modify.
  • extra_bits The value to add.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.

function wc_RNG_lock_clear_extra

int wc_RNG_lock_clear_extra(
    WC_RNG * rng,
    WC_RNG_lock_arg_t extra_bits
)

Atomically clear the supplied caller extra bits in rng's lock word.

Parameters:

  • rng The RNG object to modify.
  • extra_bits The bits to clear.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null.

function wc_RNG_invalidate_entropy

int wc_RNG_invalidate_entropy(
    WC_RNG * rng
)

Mark rng's seed material untrusted – for VM fork/resume and similar duplication events – opening a new invalidation epoch: banked and pooled pre-event material is purged and wiped first, then the entropy-invalidated bit is latched in the lock word. An invalidated instance refuses service (NEEDS_RECOVERY_E) until recovery-reseeded. Latch or condemn: on any error return the latch is down, and the instance is instead condemned (status DRBG_FAILED). A condemned bank instance is retired and recovered by the entropy daemon; a condemned leaf gets no daemon rescue – its owner sees RNG_FAILURE_E from subsequent operations and recovers it with wc_FreeRng() then wc_InitRng*().

Parameters:

  • rng The RNG object to invalidate.

See:

Return:

  • 0 Success: purges complete, latch asserted.
  • BAD_FUNC_ARG rng is null.
  • RNG_FAILURE_E (or other nonzero) A purge or the latch failed; the instance is condemned as above.

Example

// VM-resume handler
(void)wc_RNG_invalidate_entropy(rng);
// subsequent wc_RNG_lock_get() returns NEEDS_RECOVERY_E until recovery

function wc_RNG_register_free_hook

int wc_RNG_register_free_hook(
    WC_RNG * rng,
    wc_RNG_free_hook_cb_t free_hook,
    void * arg
)

Register a callback fired by wc_FreeRng() at teardown – for external registries (e.g. a kernel_module registry that must reach every live RNG on a VM duplication event) that need to drop their reference when the object dies.

Parameters:

  • rng The RNG object to hook.
  • free_hook The callback.
  • arg Opaque argument passed to the callback.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or free_hook is null.

function wc_RNG_Pool_Alloc

int wc_RNG_Pool_Alloc(
    WC_RNG * rng,
    word32 size
)

Attach a random pool to rng: a buffer of size bytes of pre-generated output, filled by wc_RNG_Pool_Collect() and drained atomic-context-safely by wc_RNG_Pool_Extract(). The pool is released with the instance.

Parameters:

  • rng The RNG object to equip.
  • size Pool capacity in bytes.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null, or size is 0 or out of range.
  • MEMORY_E Allocation failed.
  • ALREADY_E The pool is already allocated.

Example

wc_RNG_Pool_Alloc(rng, 256);
wc_RNG_Pool_Collect(rng, 256);      // sleepable context
word32 n = 16;
if (wc_RNG_Pool_Extract(rng, out, &n) == 0) {
    // n bytes delivered, atomic-context-safe
}

function wc_RNG_Pool_Collect

int wc_RNG_Pool_Collect(
    WC_RNG * rng,
    word32 n
)

Generate up to n bytes into rng's pool from rng itself. The collect/extract hand-off is arbitrated by an atomic aperture word, so a single collector is safe alongside concurrent extractors.

Parameters:

  • rng The RNG object whose pool to fill.
  • n Maximum bytes to collect this call.

See:

Return:

  • 0 Success
  • ALREADY_E The pool is full or being drained.
  • BAD_FUNC_ARG rng is null, has no pool, or n is 0.

function wc_RNG_Pool_Collect2

int wc_RNG_Pool_Collect2(
    WC_RNG * rng_dest,
    WC_RNG * rng_src,
    word32 n
)

The two-instance form of wc_RNG_Pool_Collect(): fill rng_dest's pool with output drawn from rng_src – so a service instance's pool can be topped up by a daemon-owned generator.

Parameters:

  • rng_dest The RNG object whose pool to fill.
  • rng_src The RNG object to draw output from.
  • n Maximum bytes to collect this call.

See: wc_RNG_Pool_Collect

Return:

  • 0 Success
  • ALREADY_E The pool is full or being drained.
  • BAD_FUNC_ARG rng_dest or rng_src is null, or rng_dest has no pool, or n is 0.
  • BAD_STATE_E The pool is not allocated.
  • NOT_READY_E The source could not serve; retry later.

function wc_RNG_Pool_Extract

int wc_RNG_Pool_Extract(
    WC_RNG * rng,
    byte * out,
    word32 * n
)

Drain up to n bytes from rng's pool into out – atomic-context-safe. On success n reports the bytes actually delivered; on any error return *n is left unmodified.

Parameters:

  • rng The RNG object whose pool to drain.
  • out Receives the output.
  • n In: bytes requested; out: bytes delivered.

See:

Return:

  • 0 Success
  • NOT_READY_E The pool is empty or being filled.
  • BAD_FUNC_ARG rng, out, or n is null, or rng has no pool.
  • BAD_STATE_E The pool is not allocated.
  • RNG_FAILURE_E The instance is out of service.

function wc_RNG_Pool_Current

int wc_RNG_Pool_Current(
    WC_RNG * rng,
    word32 * n
)

Report the pool's current fill in bytes. The snapshot is racy by design.

Parameters:

  • rng The RNG object to interrogate.
  • n Receives the fill.

See: wc_RNG_Pool_Extract

Return:

  • 0 Success
  • BAD_FUNC_ARG rng or n is null, or rng has no pool.

function wc_rng_debug_stats_snap

int wc_rng_debug_stats_snap(
    struct wc_rng_debug_stats_snapshot * s,
    const WC_RNG * rng
)

Snapshot the global RNG debug counters (WC_RNG_DEBUG_STATS) – seeds and reseeds by provenance, generates, pool and bank traffic – into s, for later delta accounting with wc_rng_debug_stats_sum().

Parameters:

  • s Receives the snapshot.
  • rng Optional instance for per-instance context, or null.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG s is null.

function wc_rng_debug_stats_restore

int wc_rng_debug_stats_restore(
    const struct wc_rng_debug_stats_snapshot * s,
    WC_RNG * rng
)

Restore the global RNG debug counters from a snapshot – so a test can unwind its own accounting.

Parameters:

  • s The snapshot to restore from.
  • rng Optional instance for per-instance context, or null.

See: wc_rng_debug_stats_snap

Return:

  • 0 Success
  • BAD_FUNC_ARG s is null.

function wc_rng_debug_stats_sum

int wc_rng_debug_stats_sum(
    struct wc_rng_debug_stats_snapshot * s,
    const WC_RNG * rng
)

Accumulate the current global RNG debug counters into s – combined with a prior wc_rng_debug_stats_snap(), a delta accounting of the interval's RNG activity.

Parameters:

  • s The snapshot to accumulate into.
  • rng Optional instance for per-instance context, or null.

See: wc_rng_debug_stats_snap

Return:

  • 0 Success
  • BAD_FUNC_ARG s is null.

function wc_rng_bank_new

int wc_rng_bank_new(
    struct wc_rng_bank ** ctx,
    int n_rngs,
    word32 flags,
    int timeout_secs,
    void * heap,
    int devId
)

Allocate and initialize a bank of n_rngs pre-instantiated WC_RNG instances, checked out and back in by consumers (wc_rng_bank_checkout() et al.). The bank is allocated from heap; release with wc_rng_bank_free(). Bank-level flags (WC_RNG_BANK_FLAG_*) fix the bank's posture at initialization: e.g. _CAN_WAIT admits sleeping, _QUIET suppresses seeding-degradation warnings, _NO_CHECKOUT_REFCOUNTING suppresses per-checkout refcount traffic for container-guaranteed lifetimes, _PREDICTION_RESISTANCE imposes a bank-wide fresh-reseed posture on every sleepable lease.

Parameters:

  • ctx Receives the allocated bank.
  • n_rngs Number of instances.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* bank-posture flags.
  • timeout_secs Seeding timeout budget.
  • heap Heap hint for dynamic allocation.
  • devId Device id, or INVALID_DEVID.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx is null or n_rngs is out of range.
  • MEMORY_E Allocation failed.
  • RNG_FAILURE_E No instance could be seeded within timeout_secs.

Example

struct wc_rng_bank *bank = NULL;
if (wc_rng_bank_new(&bank, 4, WC_RNG_BANK_FLAG_CAN_WAIT, 10,
                    NULL, INVALID_DEVID) == 0) {
    // ... checkout/checkin traffic ...
    wc_rng_bank_free(&bank);
}

function wc_rng_bank_init

int wc_rng_bank_init(
    struct wc_rng_bank * ctx,
    int n_rngs,
    word32 flags,
    int timeout_secs,
    void * heap,
    int devId
)

Initialize a caller-provided bank object. Semantics of wc_rng_bank_new(), without the allocation; release with wc_rng_bank_fini().

Parameters:

  • ctx The bank object to initialize.
  • n_rngs Number of instances.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* bank-posture flags.
  • timeout_secs Seeding timeout budget.
  • heap Heap hint for dynamic allocation.
  • devId Device id, or INVALID_DEVID.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx is null or n_rngs is out of range.
  • BAD_LENGTH_E n_rngs exceeds the static capacity (WC_RNG_BANK_STATIC builds).
  • RNG_FAILURE_E No instance could be seeded within timeout_secs.

function wc_rng_bank_init_nonce

int wc_rng_bank_init_nonce(
    struct wc_rng_bank * ctx,
    int n_rngs,
    word32 flags,
    int timeout_secs,
    void * heap,
    int devId,
    const byte * nonce,
    word32 nonceSz,
    const byte * perso,
    word32 persoSz
)

The nonce-bearing form of wc_rng_bank_init(): the nonce is used as additional instantiation input for each instance.

Parameters:

  • ctx The bank object to initialize.
  • n_rngs Number of instances.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* bank-posture flags.
  • timeout_secs Seeding timeout budget.
  • heap Heap hint for dynamic allocation.
  • devId Device id, or INVALID_DEVID.
  • nonce Additional instantiation input.
  • nonceSz Length of nonce in bytes.
  • perso Optional personalization string (may be null).
  • persoSz Length of perso in bytes.

See: wc_rng_bank_init

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx is null, n_rngs is out of range, or nonce is null with nonceSz nonzero.
  • RNG_FAILURE_E No instance could be seeded within timeout_secs.
  • BAD_LENGTH_E nonceSz exceeds the supported maximum.
  • MEMORY_E Allocation failed.
  • WC_TIMEOUT_E Instance seeding exceeded timeout_secs.

function wc_rng_bank_first_failover_inst_set

int wc_rng_bank_first_failover_inst_set(
    struct wc_rng_bank * ctx,
    int first_failover_inst
)

Designate the first instance of the failover pool: checkouts without a targeted preference rotate through instances at and above first_failover_inst, reserving the lower offsets for targeted (affinity or daemon) use.

Parameters:

  • ctx The bank to configure.
  • first_failover_inst The first failover-eligible instance offset.

See: wc_rng_bank_checkout

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx is null or first_failover_inst is out of range.

function wc_rng_bank_set_affinity_handlers

int wc_rng_bank_set_affinity_handlers(
    struct wc_rng_bank * ctx,
    wc_affinity_lock_fn_t affinity_lock_cb,
    wc_affinity_get_id_fn_t affinity_get_id_cb,
    wc_affinity_unlock_fn_t affinity_unlock_cb,
    void * cb_arg
)

Install affinity handlers: callbacks that pin the caller to an execution context (e.g. disable preemption or migration), report its id for instance affinity, and unpin. With handlers installed, WC_RNG_BANK_FLAG_PREFER_AFFINITY_INST checkouts prefer the instance matching the caller's affinity id, and WC_RNG_BANK_FLAG_AFFINITY_LOCK holds the pin across the lease.

Parameters:

  • ctx The bank to configure.
  • affinity_lock_cb Pin the caller; may be null.
  • affinity_get_id_cb Report the caller's affinity id.
  • affinity_unlock_cb Unpin the caller; may be null.
  • cb_arg Opaque argument passed to the callbacks.

See: wc_rng_bank_checkout

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx is null.
  • BUSY_E The bank is in service; handlers must be set before use.

function wc_rng_bank_fini

int wc_rng_bank_fini(
    struct wc_rng_bank * ctx
)

Tear down a bank initialized with wc_rng_bank_init(): once the refcount and per-instance lease gates pass, fires any registered free hook and frees every instance. Never waits: a referenced or leased bank is refused with BUSY_E, and the caller quiesces its consumers and retries.

Parameters:

  • ctx The bank to tear down.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx is null.
  • BUSY_E The bank is still referenced, or an instance lease is outstanding.
  • BAD_STATE_E The refcount is below its initialization baseline (teardown of an uninitialized or corrupted bank).

function wc_rng_bank_free

int wc_rng_bank_free(
    struct wc_rng_bank ** ctx
)

Tear down and release a bank allocated with wc_rng_bank_new().

Parameters:

  • ctx The bank to release; nulled on success.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG ctx or *ctx is null.
  • BAD_STATE_E The bank is still referenced.

function wc_rng_bank_default_set

int wc_rng_bank_default_set(
    struct wc_rng_bank * bank
)

Register bank as the process-default bank, retrievable with wc_rng_bank_default_checkout().

Parameters:

  • bank The bank to register.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null.
  • BAD_STATE_E A default bank is already registered.
  • BUSY_E Registration is contended; retry.

function wc_rng_bank_default_checkout

int wc_rng_bank_default_checkout(
    struct wc_rng_bank ** bank
)

Take a reference on the process-default bank.

Parameters:

  • bank Receives the default bank.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null.
  • BAD_STATE_E No default bank is registered.
  • NO_DEFAULT_FOUND_E No default bank is registered.

function wc_rng_bank_default_checkin

int wc_rng_bank_default_checkin(
    struct wc_rng_bank ** bank
)

Release a reference taken with wc_rng_bank_default_checkout().

Parameters:

  • bank The reference to release; nulled on success.

See: wc_rng_bank_default_checkout

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or *bank is null.

function wc_rng_bank_default_clear

int wc_rng_bank_default_clear(
    struct wc_rng_bank * bank
)

Unregister the process-default bank.

Parameters:

  • bank The bank to unregister.

See: wc_rng_bank_default_set

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null or is not the registered default.
  • BUSY_E Unregistration is contended; retry.

function wc_rng_bank_checkout

int wc_rng_bank_checkout(
    struct wc_rng_bank * bank,
    struct wc_rng_bank_inst ** rng_inst,
    int preferred_inst_offset,
    int timeout_secs,
    word32 flags
)

Lease an in-service instance from the bank: either the preferred (or affinity-matched) instance, or – with WC_RNG_BANK_FLAG_CAN_FAIL_OVER_INST – the first available failover instance. On success the caller owns the instance's lock; access the WC_RNG with WC_RNG_BANK_INST_TO_RNG() and return the lease with wc_rng_bank_inst_checkin(). WC_RNG_BANK_FLAG_CONSUME_NEXT_SEED consumes a ready banked next seed in an immediate source-free credited reseed before returning; WC_RNG_BANK_FLAG_PREDICTION_RESISTANCE (per-call, requires _CAN_WAIT) freshly credited-reseeds the lease before the caller's first draw.

Parameters:

  • bank The bank to lease from.
  • rng_inst Receives the leased instance.
  • preferred_inst_offset The preferred instance, or 0.
  • timeout_secs Wait budget (with _CAN_WAIT).
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* per-call flags.

See:

Return:

  • 0 Success; *rng_inst holds the lease.
  • BAD_FUNC_ARG bank or rng_inst is null, or the flags are contradictory.
  • NEEDS_RECOVERY_E Quarantined: refused without a lease (ordinary checkout), or lease held with recovery owed (_MAYBE_FOR_RECOVERY; see
  • BAD_STATE_E (_ERROR_ON_RNG_FAILED) only out-of-service instances were found.
  • WC_TIMEOUT_E The wait budget expired.
  • RNG_FAILURE_E No serviceable instance.
  • BAD_INDEX_E preferred_inst_offset is out of range.
  • BUSY_E The selected instance is contended (without _CAN_WAIT).

Out-of-service instances: a targeted (non-failover) checkout admits them; failover checkouts divert around them. WC_RNG_BANK_FLAG_FOR_RECOVERY makes the targeted admission explicit and interaction-safe (recovery machinery and patrols): out-of-service status is expected, the _CONSUME_NEXT_SEED arm is suppressed (a consume would fail on exactly the instances recovery targets), and failover and affinity selection are rejected in combination. WC_RNG_BANK_FLAG_ERROR_ON_RNG_FAILED gives the opposite guarantee: either a lease on an in-service instance, or an error with no lease – never a lease on an out-of-service instance; under _CAN_WAIT an out-of-service instance is retried within the timeout budget (allowing a patrol to restore it), and the distinguished error for a lap or wait that found only out-of-service instances is BAD_STATE_E.

Entropy-invalidated (quarantined) instances refuse ordinary leases with NEEDS_RECOVERY_E, with two admissions. First, when the quarantined instance holds a READY banked next seed, any claimant is admitted and the consume-at-checkout reseed runs unconditionally: the invalidation purge guarantees READY banked material post-dates the invalidation event, so admitting the claimant is completing the recovery. Second, WC_RNG_BANK_FLAG_MAYBE_FOR_RECOVERY admits the caller to a quarantined instance with no banked material, transferring the recovery obligation: checkout then returns NEEDS_RECOVERY_E with the checkout otherwise complete – *rng_inst set; instance lock, affinity locks, and any vector-inhibit state held. This is the robust-mutex (EOWNERDEAD) pattern: an error return with the acquisition complete and persistent, because "this resource needs consistency recovery" is only safely reportable to a caller that already holds it. The caller must either recover the instance (a credited reseed, e.g. wc_RNG_DRBG_Reseed_Now(), clears the quarantine) or check it back in. Ordinary consumers that cannot complete a recovery must not pass this flag.

). Example

struct wc_rng_bank_inst *inst = NULL;
if (wc_rng_bank_checkout(bank, &inst, 0, 10,
                         WC_RNG_BANK_FLAG_CAN_WAIT |
                         WC_RNG_BANK_FLAG_CAN_FAIL_OVER_INST) == 0) {
    ret = wc_RNG_GenerateBlock(WC_RNG_BANK_INST_TO_RNG(inst),
                               out, sizeof(out));
    wc_rng_bank_inst_checkin(&inst);
}

function wc_rng_bank_checkin

int wc_rng_bank_checkin(
    struct wc_rng_bank * bank,
    struct wc_rng_bank_inst ** rng_inst
)

Return a lease through the bank object, validating that rng_inst belongs to bank. Prefer wc_rng_bank_inst_checkin() when only the instance pointer is at hand.

Parameters:

  • bank The bank the instance belongs to.
  • rng_inst The lease to return; nulled on success.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or rng_inst is null, or the instance does not belong to bank.
  • OBJECT_NOT_LOCKED_E The instance's lease is not held (e.g. a stale duplicate check-in).
  • NEEDS_RECOVERY_E Checked in successfully; informational notice that the instance is entropy-invalidated.

function wc_rng_bank_inst_checkin

int wc_rng_bank_inst_checkin(
    struct wc_rng_bank_inst ** rng_inst
)

Return a lease by instance pointer alone.

Parameters:

  • rng_inst The lease to return; nulled on success.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG rng_inst or *rng_inst is null.
  • OBJECT_NOT_LOCKED_E The instance's lease is not held.
  • NEEDS_RECOVERY_E Checked in successfully; informational notice that the instance is entropy-invalidated.

function wc_rng_bank_get_inst_id

int wc_rng_bank_get_inst_id(
    struct wc_rng_bank_inst * rng_inst
)

Report the instance's offset within its bank.

Parameters:

  • rng_inst The instance to interrogate.

See: wc_rng_bank_checkout

Return:

  • n The instance offset, non-negative.
  • BAD_FUNC_ARG rng_inst is null.

function wc_rng_bank_next_seed_generate

int wc_rng_bank_next_seed_generate(
    struct wc_rng_bank * bank,
    int inst_offset,
    word32 n
)

Bank next-seed material for the instance at inst_offset –wc_RNG_DRBG_NextSeedGenerate() through the bank, without taking the instance lock; the daemon-side serialization word arbitrates against concurrent whole-instance reinitialization.

Parameters:

  • bank The bank.
  • inst_offset The instance to bank for.
  • n Maximum bytes to bank this call.

See:

Return:

  • 0 Bytes were banked.
  • ALREADY_E The instance's bank is ready or being consumed.
  • NOT_READY_E The health test could not run; simply retry.
  • BAD_FUNC_ARG bank is null, inst_offset is out of range, or n is 0.

The daemon-side serialization word (not the instance lock) excludes a concurrent wc_rng_bank_inst_reinit() from freeing the DRBG out from under the gather; lease_holders never consult it, since instance_lock exclusion already covers every lease_holder interaction. The caller must hold a bank reference (e.g. per the daemon association) for the duration of the call. Return taxonomy for a banking rotation: BUSY_E, the gate is held by a reinit – skip this turn; ALREADY_E, sleep until the bank is consumed; MISSING_RNG_E, the instance has no DRBG (RDRAND et al.) and can be retired from the rotation permanently; other errors are transient gather or health-test failures – skip the turn, and alarm if persistent.

function wc_rng_bank_next_seed_generate_rbgc

int wc_rng_bank_next_seed_generate_rbgc(
    struct wc_rng_bank * bank,
    int inst_offset,
    word32 n
)

The chain-sourced form of wc_rng_bank_next_seed_generate(): the banked material is drawn from root's generate function and tagged with its provenance.

Parameters:

  • bank The bank.
  • inst_offset The instance to bank for.
  • n Maximum bytes to bank this call.

See:

Return:

  • 0 Bytes were banked.
  • ALREADY_E The instance's bank is ready or being consumed.
  • NOT_READY_E The health test could not run; simply retry.
  • BAD_FUNC_ARG bank or root is null, inst_offset is out of range, or n is 0.

function wc_rng_bank_inst_reinit

int wc_rng_bank_inst_reinit(
    struct wc_rng_bank * bank,
    struct wc_rng_bank_inst * rng_inst,
    int timeout_secs,
    word32 flags
)

Free and reinstantiate a leased instance in place. The caller must hold the lease; the daemon-side serialization word excludes concurrent lockless banking during the cycle.

Parameters:

  • bank The bank the instance belongs to.
  • rng_inst The leased instance to reinitialize.
  • timeout_secs Seeding timeout budget.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See: wc_rng_bank_recover_inst

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or rng_inst is null.
  • RNG_FAILURE_E Reinstantiation could not be seeded within timeout_secs.
  • BUSY_E The whole-instance-operation gate is held (daemon banking in progress); retry.

function wc_rng_bank_recover_inst

int wc_rng_bank_recover_inst(
    struct wc_rng_bank * bank,
    int inst_offset,
    int timeout_secs,
    word32 flags
)

Patrol helper: check out the instance at inst_offset with WC_RNG_BANK_FLAG_FOR_RECOVERY, recover it iff it needs recovery, and check it back in. Two recovery arms: an out-of-service instance (wc_RNG_GetStatus() != WC_DRBG_OK) is reinitialized in place; an in_service but entropy_invalidated (quarantined) instance takes one credited reseed, which clears the quarantine while preserving instance identity. A healthy instance is a success no-op, so callers can invoke this unconditionally on state observed locklessly.

Parameters:

  • bank The bank.
  • inst_offset The instance to patrol.
  • timeout_secs Seeding timeout budget.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See:

Return:

  • 0 Success (recovered, or nothing to recover).
  • BAD_FUNC_ARG bank is null, inst_offset is out of range, or the flags are contradictory.
  • RNG_FAILURE_E Recovery could not be seeded within timeout_secs.
  • BUSY_E The instance lock or whole-instance-operation gate is contended; retry on a later patrol turn.

Example

// after a VM duplication event has invalidated the bank:
for (i = 0; i < n_rngs; i++)
    (void)wc_rng_bank_recover_inst(bank, i, 10,
                                   WC_RNG_BANK_FLAG_CAN_WAIT);

A stale lockless status observation costs one harmless round trip. BUSY_E reports contention on the instance lock or the whole-instance-operation gate: retry on a later patrol turn. flags may include WC_RNG_BANK_FLAG_CAN_WAIT and WC_RNG_BANK_FLAG_AFFINITY_LOCK, which are passed through.

function wc_rng_bank_spawn

int wc_rng_bank_spawn(
    struct wc_rng_bank * bank,
    WC_RNG * child_rng,
    byte * nonce,
    word32 nonceSz,
    const byte * perso,
    word32 persoSz,
    int preferred_inst_offset,
    int timeout_secs,
    word32 flags
)

Spawn an SP 800-90C chain RNG from a bank instance: check out a parent instance (honoring the usual selection flags), instantiate child_rng as its chain child (wc_InitRngNonceRBGC()), and check the parent back in. The child's lifetime is thereafter decoupled from the parent and its bank; release it with wc_FreeRng() (or wc_rng_free() for the heap form, wc_rng_bank_spawn_new()). The child's RBGC stratum is one plus the parent's stratum at instantiation.

Parameters:

  • bank The bank to spawn from.
  • child_rng The caller-provided WC_RNG to instantiate.
  • nonce Optional additional instantiation input.
  • nonceSz Length of nonce in bytes.
  • perso Optional personalization string (may be null).
  • persoSz Length of perso in bytes.
  • preferred_inst_offset The preferred parent instance, or 0.
  • timeout_secs Wait budget (with _CAN_WAIT).
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* per-call flags.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or child_rng is null, or the flags are contradictory (uncredited or recovery seeding contradict a spawn).
  • RNG_FAILURE_E No serviceable parent within the timeout budget.

A recommended nonce, when available, is a racy read of a high-resolution timer (e.g. Linux kernel random_get_entropy()). WC_RNG_BANK_FLAG_CONSUME_NEXT_SEED composes: a ready banked seed is redeemed on the parent before the spawn draw. WC_RNG_BANK_FLAG_STIR and WC_RNG_BANK_FLAG_FOR_RECOVERY are rejected. WC_RNG_BANK_FLAG_ERROR_ON_RNG_FAILED is implied: the parent is guaranteed in-service, or an error is returned with no lease and no child.

function wc_rng_bank_spawn_new

int wc_rng_bank_spawn_new(
    struct wc_rng_bank * bank,
    WC_RNG ** child_rng,
    byte * nonce,
    word32 nonceSz,
    const byte * perso,
    word32 persoSz,
    int preferred_inst_offset,
    int timeout_secs,
    word32 flags
)

The allocating form of wc_rng_bank_spawn(): the child is allocated from the bank's heap and returned through child_rng; release with wc_rng_free().

Parameters:

  • bank The bank to spawn from.
  • child_rng Receives the allocated, instantiated WC_RNG.
  • nonce Optional additional instantiation input.
  • nonceSz Length of nonce in bytes.
  • perso Optional personalization string (may be null).
  • persoSz Length of perso in bytes.
  • preferred_inst_offset The preferred parent instance, or 0.
  • timeout_secs Wait budget (with _CAN_WAIT).
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* per-call flags.

See: wc_rng_bank_spawn

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or child_rng is null.
  • MEMORY_E Allocation failed.
  • RNG_FAILURE_E No serviceable parent within the timeout budget.

function wc_rng_bank_seed

int wc_rng_bank_seed(
    struct wc_rng_bank * bank,
    const byte * seed,
    word32 seedSz,
    const byte * nonce,
    word32 nonceSz,
    int timeout_secs,
    word32 flags
)

Reseed every instance with caller-supplied seed material. WC_RNG_BANK_FLAG_STIR mixes the material in without crediting it.

Parameters:

  • bank The bank to seed.
  • seed Seed material.
  • seedSz Length of seed in bytes.
  • nonce Optional per-instance nonce material (may be null).
  • nonceSz Length of nonce in bytes.
  • timeout_secs Wait budget per instance.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or seed is null.
  • RNG_FAILURE_E An instance could not be reseeded within timeout_secs.

function wc_rng_bank_seed_range

int wc_rng_bank_seed_range(
    struct wc_rng_bank * bank,
    int first_inst,
    int last_inst,
    const byte * seed,
    word32 seedSz,
    const byte * nonce,
    word32 nonceSz,
    int timeout_secs,
    word32 flags
)

The range form of wc_rng_bank_seed(): seed instances first_inst through last_inst inclusive.

Parameters:

  • bank The bank to seed.
  • first_inst The first instance offset.
  • last_inst The last instance offset.
  • seed Seed material.
  • seedSz Length of seed in bytes.
  • nonce Optional per-instance nonce material (may be null).
  • nonceSz Length of nonce in bytes.
  • timeout_secs Wait budget per instance.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See: wc_rng_bank_seed

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or seed is null, or the range is out of bounds.
  • RNG_FAILURE_E An instance could not be reseeded within timeout_secs.
  • BAD_INDEX_E The instance range is invalid.
  • BAD_STATE_E The bank is not initialized.
  • NO_DEFAULT_FOUND_E bank is null and no default bank is registered.

function wc_rng_bank_reseed

int wc_rng_bank_reseed(
    struct wc_rng_bank * bank,
    const byte * nonce,
    word32 nonceSz,
    int timeout_secs,
    word32 flags
)

Reseed every instance from the module's seed source.

Parameters:

  • bank The bank to reseed.
  • nonce Optional per-instance nonce material (may be null).
  • nonceSz Length of nonce in bytes.
  • timeout_secs Wait budget per instance.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null.
  • RNG_FAILURE_E An instance could not be reseeded within timeout_secs.

function wc_rng_bank_reseed_range

int wc_rng_bank_reseed_range(
    struct wc_rng_bank * bank,
    int first_inst,
    int last_inst,
    const byte * nonce,
    word32 nonceSz,
    int timeout_secs,
    word32 flags
)

The range form of wc_rng_bank_reseed().

Parameters:

  • bank The bank to reseed.
  • nonce Optional per-instance nonce material (may be null).
  • nonceSz Length of nonce in bytes.
  • first_inst The first instance offset.
  • last_inst The last instance offset.
  • timeout_secs Wait budget per instance.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See: wc_rng_bank_reseed

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null, or the range is out of bounds.
  • RNG_FAILURE_E An instance could not be reseeded within timeout_secs.
  • BAD_INDEX_E The instance range is invalid.
  • BAD_STATE_E The bank is not initialized.
  • WC_TIMEOUT_E The walk exceeded timeout_secs.

function wc_rng_bank_invalidate_entropy

int wc_rng_bank_invalidate_entropy(
    struct wc_rng_bank * bank,
    word32 flags
)

Set the entropy-invalidated latch on every instance (see wc_RNG_invalidate_entropy()): cached entropy products are discarded, and each instance is forced through a credited reseed before its next generate serves output. Lock_free and constant_time per instance; safe from a state_invalidation event context (VM fork/resume).

Parameters:

  • bank The bank to invalidate.
  • flags Bitwise-or of WC_RNG_BANK_FLAG_* flags.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null.
  • BAD_STATE_E The bank is not initialized.

Example

// VM-resume notifier
(void)wc_rng_bank_invalidate_entropy(bank, WC_RNG_BANK_FLAG_NONE);
// instances recover on next checkout, or by patrol:
//   wc_rng_bank_recover_inst()

Also purges each instance's banked next-seed apertures: the purge is the provenance guarantee that a READY bank observed after the event holds post-event material (see wc_rng_bank_checkout()'s recovery admissions). Walks every instance even on error, returning the first error. flags must be 0.

function wc_rng_bank_daemon_reserve

int wc_rng_bank_daemon_reserve(
    struct wc_rng_bank * bank,
    WC_ATOMIC_UINT_ARG magic
)

Reserve the bank's daemon slot with a caller-chosen nonzero magic word, admitting exactly one scheduling daemon per bank. The lifecycle is strictly ordered: _reserve, then _register, then _unregister, then _release.

Parameters:

  • bank The bank to claim.
  • magic The daemon's magic word.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null or magic is the free sentinel.
  • BUSY_E The slot is claimed, or claiming is contended.

function wc_rng_bank_daemon_register

int wc_rng_bank_daemon_register(
    struct wc_rng_bank * bank,
    void * daemon,
    WC_ATOMIC_UINT_ARG magic
)

Register the daemon object in a slot reserved with the same magic word.

Parameters:

  • bank The bank.
  • daemon The daemon object to register.
  • magic The daemon's magic word.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or daemon is null.
  • ALREADY_E The slot is already in the requested state.
  • WRONG_TYPE_OBJECT_E magic does not match the claim.
  • BUSY_E The slot transition is contended; retry.

function wc_rng_bank_daemon_unregister

int wc_rng_bank_daemon_unregister(
    struct wc_rng_bank * bank,
    void ** daemon,
    WC_ATOMIC_UINT_ARG magic
)

Unregister the daemon object, returning it through daemon.

Parameters:

  • bank The bank.
  • daemon Receives the registered daemon object.
  • magic The daemon's magic word.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or daemon is null.
  • ALREADY_E The slot is already in the requested state.
  • WRONG_TYPE_OBJECT_E magic does not match the claim.
  • BUSY_E The slot transition is contended; retry.

function wc_rng_bank_daemon_release

int wc_rng_bank_daemon_release(
    struct wc_rng_bank * bank,
    WC_ATOMIC_UINT_ARG magic
)

Release the daemon slot claimed with magic, returning it to the free sentinel.

Parameters:

  • bank The bank.
  • magic The daemon's magic word.

See: wc_rng_bank_daemon_reserve

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null.
  • ALREADY_E The slot is already in the requested state.
  • WRONG_TYPE_OBJECT_E magic does not match the claim.
  • BUSY_E The slot transition is contended; retry.

function wc_rng_bank_register_free_hook

int wc_rng_bank_register_free_hook(
    struct wc_rng_bank * bank,
    wc_rng_bank_free_hook_cb_t free_hook,
    void * arg
)

Register a callback fired by wc_rng_bank_fini() once its refcount and leak gates pass – i.e. once teardown is committed – for external registries that must drop their reference when the bank dies. One-shot: the hook is cleared before firing. A null free_hook unregisters.

Parameters:

  • bank The bank to hook.
  • free_hook The callback.
  • arg Opaque argument passed to the callback.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank is null.

function wc_InitRng_BankRef

int wc_InitRng_BankRef(
    struct wc_rng_bank * bank,
    WC_RNG * rng
)

Initialize rng as a bank reference: a WC_RNG with no DRBG of its own, whose wc_RNG_GenerateBlock() transparently checks an instance out of bank, generates, and checks it back in. Release with wc_FreeRng().

Parameters:

  • bank The bank to reference.
  • rng The WC_RNG to initialize as a reference.

See:

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or rng is null.

Example

WC_RNG rng;
if (wc_InitRng_BankRef(bank, &rng) == 0) {
    // rng now serves through the bank
    ret = wc_RNG_GenerateBlock(&rng, out, sizeof(out));
    wc_FreeRng(&rng);
}

function wc_BankRef_Release

int wc_BankRef_Release(
    WC_RNG * rng
)

Release a bank reference. wc_FreeRng() calls this automatically for bank references; direct use is rarely needed.

Parameters:

  • rng The bank reference to release.

See: wc_InitRng_BankRef

Return:

  • 0 Success
  • BAD_FUNC_ARG rng is null or is not a bank reference.

function wc_rng_new_bankref

int wc_rng_new_bankref(
    struct wc_rng_bank * bank,
    WC_RNG ** rng
)

The allocating form of wc_InitRng_BankRef(): the reference is allocated from the bank's heap; release with wc_rng_free().

Parameters:

  • bank The bank to reference.
  • rng Receives the allocated bank reference.

See: wc_InitRng_BankRef

Return:

  • 0 Success
  • BAD_FUNC_ARG bank or rng is null.
  • MEMORY_E Allocation failed.

function wc_rng_bank_debug_stats_snap

int wc_rng_bank_debug_stats_snap(
    struct wc_rng_debug_stats_snapshot * s,
    struct wc_rng_bank * bank
)

Snapshot the RNG debug counters (WC_RNG_DEBUG_STATS) with bank-level context.

Parameters:

  • s Receives the snapshot.
  • bank Optional bank for context, or null.

See: wc_rng_debug_stats_snap

Return:

  • 0 Success
  • BAD_FUNC_ARG s is null.

Updated on 2026-09-18 at 01:16:49 +0000