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

libbitcoin / libbitcoin-server / 46108256844

28 Nov 2026 04:35AM UTC coverage: 93.413% (-0.4%) from 93.797%
46108256844

push

github

web-flow
Merge pull request #1244 from echennells/fix/sv2-max-target

Bound the stratum v2 target by the channel max_target.

18 of 18 new or added lines in 2 files covered. (100.0%)

114 existing lines in 5 files now uncovered.

15614 of 16715 relevant lines covered (93.41%)

446.52 hits per line

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

56.16
/src/protocols/admin/protocol_admin.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/server/protocols/protocol_admin.hpp>
20

21
#include <atomic>
22
#include <chrono>
23
#include <bitcoin/server/define.hpp>
24
#include <bitcoin/server/parsers/parsers.hpp>
25
#include <bitcoin/server/serializers/serializers.hpp>
26
#include <bitcoin/server/utilities/utilities.hpp>
27

28
namespace libbitcoin {
29
namespace server {
30

31
using namespace system;
32
using namespace network;
33
using namespace network::http;
34
using namespace std::placeholders;
35
constexpr auto relaxed = std::memory_order_relaxed;
36

37
#define CLASS protocol_admin
38
#define SUBSCRIBE_ADMIN(method, ...) \
39
    subscribe<CLASS>(&CLASS::method, __VA_ARGS__)
40

41
// Limited by json number domain and sentinel bit.
42
static_assert(node::events::unknown < 53u);
43
static_assert(network::levels::verbose < 53u);
44

45
// Start.
46
// ----------------------------------------------------------------------------
47

48
void protocol_admin::start() NOEXCEPT
34 ✔
49
{
50
    BC_ASSERT(stranded());
34 ✔
51

52
    if (started())
34 ✔
53
        return;
54

55
    // Subscription methods.
56
    SUBSCRIBE_ADMIN(handle_get_log_subscribe, _1, _2, _3, _4);
34 ✔
57
    SUBSCRIBE_ADMIN(handle_get_event_subscribe, _1, _2, _3, _4);
34 ✔
58
    SUBSCRIBE_ADMIN(handle_get_mining, _1, _2, _3);
34 ✔
59
    SUBSCRIBE_ADMIN(handle_get_mining_subscribe, _1, _2, _3);
34 ✔
60
    protocol_native::start();
34 ✔
61
}
62

63
void protocol_admin::stopping(const code& ec) NOEXCEPT
34 ✔
64
{
65
    BC_ASSERT(stranded());
34 ✔
66
    log_interest_->set(zero);
34 ✔
67
    mining_timer_->stop();
34 ✔
68
    admin_dispatcher_.stop(ec);
34 ✔
69
    protocol_native::stopping(ec);
34 ✔
70
}
34 ✔
71

72
// Dispatch.
73
// ----------------------------------------------------------------------------
74

75
bool protocol_admin::try_dispatch_object(const http::request& request) NOEXCEPT
22 ✔
76
{
77
    BC_ASSERT(stranded());
22 ✔
78

79
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
80
    const auto target = request.target();
22 ✔
81
    BC_POP_WARNING()
82

83
    rpc::request_t model{};
22 ✔
84
    if (const auto ec = admin_target(model, target))
22 ✔
85
    {
86
        // An unrecognized admin target may be a native interface request.
87
        if (ec == error::invalid_target)
6 ✔
88
            return protocol_native::try_dispatch_object(request);
6 ✔
89

90
        // A target without a version or requesting html is a page request.
91
        if (ec == error::missing_version || ec == error::empty_path ||
2 ✔
92
            is_page_request(request))
1 ✔
UNCOV
93
            return false;
×
94

95
        send_bad_target(ec, *reset_request());
1 ✔
96
        return true;
1 ✔
97
    }
98

99
    // No media defaults injected for an http request.
100
    if (!admin_query(model, request))
16 ✔
101
    {
102
        send_bad_request();
4 ✔
103
        return true;
104
    }
105

106
    const auto media = strip_media(model);
12 ✔
107
    if (media == media_type::unknown)
12 ✔
108
    {
109
        send_not_acceptable();
1 ✔
110
        return true;
111
    }
112

113
    // Falls through to html page dispatch.
114
    if (media == media_type::text_html)
11 ✔
115
        return false;
116

117
    // The credential may be restricted to a subset of interface methods.
118
    if (!permitted(model.method))
10 ✔
119
    {
120
        send_forbidden();
1 ✔
121
        return true;
122
    }
123

124
    if (admin_dispatcher_.notify(model))
9 ✔
UNCOV
125
        send_bad_request();
×
126

127
    return true;
128
}
22 ✔
129

130
void protocol_admin::dispatch_websocket(const http::request& request) NOEXCEPT
20 ✔
131
{
132
    BC_ASSERT(stranded());
20 ✔
133

134
    // ws frames carry no headers, so ws authorization is enforced here, not by
135
    // channel (established by basic auth on upgrade request).
136
    if (!authorized())
20 ✔
137
    {
UNCOV
138
        send_unauthorized(request);
×
139
        return;
6 ✔
140
    }
141

142
    // Admin websocket interface supports only string requests.
143
    if (!request.body().contains<http::string_value>())
20 ✔
144
    {
UNCOV
145
        send_not_acceptable(request);
×
UNCOV
146
        return;
×
147
    }
148

149
    // Target with query string is passed via websocket string body.
150
    const auto target = request.body().get<http::string_value>();
20 ✔
151

152
    rpc::request_t model{};
20 ✔
153
    if (const auto ec = admin_target(model, target))
20 ✔
154
    {
155
        // An unrecognized admin target may be a native interface request.
156
        if (ec == error::invalid_target)
4 ✔
157
            protocol_native::dispatch_websocket(request);
3 ✔
158
        else
159
            send_bad_target(ec, request);
1 ✔
160

161
        return;
4 ✔
162
    }
163

164
    // Default to json by simulating a json accept header (format overrides).
165
    if (!admin_query(model, target, { media_type::application_json }))
16 ✔
166
    {
167
        send_bad_request(request);
1 ✔
168
        return;
169
    }
170

171
    if (strip_media(model) != media_type::application_json)
15 ✔
172
    {
173
        send_not_acceptable(request);
1 ✔
174
        return;
175
    }
176

177
    // The credential may be restricted to a subset of interface methods.
178
    if (!permitted(model.method))
14 ✔
179
    {
UNCOV
180
        send_forbidden(request);
×
181
        return;
182
    }
183

184
    if (admin_dispatcher_.notify(model))
14 ✔
UNCOV
185
        send_bad_request(request);
×
186
}
20 ✔
187

188
// Interface handlers.
189
// ----------------------------------------------------------------------------
190

191
void protocol_admin::handle_get_log_subscribe(const code& ec,
49 ✔
192
    admin_interface::log_subscribe, uint8_t /*version*/,
193
    uint64_t filter) NOEXCEPT
194
{
195
    BC_ASSERT(stranded());
49 ✔
196

197
    if (stopped(ec))
49 ✔
198
        return;
199

200
    // log outlives node, so cannot hold shared_ptr to the protocol.
201
    const auto previous = log_interest_->set(filter);
15 ✔
202
    if (!is_zero(filter) && !log_subscribed_)
15 ✔
203
    {
204
        auto handler = BIND_WEAK(handle_log, _1, _2, _3, _4);
10 ✔
205
        log.subscribe_messages(log_interest_, std::move(handler));
10 ✔
206
        log_subscribed_ = true;
10 ✔
207
    }
10 ✔
208

209
    send_json({ { "previous", previous } });
15 ✔
210
}
211

212
void protocol_admin::handle_get_event_subscribe(const code& ec,
42 ✔
213
    admin_interface::event_subscribe, uint8_t /*version*/,
214
    uint64_t filter) NOEXCEPT
215
{
216
    BC_ASSERT(stranded());
42 ✔
217

218
    if (stopped(ec))
42 ✔
219
        return;
34 ✔
220

221
    // log outlives node, so cannot hold shared_ptr to the protocol.
222
    uint64_t previous{};
8 ✔
223
    if (update_filter(previous, filter, event_state_))
8 ✔
224
        log.subscribe_events(BIND_WEAK(handle_event, _1, _2, _3, _4));
6 ✔
225

226
    send_json({ { "previous", previous } });
8 ✔
227
}
228

229
void protocol_admin::handle_get_mining(const code& ec,
34 ✔
230
    admin_interface::mining, uint8_t /*version*/) NOEXCEPT
231
{
232
    BC_ASSERT(stranded());
34 ✔
233

234
    if (stopped(ec))
34 ✔
235
        return;
236

UNCOV
237
    send_json(mining_snapshot());
×
238
}
239

240
// The snapshot is pushed as channels open or close, and periodically.
241
void protocol_admin::handle_get_mining_subscribe(const code& ec,
34 ✔
242
    admin_interface::mining_subscribe, uint8_t /*version*/) NOEXCEPT
243
{
244
    BC_ASSERT(stranded());
34 ✔
245

246
    if (stopped(ec))
34 ✔
247
        return;
248

UNCOV
249
    if (!websocket())
×
250
    {
UNCOV
251
        send_not_acceptable();
×
UNCOV
252
        return;
×
253
    }
254

UNCOV
255
    mining_generation_ = mining()->generation();
×
UNCOV
256
    mining_checks_ = zero;
×
UNCOV
257
    send_json(mining_snapshot());
×
258

UNCOV
259
    if (!mining_subscribed_)
×
260
    {
UNCOV
261
        mining_subscribed_ = true;
×
UNCOV
262
        start_mining();
×
263
    }
264
}
265

266
// Event handlers.
267
// ----------------------------------------------------------------------------
268

269
bool protocol_admin::handle_log(const code& ec, uint8_t level, time_t zulu,
4 ✔
270
    const std::string& message) NOEXCEPT
271
{
272
    if (stopped(ec))
4 ✔
273
        return false;
274

275
    if (websocket())
4 ✔
276
    {
277
        POST(do_log, level, zulu * 1'000_u64, message);
4 ✔
278
    }
279

280
    return true;
281
}
282

283
bool protocol_admin::handle_event(const code& ec, uint8_t event_,
4 ✔
284
    uint64_t value, const logger::time& point) NOEXCEPT
285
{
286
    bool filtered{};
4 ✔
287
    if (stopped(ec) || !get_filter(filtered, event_, event_state_))
4 ✔
288
        return false;
1 ✔
289

290
    if (!filtered || !websocket())
3 ✔
291
        return true;
1 ✔
292

293
    POST(do_event, event_, to_zulu(point), value);
2 ✔
294
    return true;
2 ✔
295
}
296

297
// Notification event handlers.
298
// ----------------------------------------------------------------------------
299
// Posted to the protocol strand.
300

301
void protocol_admin::do_log(uint8_t level, uint64_t zulu,
4 ✔
302
    const std::string& message) NOEXCEPT
303
{
304
    BC_ASSERT(stranded() && websocket());
4 ✔
305

306
    if (stopped())
4 ✔
307
        return;
308

309
    notify_json(
4 ✔
310
    {
311
        { "level", level },
312
        { "time", zulu },
313
        { "message", message }
314
    });
315
}
316

317
void protocol_admin::do_event(uint8_t event_, uint64_t zulu,
2 ✔
318
    uint64_t value_) NOEXCEPT
319
{
320
    BC_ASSERT(stranded() && websocket());
2 ✔
321

322
    if (stopped())
2 ✔
323
        return;
324

325
    notify_json(
2 ✔
326
    {
327
        { "event", event_ },
328
        { "value", value_ },
329
        { "time", zulu }
330
    });
331
}
332

UNCOV
333
void protocol_admin::start_mining() NOEXCEPT
×
334
{
UNCOV
335
    BC_ASSERT(stranded());
×
336

UNCOV
337
    if (stopped())
×
338
        return;
339

UNCOV
340
    mining_timer_->start(BIND(do_mining, _1),
×
UNCOV
341
        seconds{ mining_check_seconds });
×
342
}
343

UNCOV
344
void protocol_admin::do_mining(const code& ec) NOEXCEPT
×
345
{
UNCOV
346
    BC_ASSERT(stranded() && websocket());
×
347

UNCOV
348
    if (stopped() || ec == network::error::operation_canceled)
×
UNCOV
349
        return;
×
350

UNCOV
351
    if (ec)
×
352
    {
UNCOV
353
        stop(ec);
×
UNCOV
354
        return;
×
355
    }
356

UNCOV
357
    const auto generation = mining()->generation();
×
UNCOV
358
    if (generation != mining_generation_ ||
×
UNCOV
359
        ++mining_checks_ >= mining_snapshot_checks)
×
360
    {
UNCOV
361
        mining_generation_ = generation;
×
UNCOV
362
        mining_checks_ = zero;
×
UNCOV
363
        notify_json(mining_snapshot());
×
364
    }
365

UNCOV
366
    start_mining();
×
367
}
368

369
// Utils.
370
// ----------------------------------------------------------------------------
371
// static/private
372

UNCOV
373
system::json::value protocol_admin::mining_snapshot() const NOEXCEPT
×
374
{
UNCOV
375
    auto& registry = *mining();
×
UNCOV
376
    system::json::array channels{};
×
UNCOV
377
    for (const auto& channel: registry.get_channels(miners::now()))
×
378
    {
UNCOV
379
        system::json::array workers{};
×
UNCOV
380
        for (const auto& worker: channel.workers)
×
UNCOV
381
            workers.emplace_back(worker);
×
382

UNCOV
383
        system::json::object rejections{};
×
UNCOV
384
        for (const auto& [result, count]: channel.rejections)
×
UNCOV
385
            rejections[result] = count;
×
386

UNCOV
387
        system::json::array shares{};
×
UNCOV
388
        for (const auto& share: channel.shares)
×
UNCOV
389
            shares.push_back(system::json::object
×
390
            {
UNCOV
391
                { "time", share.time },
×
UNCOV
392
                { "height", share.height },
×
UNCOV
393
                { "difficulty", share.difficulty },
×
UNCOV
394
                { "result", share.result }
×
395
            });
396

UNCOV
397
        system::json::array history{};
×
UNCOV
398
        for (const auto& sample: channel.history)
×
UNCOV
399
            history.push_back(system::json::array{ sample.time, sample.rate });
×
400

UNCOV
401
        system::json::value last{};
×
UNCOV
402
        if (channel.last_share.has_value())
×
UNCOV
403
            last = channel.last_share.value();
×
404

UNCOV
405
        channels.push_back(system::json::object
×
406
        {
UNCOV
407
            { "id", channel.id },
×
UNCOV
408
            { "service", channel.service },
×
UNCOV
409
            { "transport", channel.transport },
×
UNCOV
410
            { "address", channel.address },
×
UNCOV
411
            { "client", channel.client },
×
UNCOV
412
            { "workers", std::move(workers) },
×
UNCOV
413
            { "connected", channel.connected },
×
UNCOV
414
            { "difficulty", channel.difficulty },
×
UNCOV
415
            { "hashrate", channel.hashrate },
×
UNCOV
416
            { "accepted", channel.accepted },
×
UNCOV
417
            { "rejected", channel.rejected },
×
UNCOV
418
            { "rejections", std::move(rejections) },
×
UNCOV
419
            { "last_share", std::move(last) },
×
UNCOV
420
            { "shares", std::move(shares) },
×
UNCOV
421
            { "history", std::move(history) }
×
422
        });
UNCOV
423
    }
×
424

UNCOV
425
    system::json::array blocks{};
×
UNCOV
426
    for (const auto& block: registry.get_blocks())
×
UNCOV
427
        blocks.push_back(system::json::object
×
428
        {
UNCOV
429
            { "hash", encode_hash(block.hash) },
×
UNCOV
430
            { "height", block.height },
×
UNCOV
431
            { "time", block.time },
×
UNCOV
432
            { "channel", block.channel }
×
UNCOV
433
        });
×
434

UNCOV
435
    return system::json::object
×
436
    {
UNCOV
437
        { "channels", std::move(channels) },
×
UNCOV
438
        { "blocks", std::move(blocks) }
×
UNCOV
439
    };
×
UNCOV
440
}
×
441

442
// zulu time in milliseconds since epoch (native js time format).
443
uint64_t protocol_admin::to_zulu(const logger::time& point) NOEXCEPT
2 ✔
444
{
445
    using namespace std::chrono;
446
    const auto now = logger::now();
2 ✔
447
    const auto delta = duration_cast<system_clock::duration>(now - point);
2 ✔
448
    const auto time = (system_clock::now() - delta).time_since_epoch();
2 ✔
449
    return duration_cast<milliseconds>(time).count();
2 ✔
450
}
451

452
// Unsubscribe if false.
453
bool protocol_admin::get_filter(bool& filtered, size_t bit,
4 ✔
454
    filter_t& filter) NOEXCEPT
455
{
456
    auto state = filter.load(relaxed);
457
    const auto next = set_left(state, zero, false);
4 ✔
458

459
    // Empty filter unregisters, failure implies a new filter arrived.
460
    if (is_zero(next) && filter.compare_exchange_strong(state, next, relaxed))
5 ✔
461
        return false;
462

463
    filtered = get_right(state, bit);
3 ✔
464
    return true;
3 ✔
465
}
466

467
// Subscribe if true.
468
bool protocol_admin::update_filter(uint64_t& prior, uint64_t value,
8 ✔
469
    filter_t& filter) NOEXCEPT
470
{
471
    const auto next = set_left(value, zero, true);
8 ✔
472
    const auto state = is_zero(value) ? filter.fetch_and(next, relaxed) :
8 ✔
473
        filter.exchange(next, relaxed);
474

475
    prior = set_left(state, zero, false);
8 ✔
476
    return !is_zero(value) && !get_left(state);
8 ✔
477
}
478

479
} // namespace server
480
} // 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