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

libbitcoin / libbitcoin-network / 44830417874

20 Nov 2026 10:36PM UTC coverage: 94.07% (-0.02%) from 94.093%
44830417874

push

github

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

Add the manual request_mempool setting.

16132 of 17149 relevant lines covered (94.07%)

2235.35 hits per line

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

90.55
/src/net/socket_ws.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/socket.hpp>
20

21
#include <bitcoin/network/define.hpp>
22
#include <bitcoin/network/log/log.hpp>
23
#include <bitcoin/network/settings.hpp>
24
#include <bitcoin/network/ws/ws.hpp>
25

26
namespace libbitcoin {
27
namespace network {
28

29
using namespace system;
30
using namespace std::placeholders;
31

32
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
33
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
34

35
// WS (read).
36
// ----------------------------------------------------------------------------
37
// The flat_buffer's max_size() must be large enough to hold the complete ws
38
// framed message. The read will fail if the message exceeds this limit.
39

40
void socket::ws_read(http::flat_buffer& out,
5 ✔
41
    count_handler&& handler) NOEXCEPT
42
{
43
    io::dispatch(strand_,
5 ✔
44
        std::bind(&socket::do_ws_read,
10 ✔
45
            shared_from_this(), std::ref(out), std::move(handler)));
10 ✔
46
}
5 ✔
47

48
// private
49
void socket::do_ws_read(ref<http::flat_buffer> out,
5 ✔
50
    const count_handler& handler) NOEXCEPT
51
{
52
    BC_ASSERT(stranded());
5 ✔
53
    async_read(out.get(), handler);
5 ✔
54
}
5 ✔
55

56
// WS (write).
57
// ----------------------------------------------------------------------------
58

59
void socket::ws_write(const io::const_buffer& in, bool binary,
125 ✔
60
    count_handler&& handler) NOEXCEPT
61
{
62
    io::dispatch(strand_,
125 ✔
63
        std::bind(&socket::do_ws_write,
250 ✔
64
            shared_from_this(), in, binary, std::move(handler)));
250 ✔
65
}
125 ✔
66

67
// private
68
void socket::do_ws_write(const io::const_buffer& in, bool binary,
125 ✔
69
    const count_handler& handler) NOEXCEPT
70
{
71
    BC_ASSERT(stranded());
125 ✔
72
    async_write(in, binary, true, handler);
125 ✔
73
}
125 ✔
74

75
// WS (upgrade).
76
// ----------------------------------------------------------------------------
77

78
// The response is written before the upgrade (or refusal) is returned.
79
code socket::accept_websocket(const http::request& request) NOEXCEPT
27 ✔
80
{
81
    BC_ASSERT(stranded());
27 ✔
82
    BC_ASSERT(!websocket());
27 ✔
83

84
    ws::response response{};
27 ✔
85
    const auto ec = ws::accept(response, request.base());
27 ✔
86
    response.set(http::field::server, BC_HTTP_SERVER_NAME);
27 ✔
87

88
    http::serializer<false, http::string_body> serializer{ response };
27 ✔
89
    data_chunk bytes{};
27 ✔
90
    code error{};
27 ✔
91
    while (!serializer.is_done() && !error)
54 ✔
92
        for (const auto& buffer: serializer.next(error))
57 ✔
93
            bytes.insert(bytes.end(), pointer_cast<const uint8_t>(
30 ✔
94
                buffer.data()), std::next(pointer_cast<const uint8_t>(
95
                    buffer.data()), buffer.size()));
57 ✔
96

97
    VARIANT_DISPATCH_FUNCTION(io::write, get_tcp(),
54 ✔
98
        io::buffer(bytes), error);
99

100
    if (error || ec)
27 ✔
101
        return error::operation_failed;
3 ✔
102

103
    ws_reader_.emplace(maximum_, true);
24 ✔
104
    ws_input_.clear();
24 ✔
105
    ws_continuing_ = false;
24 ✔
106
    ws_closing_ = false;
24 ✔
107
    websocket_.store(true);
24 ✔
108
    return error::success;
24 ✔
109
}
27 ✔
110

111
// WS (framing).
112
// ----------------------------------------------------------------------------
113
// A read assembles one data message, answering pings and the peer's close.
114
// Frames are written in order, so control frames queue behind data frames.
115

116
// private
117
void socket::do_ws_read_message(const ref<http::flat_buffer>& out,
24 ✔
118
    const count_handler& handler) NOEXCEPT
119
{
120
    BC_ASSERT(stranded());
24 ✔
121

122
    while (true)
123
    {
124
        ws::reader::event event{};
26 ✔
125
        code ec{};
26 ✔
126
        const auto data = ws_input_.data();
26 ✔
127
        const std::span<const uint8_t> bytes{ pointer_cast<const uint8_t>(
128
            data.data()), data.size() };
26 ✔
129

130
        const auto used = ws_reader_->put(bytes, out.get(), event, ec);
26 ✔
131
        ws_input_.consume(used);
26 ✔
132

133
        if (ec == error::need_more)
26 ✔
134
            break;
135

136
        if (ec)
13 ✔
137
        {
138
            handler(ec, out.get().size());
×
139
            return;
11 ✔
140
        }
141

142
        const auto& payload = ws_reader_->control();
13 ✔
143
        switch (event)
13 ✔
144
        {
145
            case ws::reader::event::message:
10 ✔
146
                handler(error::success, out.get().size());
10 ✔
147
                return;
10 ✔
148
            case ws::reader::event::ping:
1 ✔
149
                do_ws_event(ws::opcode::ping, payload);
1 ✔
150
                ws_pong(payload);
1 ✔
151
                continue;
3 ✔
152
            case ws::reader::event::pong:
1 ✔
153
                do_ws_event(ws::opcode::pong, payload);
1 ✔
154
                continue;
1 ✔
155
            case ws::reader::event::close:
1 ✔
156
            {
157
                do_ws_event(ws::opcode::close, payload);
1 ✔
158
                if (ws_closing_)
1 ✔
159
                {
160
                    handler(error::websocket_closed, out.get().size());
×
161
                    return;
×
162
                }
163

164
                // The close is answered with the peer's close code.
165
                ws_closing_ = true;
1 ✔
166
                const auto echo = payload.size() < two ? data_chunk{} :
1 ✔
167
                    data_chunk{ payload.begin(), std::next(payload.begin(),
1 ✔
168
                        two) };
1 ✔
169

170
                ws_send(ws::opcode::close, echo,
1 ✔
171
                    std::bind(&socket::handle_ws_echo,
2 ✔
172
                        shared_from_this(), _1, _2, out, handler));
2 ✔
173
                return;
174
            }
1 ✔
175
            case ws::reader::event::none:
×
176
            default:
177
                continue;
×
178
        }
2 ✔
179
    }
2 ✔
180

181
    const auto limit = floored_subtract(ws_input_.max_size(),
13 ✔
182
        ws_input_.size());
13 ✔
183
    const auto size = std::min(limit, std::max(ws_input_.capacity() -
26 ✔
184
        ws_input_.size(), header_));
13 ✔
185

186
    try
187
    {
188
        VARIANT_DISPATCH_METHOD(get_tcp(),
26 ✔
189
            async_read_some(ws_input_.prepare(size),
190
                std::bind(&socket::handle_ws_read_message,
191
                    shared_from_this(), _1, _2, out, handler)));
192
    }
193
    catch (const std::exception& e)
×
194
    {
195
        LOGF("Exception @ ws_read: " << e.what());
×
196
        handler(error::operation_failed, {});
×
197
    }
×
198
}
199

200
// private
201
void socket::handle_ws_read_message(const code& ec, size_t size,
13 ✔
202
    const ref<http::flat_buffer>& out, const count_handler& handler) NOEXCEPT
203
{
204
    BC_ASSERT(stranded());
13 ✔
205

206
    if (ec == error::operation_canceled)
13 ✔
207
    {
208
        handler(error::channel_stopped, out.get().size());
×
209
        return;
×
210
    }
211

212
    if (ec)
13 ✔
213
    {
214
        if (ec == error::unknown) logx("ws-read", ec);
×
215
        handler(ec, out.get().size());
×
216
        return;
×
217
    }
218

219
    ws_input_.commit(size);
13 ✔
220
    do_ws_read_message(out, handler);
13 ✔
221
}
222

223
// private
224
// The server closes the connection once the closing handshake is complete.
225
void socket::handle_ws_echo(const code&, size_t,
1 ✔
226
    const ref<http::flat_buffer>& out, const count_handler& handler) NOEXCEPT
227
{
228
    BC_ASSERT(stranded());
1 ✔
229

230
    code ignore{};
1 ✔
231
    get_base().shutdown(io::socket::shutdown_type::send, ignore);
1 ✔
232
    handler(error::websocket_closed, out.get().size());
1 ✔
233
}
1 ✔
234

235
// private
236
// A data frame continues the message of a preceding unfinished frame.
237
void socket::ws_send_data(const io::const_buffer& data, bool binary,
133 ✔
238
    bool finish, const count_handler& handler) NOEXCEPT
239
{
240
    BC_ASSERT(stranded());
133 ✔
241

242
    const auto code = ws_continuing_ ? ws::opcode::continuation :
133 ✔
243
        (binary ? ws::opcode::binary : ws::opcode::text);
8 ✔
244

245
    ws_continuing_ = !finish;
133 ✔
246
    const auto frame = emplace_shared<ws_frame>();
133 ✔
247
    frame->header = ws::serialize_header(code, finish,
266 ✔
248
        possible_wide_cast<uint64_t>(data.size()));
133 ✔
249
    frame->data = data;
133 ✔
250
    frame->handler = handler;
133 ✔
251
    frame->finish = finish;
133 ✔
252
    ws_queue_.push_back(frame);
133 ✔
253
    ws_write_next();
133 ✔
254
}
133 ✔
255

256
// private
257
void socket::ws_send(ws::opcode code, const data_chunk& payload,
3 ✔
258
    const count_handler& handler) NOEXCEPT
259
{
260
    BC_ASSERT(stranded());
3 ✔
261

262
    const auto frame = emplace_shared<ws_frame>();
3 ✔
263
    frame->header = ws::serialize_header(code, true,
6 ✔
264
        possible_wide_cast<uint64_t>(payload.size()));
3 ✔
265
    frame->payload = payload;
3 ✔
266
    frame->handler = handler;
3 ✔
267
    frame->control = true;
3 ✔
268
    ws_queue_.push_back(frame);
3 ✔
269
    ws_write_next();
3 ✔
270
}
3 ✔
271

272
// private
273
// An unsent pong answers only the most recent ping (rfc6455 5.5.3).
274
void socket::ws_pong(const data_chunk& payload) NOEXCEPT
1 ✔
275
{
276
    BC_ASSERT(stranded());
1 ✔
277

278
    const auto queued = !is_null(ws_pong_);
1 ✔
279
    if (!queued)
1 ✔
280
    {
281
        ws_pong_ = emplace_shared<ws_frame>();
1 ✔
282
        ws_pong_->control = true;
1 ✔
283
    }
284

285
    ws_pong_->header = ws::serialize_header(ws::opcode::pong, true,
2 ✔
286
        possible_wide_cast<uint64_t>(payload.size()));
1 ✔
287
    ws_pong_->payload = payload;
1 ✔
288

289
    if (!queued)
1 ✔
290
    {
291
        ws_queue_.push_back(ws_pong_);
1 ✔
292
        ws_write_next();
1 ✔
293
    }
294
}
1 ✔
295

296
// private
297
void socket::ws_write_next() NOEXCEPT
274 ✔
298
{
299
    BC_ASSERT(stranded());
274 ✔
300

301
    if (ws_writing_ || ws_queue_.empty())
274 ✔
302
        return;
137 ✔
303

304
    ws_writing_ = true;
137 ✔
305
    const auto frame = ws_queue_.front();
137 ✔
306
    if (frame == ws_pong_)
137 ✔
307
        ws_pong_.reset();
1 ✔
308
    const auto payload = frame->payload.empty() ? frame->data :
137 ✔
309
        io::const_buffer{ frame->payload.data(), frame->payload.size() };
137 ✔
310

311
    frame->buffers =
274 ✔
312
    {
313
        io::const_buffer{ frame->header.data(), frame->header.size() },
137 ✔
314
        payload
315
    };
316

317
    const count_handler complete = std::bind(&socket::handle_ws_frame,
274 ✔
318
        shared_from_this(), _1, _2, frame);
411 ✔
319

320
    if (frame->control)
137 ✔
321
        interject(frame->buffers, complete);
4 ✔
322
    else
323
        transmit(frame->buffers, frame->finish, complete);
133 ✔
324
}
137 ✔
325

326
// private
327
void socket::handle_ws_frame(const code& ec, size_t,
137 ✔
328
    const ws_frame::ptr& frame) NOEXCEPT
329
{
330
    BC_ASSERT(stranded());
137 ✔
331

332
    ws_writing_ = false;
137 ✔
333
    ws_queue_.pop_front();
137 ✔
334
    const auto code = (ec == error::operation_canceled) ? error::channel_stopped :
137 ✔
335
        ec;
137 ✔
336

337
    if (code == error::unknown)
137 ✔
338
        logx("ws-write", ec);
×
339

340
    // A failed write fails the frames that follow it. These are removed before
341
    // any handler runs, as a handler may queue (and write) another frame.
342
    std::deque<ws_frame::ptr> failed{};
137 ✔
343
    if (code)
137 ✔
344
    {
345
        ws_pong_.reset();
×
346
        std::swap(failed, ws_queue_);
×
347
    }
348

349
    // The payload size is reported (as with stream writes).
350
    const auto size = frame->payload.empty() ? frame->data.size() :
137 ✔
351
        frame->payload.size();
4 ✔
352

353
    if (frame->handler)
137 ✔
354
        frame->handler(code, size);
136 ✔
355

356
    for (const auto& next: failed)
137 ✔
357
        if (next->handler)
×
358
            next->handler(code, zero);
×
359

360
    if (!code)
137 ✔
361
        ws_write_next();
137 ✔
362
}
137 ✔
363

364
// WS (events).
365
// ----------------------------------------------------------------------------
366

367
// private
368
void socket::do_ws_event(ws::opcode kind, const data_chunk& data) NOEXCEPT
3 ✔
369
{
370
    BC_ASSERT(stranded());
3 ✔
371

372
    switch (kind)
3 ✔
373
    {
374
        case ws::opcode::ping:
1 ✔
375
            LOGX("WS ping [" << endpoint() << "] size: " << data.size());
1 ✔
376
            break;
377
        case ws::opcode::pong:
1 ✔
378
            LOGX("WS pong [" << endpoint() << "] size: " << data.size());
1 ✔
379
            break;
380
        case ws::opcode::close:
1 ✔
381
        {
382
            uint16_t value{};
1 ✔
383
            std::string reason{};
1 ✔
384
            code ignore{};
1 ✔
385
            ws::parse_close(value, reason, data, ignore);
1 ✔
386
            LOGX("WS close [" << endpoint() << "] " << value << " "
1 ✔
387
                << reason);
388
            break;
389
        }
1 ✔
390
        default:
391
            break;
392
    }
393
}
3 ✔
394

395
BC_POP_WARNING()
396
BC_POP_WARNING()
397

398
} // namespace network
399
} // 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