• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

libbitcoin / libbitcoin-network / 45495981786

24 Nov 2026 09:55PM UTC coverage: 94.028% (-0.2%) from 94.184%
45495981786

push

github

web-flow
Merge pull request #1062 from evoskuil/master

Regenerate artifacts.

16200 of 17229 relevant lines covered (94.03%)

2210.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.79
/src/net/proxy_queue.cpp
1
/**
2
 * Copyright (c) 2011-2026 libbitcoin developers
3
 *
4
 * This file is part of libbitcoin.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include <bitcoin/network/net/proxy.hpp>
20

21
#include <bitcoin/network/define.hpp>
22
#include <bitcoin/network/log/log.hpp>
23

24
// stackoverflow.com/questions/7754695/boost-asio-async-write-how-to-not-
25
// interleaving-async-write-calls
26

27
namespace libbitcoin {
28
namespace network {
29

30
// Shared pointers required in handler parameters so closures control lifetime.
31
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
32
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
33
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
34

35
using namespace std::placeholders;
36

37
// Send cycle (send continues until queue is empty).
38
// ----------------------------------------------------------------------------
39
// private
40

41
// Memory of queue entry apart from its payload: writer closure with
42
// its bound pointers, queue slot, control blocks and message
43
// object. Bounds queue depth implicitly, as flood of small messages
44
// is charged its estimated cost, not its smaller wire size.
45
constexpr size_t entry_size = 256;
46

47
// Charges the entry against the backlog, false if refused.
48
bool proxy::charge(pending& write_) NOEXCEPT
48 ✔
49
{
50
    BC_ASSERT(stranded());
48 ✔
51

52
    write_.cost = system::ceilinged_add(write_.cost, entry_size);
48 ✔
53

54
    const auto idle = queue_.empty() && deferred_.empty();
48 ✔
55
    if (!idle && system::ceilinged_add(backlog_, write_.cost) >
3 ✔
56
        maximum_backlog_)
3 ✔
57
    {
58
        // zeromq messages are sequenced, so drops are acceptable.
59
        if (socket_->zeromq())
2 ✔
60
        {
61
            LOGS("Dropped message on congested channel [" << endpoint() << "]");
1 ✔
62
            write_.handler(error::message_dropped, zero);
1 ✔
63
            return false;
1 ✔
64
        }
65

66
        LOGS("Stopping congested channel [" << endpoint() << "]");
1 ✔
67
        stop(error::channel_backlog);
1 ✔
68
        return false;
1 ✔
69
    }
70

71
    backlog_ = system::ceilinged_add(backlog_, write_.cost);
46 ✔
72
    return true;
46 ✔
73
}
74

75
// A bound entry is an lvalue, moved to the queue from its binding.
76
void proxy::do_write(pending& write_, bool notification) NOEXCEPT
489 ✔
77
{
78
    BC_ASSERT(stranded());
489 ✔
79

80
    if (stopped())
489 ✔
81
    {
82
        // Does not queue new work or invoke handler after stop.
83
        LOGQ("Payload write abort [" << endpoint() << "]");
1 ✔
84
        return;
1 ✔
85
    }
86

87
    // Solicited write (response) is paced by request that provoked it.
88
    // Notification must be charged as recipient can force accumulation.
89
    if (notification)
488 ✔
90
    {
91
        if (!charge(write_))
47 ✔
92
            return;
93
    }
94
    else
95
    {
96
        write_.cost = zero;
441 ✔
97
    }
98

99
    const auto started = !queue_.empty();
486 ✔
100
    queue_.push_back(std::move(write_));
486 ✔
101

102
    // Start the asynchronous loop if it wasn't already started.
103
    if (!started)
486 ✔
104
        write();
430 ✔
105
}
106

107
// A write invoked by a completion within the loop is invoked by the loop.
108
void proxy::write() NOEXCEPT
859 ✔
109
{
110
    BC_ASSERT(stranded());
859 ✔
111
    if (looping_)
859 ✔
112
    {
113
        again_ = true;
3 ✔
114
        return;
3 ✔
115
    }
116

117
    // Invokes oldest writer on queue, completion invokes
118
    // handle_write. Its writes are held for next writer while
119
    // another is queued, and held write completes on settle.
120
    looping_ = true;
856 ✔
121
    do
122
    {
123
        again_ = false;
859 ✔
124
        if (queue_.empty())
859 ✔
125
            break;
126

127
        writing_ = true;
486 ✔
128
        socket_->hold(queue_.size() > one);
486 ✔
129
        queue_.front().call();
486 ✔
130
        socket_->settle();
486 ✔
131
    }
132
    while (again_);
486 ✔
133
    looping_ = false;
856 ✔
134
}
135

136
void proxy::handle_write(const code& ec, size_t bytes) NOEXCEPT
486 ✔
137
{
138
    BC_ASSERT(stranded());
486 ✔
139
    if (queue_.empty())
486 ✔
140
        return;
×
141

142
    // The last queued writer releases any writes that remain held.
143
    if (!stopped() && is_one(queue_.size()) && socket_->holding())
486 ✔
144
    {
145
        socket_->release(std::bind(&proxy::handle_write,
×
146
            shared_from_this(), ec, bytes));
×
147
        return;
×
148
    }
149

150
    // Handler precedes pop so handler send does not start second write loop
151
    // (non-empty queue defers start to pop below).
152
    const auto handler = std::move(queue_.front().handler);
486 ✔
153
    handler(ec, bytes);
486 ✔
154
    backlog_ = system::floored_subtract(backlog_, queue_.front().cost);
486 ✔
155
    queue_.pop_front();
486 ✔
156

157
    // All handlers must be invoked unless stopped, so continue despite code.
158
    if (!stopped())
486 ✔
159
        write();
429 ✔
160
}
486 ✔
161

162
// Throttle (sent bytes are allocated time at the configured rate).
163
// ----------------------------------------------------------------------------
164
// private
165
// Applied to every send, so deferral delays next queued write.
166

167
// Nanoseconds allocated to the transmission of bytes at the given rate.
168
inline steady_clock::duration to_allocation(size_t bytes,
4 ✔
169
    uint32_t rate) NOEXCEPT
170
{
171
    using namespace system;
172
    constexpr auto nanos = 1'000'000'000_u64;
173

174
    // Overflow implies an unusable rate/size, saturated at the type maximum.
175
    const auto span = ceilinged_multiply<uint64_t>(bytes, nanos) / rate;
4 ✔
176
    return nanoseconds{ limit<nanoseconds::rep>(span) };
4 ✔
177
}
178

179
count_handler proxy::counted(count_handler&& handler) NOEXCEPT
391 ✔
180
{
181
    return std::bind(&proxy::handle_counted,
782 ✔
182
        shared_from_this(), _1, _2, std::move(handler));
1,173 ✔
183
}
184

185
void proxy::count_received(size_t bytes) NOEXCEPT
560 ✔
186
{
187
    received_ = system::ceilinged_add(received_.load(), bytes);
560 ✔
188
}
560 ✔
189

190
void proxy::handle_counted(const code& ec, size_t bytes,
391 ✔
191
    const count_handler& handler) NOEXCEPT
192
{
193
    count_received(bytes);
391 ✔
194
    handler(ec, bytes);
391 ✔
195
}
391 ✔
196

197
count_handler proxy::metered(count_handler&& handler) NOEXCEPT
491 ✔
198
{
199
    // Stamped at issue, so only transmission time is credited against
200
    // allocation. Time spent idle between sends earns nothing.
201
    return std::bind(&proxy::handle_metered,
982 ✔
202
        shared_from_this(), _1, _2, steady_clock::now(), std::move(handler));
1,473 ✔
203
}
204

205
steady_clock::duration proxy::unconsumed(size_t bytes,
496 ✔
206
    const steady_clock::time_point& start) const NOEXCEPT
207
{
208
    BC_ASSERT(stranded());
496 ✔
209

210
    // Stop is never deferred, and a null throttle implies no rate limit.
211
    if (!throttle_ || stopped())
496 ✔
212
        return {};
492 ✔
213

214
    const auto allocated = to_allocation(bytes, rate_limit_);
4 ✔
215
    const auto consumed = steady_clock::now() - start;
4 ✔
216
    return consumed < allocated ? allocated - consumed :
4 ✔
217
        steady_clock::duration{};
1 ✔
218
}
219

220
void proxy::handle_metered(const code& ec, size_t bytes,
491 ✔
221
    const steady_clock::time_point& start,
222
    const count_handler& handler) NOEXCEPT
223
{
224
    BC_ASSERT(stranded());
491 ✔
225
    sent_ = system::ceilinged_add(sent_.load(), bytes);
982 ✔
226
    writing();
491 ✔
227
    writing_ = false;
491 ✔
228

229
    // A send that consumed its full allocation is not deferred.
230
    const auto delay = unconsumed(bytes, start);
491 ✔
231
    if (is_zero(delay.count()))
491 ✔
232
    {
233
        handler(ec, bytes);
490 ✔
234
        return;
490 ✔
235
    }
236

237
    // Handler is posted to the strand, and fired by stop (canceled).
238
    throttle_->start(std::bind(&proxy::handle_charge,
1 ✔
239
        shared_from_this(), _1, ec, bytes, handler), delay);
2 ✔
240
}
241

242
void proxy::handle_charge(const code&, const code& ec, size_t bytes,
1 ✔
243
    const count_handler& handler) NOEXCEPT
244
{
245
    BC_ASSERT(stranded());
1 ✔
246

247
    // The timer code is discarded, as the send result is what is reported.
248
    handler(ec, bytes);
1 ✔
249
}
1 ✔
250

251
BC_POP_WARNING()
252
BC_POP_WARNING()
253
BC_POP_WARNING()
254

255
} // namespace network
256
} // namespace libbitcoin
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc