| 338 | } |
| 339 | |
| 340 | class RNGState { |
| 341 | Mutex m_mutex; |
| 342 | /* The RNG state consists of 256 bits of entropy, taken from the output of |
| 343 | * one operation's SHA512 output, and fed as input to the next one. |
| 344 | * Carrying 256 bits of entropy should be sufficient to guarantee |
| 345 | * unpredictability as long as any entropy source was ever unpredictable |
| 346 | * to an attacker. To protect against situations where an attacker might |
| 347 | * observe the RNG's state, fresh entropy is always mixed when |
| 348 | * GetStrongRandBytes is called. |
| 349 | */ |
| 350 | unsigned char m_state[32] GUARDED_BY(m_mutex) = {0}; |
| 351 | uint64_t m_counter GUARDED_BY(m_mutex) = 0; |
| 352 | bool m_strongly_seeded GUARDED_BY(m_mutex) = false; |
| 353 | |
| 354 | /** If not nullopt, the output of this RNGState is redirected and drawn from here |
| 355 | * (unless always_use_real_rng is passed to MixExtract). */ |
| 356 | std::optional<ChaCha20> m_deterministic_prng GUARDED_BY(m_mutex); |
| 357 | |
| 358 | Mutex m_events_mutex; |
| 359 | CSHA256 m_events_hasher GUARDED_BY(m_events_mutex); |
| 360 | |
| 361 | public: |
| 362 | RNGState() noexcept |
| 363 | { |
| 364 | InitHardwareRand(); |
| 365 | } |
| 366 | |
| 367 | ~RNGState() = default; |
| 368 | |
| 369 | void AddEvent(uint32_t event_info) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_events_mutex) |
| 370 | { |
| 371 | LOCK(m_events_mutex); |
| 372 | |
| 373 | m_events_hasher.Write((const unsigned char *)&event_info, sizeof(event_info)); |
| 374 | // Get the low four bytes of the performance counter. This translates to roughly the |
| 375 | // subsecond part. |
| 376 | uint32_t perfcounter = (GetPerformanceCounter() & 0xffffffff); |
| 377 | m_events_hasher.Write((const unsigned char*)&perfcounter, sizeof(perfcounter)); |
| 378 | } |
| 379 | |
| 380 | /** |
| 381 | * Feed (the hash of) all events added through AddEvent() to hasher. |
| 382 | */ |
| 383 | void SeedEvents(CSHA512& hasher) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_events_mutex) |
| 384 | { |
| 385 | // We use only SHA256 for the events hashing to get the ASM speedups we have for SHA256, |
| 386 | // since we want it to be fast as network peers may be able to trigger it repeatedly. |
| 387 | LOCK(m_events_mutex); |
| 388 | |
| 389 | unsigned char events_hash[32]; |
| 390 | m_events_hasher.Finalize(events_hash); |
| 391 | hasher.Write(events_hash, 32); |
| 392 | |
| 393 | // Re-initialize the hasher with the finalized state to use later. |
| 394 | m_events_hasher.Reset(); |
| 395 | m_events_hasher.Write(events_hash, 32); |
| 396 | } |
| 397 |
nothing calls this directly
no test coverage detected