Inside Bitcoin
Opening the selected file…
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) The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_UTIL_TOKENBUCKET_H6#define BITCOIN_UTIL_TOKENBUCKET_H8#include <util/time.h>10namespace util {12/** A token bucket rate limiter.13*14* Tokens are added at a steady rate (m_rate per second) up to a capacity15* cap (m_cap). Tokens are removed by calling decrement(), which returns16* false if the bucket is emptied.17*18* Typical usage:19* bucket.increment(now); // refill based on elapsed time20* if (bucket.value() >= 1) bucket.decrement(1); // consume a token21*/22template <typename Clock>23class TokenBucket24{25public:26using clock = Clock;27using time_point = typename Clock::time_point;28using duration = typename Clock::duration;30const double m_rate{1}; //!< Tokens added per second31const double m_cap{0}; //!< Maximum token balance33/** @param rate Tokens added per second.34* @param value Initial token balance (clamped to cap).35* @param cap Maximum token balance. */36TokenBucket(double rate, double value, double cap) : m_rate{rate}, m_cap{cap}, m_value{std::min(value, cap)} {}38/** Refill tokens based on elapsed time since last call. No refill39* occurs on the first call (establishes the time baseline). */40void increment(const time_point& now)41{42if (now > m_last_updated) {43if (m_value < m_cap && m_last_updated > MIN_TIME) {44double inc = m_rate * std::chrono::duration_cast<SecondsDouble>(now - m_last_updated).count();45m_value = std::min(m_cap, m_value + inc);46}47}48m_last_updated = now;49}51/** Consume n tokens. Returns false if the balance dropped to/below the given floor. */52bool decrement(double n = 1.0, double floor = 0.0)53{54m_value -= n;55return (m_value > floor);56}58/** Current token balance. */59double value() const { return m_value; }61private:62static constexpr time_point MIN_TIME{time_point::min()};63time_point m_last_updated{MIN_TIME};64double m_value{0};65};67} // namespace util69#endif // BITCOIN_UTIL_TOKENBUCKET_H