Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2011 The LevelDB Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file. See the AUTHORS file for names of contributors.5#ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_6#define STORAGE_LEVELDB_UTIL_RANDOM_H_8#include <stdint.h>10namespace leveldb {12// A very simple random number generator. Not especially good at13// generating truly random bits, but good enough for our needs in this14// package.15class Random {16private:17uint32_t seed_;19public:20explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) {21// Avoid bad seeds.22if (seed_ == 0 || seed_ == 2147483647L) {23seed_ = 1;24}25}26uint32_t Next() {27static const uint32_t M = 2147483647L; // 2^31-128static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 029// We are computing30// seed_ = (seed_ * A) % M, where M = 2^31-131//32// seed_ must not be zero or M, or else all subsequent computed values33// will be zero or M respectively. For all other values, seed_ will end34// up cycling through every number in [1,M-1]35uint64_t product = seed_ * A;37// Compute (product % M) using the fact that ((x << 31) % M) == x.38seed_ = static_cast<uint32_t>((product >> 31) + (product & M));39// The first reduction may overflow by 1 bit, so we may need to40// repeat. mod == M is not possible; using > allows the faster41// sign-bit-based test.42if (seed_ > M) {43seed_ -= M;44}45return seed_;46}47// Returns a uniformly distributed value in the range [0..n-1]48// REQUIRES: n > 049uint32_t Uniform(int n) { return Next() % n; }51// Randomly returns true ~"1/n" of the time, and false otherwise.52// REQUIRES: n > 053bool OneIn(int n) { return (Next() % n) == 0; }55// Skewed: pick "base" uniformly from range [0,max_log] and then56// return "base" random bits. The effect is to pick a number in the57// range [0,2^max_log-1] with exponential bias towards smaller numbers.58uint32_t Skewed(int max_log) { return Uniform(1 << Uniform(max_log + 1)); }59};61} // namespace leveldb63#endif // STORAGE_LEVELDB_UTIL_RANDOM_H_
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.