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

libbitcoin / libbitcoin-system / 44793656845

20 Nov 2026 06:31PM UTC coverage: 96.46% (+0.006%) from 96.454%
44793656845

Pull #2189

github

web-flow
Merge a5e71dc34 into af0039d66
Pull Request #2189: Pool updates.

237 of 243 new or added lines in 2 files covered. (97.53%)

28991 of 30055 relevant lines covered (96.46%)

3668595.85 hits per line

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

98.64
/include/bitcoin/system/impl/pool/algorithm.ipp
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
#ifndef LIBBITCOIN_SYSTEM_POOL_ALGORITHM_IPP
20
#define LIBBITCOIN_SYSTEM_POOL_ALGORITHM_IPP
21

22
#include <span>
23
#include <unordered_set>
24
#include <bitcoin/system/data/data.hpp>
25
#include <bitcoin/system/define.hpp>
26
#include <bitcoin/system/endian/endian.hpp>
27
#include <bitcoin/system/intrinsics/intrinsics.hpp>
28
#include <bitcoin/system/math/math.hpp>
29

30
namespace libbitcoin {
31
namespace system {
32
namespace pool {
33

34
BC_PUSH_WARNING(NO_USE_OF_SPAN)
35
BC_PUSH_WARNING(NO_ARRAY_INDEXING)
36
BC_PUSH_WARNING(NO_DYNAMIC_ARRAY_INDEXING)
37
BC_PUSH_WARNING(NO_POINTER_ARITHMETIC)
38

39
// Cells.
40
// ----------------------------------------------------------------------------
41

42
constexpr bool algorithm::is_present(link_t cell) NOEXCEPT
831,606 ✔
43
{
44
    return cell < absent;
831,606 ✔
45
}
46

47
constexpr bool algorithm::is_labeled(link_t cell) NOEXCEPT
450,251 ✔
48
{
49
    return cell < unlabeled;
450,251 ✔
50
}
51

52
constexpr bool algorithm::is_boundary(link_t cell) NOEXCEPT
338,439 ✔
53
{
54
    return cell == boundary;
338,439 ✔
55
}
56

57
constexpr bool algorithm::is_absent(link_t cell) NOEXCEPT
445,773 ✔
58
{
59
    return cell >= absent && cell < boundary;
445,773 ✔
60
}
61

62
constexpr algorithm::link_t algorithm::raised(link_t cell,
21,547 ✔
63
    link_t cause) NOEXCEPT
64
{
65
    return bit_or(is_absent(cell) ? cell : absent, cause);
21,547 ✔
66
}
67

68
constexpr algorithm::link_t algorithm::lowered(link_t cell,
78,689 ✔
69
    link_t cause) NOEXCEPT
70
{
71
    if (!is_absent(cell))
78,689 ✔
72
        return cell;
73

74
    const auto left = bit_and(cell, bit_not(cause));
22,168 ✔
75
    return left == absent ? unlabeled : left;
22,168 ✔
76
}
77

78
constexpr uint64_t algorithm::chargeable(const totals_t& totals,
592 ✔
79
    uint32_t bytes_per_sigop) NOEXCEPT
80
{
81
    const auto sigops = totals.sigops;
592 ✔
82
    const auto cost = ceilinged_multiply<uint64_t>(sigops, bytes_per_sigop);
592 ✔
83
    return greater(totals.size, cost);
592 ✔
84
}
85

86
constexpr uint64_t algorithm::chargeable(mask_t outcome,
142 ✔
87
    const component_t& component, const graph_t& graph,
88
    uint32_t bytes_per_sigop) NOEXCEPT
89
{
90
    uint64_t bytes{};
91
    for (size_t member{}; member < component.count; ++member)
852 ✔
92
    {
93
        if (!get_right(outcome, member))
710 ✔
94
            continue;
420 ✔
95

96
        const auto row = totals(graph, component.rows[member]);
290 ✔
97
        bytes = ceilinged_add(bytes, chargeable(row, bytes_per_sigop));
290 ✔
98
    }
99

100
    return bytes;
142 ✔
101
}
102

103
constexpr uint64_t algorithm::fee_rate(const totals_t& totals,
91 ✔
104
    uint32_t bytes_per_sigop) NOEXCEPT
105
{
106
    const auto size = greater(chargeable(totals, bytes_per_sigop), one);
91 ✔
107
    return ceilinged_multiply(totals.fee, 1'000_u64) / size;
91 ✔
108
}
109

110
// Column values.
111
// ----------------------------------------------------------------------------
112

113
constexpr algorithm::link_t algorithm::to_column(link_t value) NOEXCEPT
221,214 ✔
114
{
115
    return native_to_little_end(value);
221,214 ✔
116
}
117

118
constexpr algorithm::edges_t algorithm::to_column(
3,166 ✔
119
    const edges_t& value) NOEXCEPT
120
{
121
    return { to_column(value.first), to_column(value.count) };
3,166 ✔
122
}
123

124
constexpr algorithm::totals_t algorithm::to_column(
3,162 ✔
125
    const totals_t& value) NOEXCEPT
126
{
127
    return
128
    {
129
        native_to_little_end(value.fee),
3,162 ✔
130
        native_to_little_end(value.size),
3,162 ✔
131
        native_to_little_end(value.sigops)
3,162 ✔
132
    };
3,162 ✔
133
}
134

135
constexpr algorithm::link_t algorithm::from_column(link_t value) NOEXCEPT
9,939,886 ✔
136
{
137
    return native_from_little_end(value);
9,939,886 ✔
138
}
139

140
constexpr algorithm::edges_t algorithm::from_column(
2,309,492 ✔
141
    const edges_t& value) NOEXCEPT
142
{
143
    return { from_column(value.first), from_column(value.count) };
2,309,492 ✔
144
}
145

146
constexpr algorithm::totals_t algorithm::from_column(
3,061 ✔
147
    const totals_t& value) NOEXCEPT
148
{
149
    return
150
    {
151
        native_from_little_end(value.fee),
3,061 ✔
152
        native_from_little_end(value.size),
3,061 ✔
153
        native_from_little_end(value.sigops)
3,061 ✔
154
    };
3,061 ✔
155
}
156

157
// Candidates.
158
// ----------------------------------------------------------------------------
159

160
constexpr void algorithm::initialize(const graph_t& graph,
3 ✔
161
    const std::span<const link_t>& candidates) NOEXCEPT
162
{
163
    for (const auto row: candidates)
6 ✔
164
        set_cell(graph, row, unlabeled);
3 ✔
165

166
    // Relevance closes over the candidates in at most count passes.
167
    for (auto changed = true; changed;)
8 ✔
168
    {
169
        changed = false;
170
        for (const auto row: candidates)
10 ✔
171
        {
172
            if (is_labeled(cell(graph, row)))
5 ✔
173
                continue;
2 ✔
174

175
            if (contested(graph, row) || descended(graph, row))
3 ✔
176
            {
177
                set_cell(graph, row, row);
2 ✔
178
                changed = true;
179
            }
180
        }
181
    }
182
}
3 ✔
183

184
// Components (frontier).
185
// ----------------------------------------------------------------------------
186

187
constexpr bool algorithm::collect(component_t& out, const graph_t& graph,
2,214 ✔
188
    link_t row) NOEXCEPT
189
{
190
    out = {};
2,214 ✔
191
    const auto add = [&](link_t found) NOEXCEPT
98,350 ✔
192
    {
193
        if (index(out, found) != maximum_members)
98,350 ✔
194
            return true;
195

196
        if (out.count == maximum_members)
52,956 ✔
197
            return false;
198

199
        out.rows[out.count++] = found;
52,021 ✔
200
        return true;
52,021 ✔
201
    };
2,214 ✔
202

203
    if (!add(row))
2,214 ✔
204
        return false;
205

206
    for (size_t at{}; at < out.count; ++at)
39,530 ✔
207
    {
208
        const auto member = out.rows[at];
37,893 ✔
209
        const auto slice = edges(graph, member);
37,893 ✔
210
        for (auto input = slice.first; input < slice.first + slice.count;
119,339 ✔
211
            ++input)
212
        {
213
            const auto up = parent(graph, input);
81,604 ✔
214
            if (up != none && is_labeled(cell(graph, up)) && !add(up))
81,604 ✔
215
                return false;
158 ✔
216

217
            auto added = true;
81,510 ✔
218
            each_rival(graph, input, [&](link_t other) NOEXCEPT
81,510 ✔
219
            {
220
                const auto rival_row = owner(graph, other);
21,026 ✔
221
                if (is_present(cell(graph, rival_row)) && !add(rival_row))
21,026 ✔
222
                    added = false;
80 ✔
223
            });
21,026 ✔
224

225
            if (!added)
81,510 ✔
226
                return false;
227
        }
228

229
        auto added = true;
37,735 ✔
230
        each_child(graph, member, [&](link_t down) NOEXCEPT
37,735 ✔
231
        {
232
            if (is_present(cell(graph, down)) && !add(down))
54,244 ✔
233
                added = false;
761 ✔
234
        });
54,244 ✔
235

236
        if (!added)
37,735 ✔
237
            return false;
238
    }
239

240
    std::sort(out.rows.begin(), std::next(out.rows.begin(), out.count));
1,637 ✔
241
    return true;
1,637 ✔
242
}
243

244
constexpr bool algorithm::relate(component_t& out,
28 ✔
245
    const graph_t& graph) NOEXCEPT
246
{
247
    out.contests = zero;
28 ✔
248
    for (size_t member{}; member < out.count; ++member)
169 ✔
249
    {
250
        mask_t direct{};
141 ✔
251
        const auto row = out.rows[member];
141 ✔
252
        const auto slice = edges(graph, row);
141 ✔
253
        for (auto input = slice.first; input < slice.first + slice.count;
310 ✔
254
            ++input)
255
        {
256
            const auto up = index(out, parent(graph, input));
169 ✔
257
            if (up != maximum_members)
169 ✔
258
                set_right_into(direct, up);
56 ✔
259

260
            auto clique = set_right(mask_t{}, member);
169 ✔
261
            each_rival(graph, input, [&](link_t other) NOEXCEPT
169 ✔
262
            {
263
                const auto rival_member = index(out, owner(graph, other));
116 ✔
264
                if (rival_member != maximum_members)
116 ✔
265
                    set_right_into(clique, rival_member);
116 ✔
266
            });
116 ✔
267

268
            if (is_one(ones_count(clique)))
169 ✔
269
                continue;
113 ✔
270

271
            const auto end = std::next(out.cliques.begin(), out.contests);
113 ✔
272
            if (std::find(out.cliques.begin(), end, clique) != end)
113 ✔
273
                continue;
57 ✔
274

275
            if (out.contests == maximum_members)
56 ✔
276
                return false;
×
277

278
            out.cliques[out.contests++] = clique;
56 ✔
279
        }
280

281
        out.ancestors[member] = direct;
141 ✔
282
    }
283

284
    // Ancestry closes within the component in at most count passes.
285
    for (auto changed = true; changed;)
56 ✔
286
    {
287
        changed = false;
288
        for (size_t member{}; member < out.count; ++member)
169 ✔
289
        {
290
            auto ancestors = out.ancestors[member];
141 ✔
291
            for (size_t up{}; up < out.count; ++up)
852 ✔
292
                if (get_right(ancestors, up))
711 ✔
293
                    ancestors |= out.ancestors[up];
56 ✔
294

295
            if (ancestors != out.ancestors[member])
141 ✔
296
            {
297
                out.ancestors[member] = ancestors;
×
298
                changed = true;
299
            }
300
        }
301
    }
302

303
    return true;
304
}
305

306
constexpr algorithm::mask_t algorithm::members(const component_t& component,
1 ✔
307
    const std::span<const link_t>& rows) NOEXCEPT
308
{
309
    mask_t out{};
1 ✔
310
    for (const auto row: rows)
4 ✔
311
    {
312
        const auto member = index(component, row);
3 ✔
313
        if (member != maximum_members)
3 ✔
314
            set_right_into(out, member);
2 ✔
315
    }
316

317
    return out;
1 ✔
318
}
319

320
inline bool algorithm::ancestry(totals_t& out, const graph_t& graph,
4 ✔
321
    const component_t& component, const totals_t& limit) NOEXCEPT
322
{
323
    out = {};
4 ✔
324
    std::vector<link_t> visited{};
4 ✔
325
    std::vector<link_t> pending{};
4 ✔
326
    const auto push = [&](link_t row) NOEXCEPT
7 ✔
327
    {
328
        if (index(component, row) != maximum_members ||
7 ✔
329
            std::ranges::find(visited, row) != visited.end())
1 ✔
330
            return;
6 ✔
331

332
        visited.push_back(row);
1 ✔
333
        pending.push_back(row);
1 ✔
334
    };
4 ✔
335

336
    const auto charge = [&](link_t row) NOEXCEPT
18 ✔
337
    {
338
        const auto& add = totals(graph, row);
18 ✔
339
        out.fee = ceilinged_add(out.fee, add.fee);
18 ✔
340
        out.size = ceilinged_add(out.size, add.size);
18 ✔
341
        out.sigops = ceilinged_add(out.sigops, add.sigops);
18 ✔
342

343
        const auto slice = edges(graph, row);
18 ✔
344
        for (auto input = slice.first; input < slice.first + slice.count;
39 ✔
345
            ++input)
346
        {
347
            const auto up = parent(graph, input);
21 ✔
348
            if (up != none && is_present(cell(graph, up)))
21 ✔
349
                push(up);
7 ✔
350
        }
351

352
        return out.size <= limit.size && out.sigops <= limit.sigops;
18 ✔
353
    };
4 ✔
354

355
    for (size_t member{}; member < component.count; ++member)
19 ✔
356
        if (!charge(component.rows[member]))
17 ✔
357
            return false;
358

359
    while (!pending.empty())
3 ✔
360
    {
361
        const auto row = pending.back();
1 ✔
362
        pending.pop_back();
1 ✔
363
        if (!charge(row))
1 ✔
364
            return false;
365
    }
366

367
    return true;
368
}
4 ✔
369

370
template <typename Word>
371
inline bool algorithm::family(uint64_t& fee, uint64_t& bytes,
3 ✔
372
    const graph_t& graph, const std::span<const link_t>& rows,
373
    uint64_t limit, uint32_t bytes_per_sigop,
374
    size_t maximum_outcomes) NOEXCEPT
375
{
376
    fee = zero;
3 ✔
377
    bytes = zero;
3 ✔
378
    std::vector<link_t> found{};
3 ✔
379
    std::unordered_set<link_t> visited{};
3 ✔
380
    const auto push = [&](link_t row) NOEXCEPT
39 ✔
381
    {
382
        if (row == none || !is_present(cell(graph, row)) ||
36 ✔
383
            !visited.insert(row).second)
25 ✔
384
            return true;
21 ✔
385

386
        found.push_back(row);
15 ✔
387
        const auto size = chargeable(totals(graph, row), bytes_per_sigop);
15 ✔
388
        bytes = ceilinged_add(bytes, size);
15 ✔
389
        return bytes <= limit;
15 ✔
390
    };
391

392
    for (const auto row: rows)
6 ✔
393
        if (!push(row))
3 ✔
NEW
394
            return false;
×
395

396
    for (size_t at{}; at < found.size(); ++at)
15 ✔
397
    {
398
        auto within = true;
13 ✔
399
        const auto row = found[at];
13 ✔
400
        const auto slice = edges(graph, row);
13 ✔
401
        for (auto input = slice.first; input < slice.first + slice.count;
29 ✔
402
            ++input)
403
        {
404
            within = within && push(parent(graph, input));
16 ✔
405
            each_rival(graph, input, [&](link_t other) NOEXCEPT
16 ✔
406
            {
407
                within = within && push(owner(graph, other));
11 ✔
408
            });
409
        }
410

411
        each_child(graph, row, [&](link_t down) NOEXCEPT
13 ✔
412
        {
413
            within = within && push(down);
6 ✔
414
        });
415

416
        if (!within)
13 ✔
417
            return false;
1 ✔
418
    }
419

420
    // Each component pays its best outcome, then each other row its fee.
421
    std::vector<mask_t> masks{};
2 ✔
422
    std::unordered_set<link_t> resolved{};
2 ✔
423
    for (const auto row: found)
7 ✔
424
    {
425
        if (!is_labeled(cell(graph, row)) || resolved.contains(row))
6 ✔
426
            continue;
4 ✔
427

428
        component_t component{};
2 ✔
429
        if (!collect(component, graph, row) || !relate(component, graph))
2 ✔
430
            return false;
1 ✔
431

432
        const auto leaves = outcomes(component);
2 ✔
433
        if (leaves > maximum_outcomes)
2 ✔
434
            return false;
435

436
        masks.resize(leaves);
1 ✔
437
        for (size_t index{}; index < leaves; ++index)
5 ✔
438
            masks[index] = outcome(component, index);
4 ✔
439

440
        fee = ceilinged_add(fee, evaluate<Word>(masks, component, graph));
1 ✔
441
        for (size_t member{}; member < component.count; ++member)
6 ✔
442
            resolved.insert(component.rows[member]);
5 ✔
443
    }
444

445
    for (const auto row: found)
6 ✔
446
        if (!resolved.contains(row))
5 ✔
NEW
447
            fee = ceilinged_add(fee, totals(graph, row).fee);
×
448

449
    return true;
1 ✔
450
}
3 ✔
451

452
// Outcomes.
453
// ----------------------------------------------------------------------------
454

455
constexpr size_t algorithm::outcomes(const component_t& component) NOEXCEPT
10 ✔
456
{
457
    size_t out{ one };
458
    for (size_t contest{}; contest < component.contests; ++contest)
30 ✔
459
        out = ceilinged_multiply(out, ones_count(component.cliques[contest]));
20 ✔
460

461
    return out;
10 ✔
462
}
463

464
constexpr algorithm::mask_t algorithm::outcome(const component_t& component,
176 ✔
465
    size_t index) NOEXCEPT
466
{
467
    const auto lost = losers(component, index);
176 ✔
468
    auto out = bit_and(unmask_right<mask_t>(component.count), bit_not(lost));
176 ✔
469
    for (size_t member{}; member < component.count; ++member)
1,056 ✔
470
        if (is_nonzero(bit_and(component.ancestors[member], lost)))
880 ✔
471
            out = set_right(out, member, false);
215 ✔
472

473
    return out;
176 ✔
474
}
475

476
template <typename Word>
477
constexpr uint64_t algorithm::evaluate(const std::span<const mask_t>& outcomes,
8 ✔
478
    const component_t& component, const graph_t& graph) NOEXCEPT
479
{
480
    uint64_t best{};
8 ✔
481
    each_fee<Word>(zero, outcomes, component, graph,
8 ✔
482
        [&](size_t, uint64_t fee) NOEXCEPT
154 ✔
483
        {
484
            best = std::max(best, fee);
146 ✔
485
        });
486

487
    return best;
8 ✔
488
}
489

490
constexpr uint64_t algorithm::chargeable(const component_t& component,
3 ✔
491
    const graph_t& graph, uint32_t bytes_per_sigop) NOEXCEPT
492
{
493
    uint64_t bytes{};
494
    for (size_t member{}; member < component.count; ++member)
18 ✔
495
    {
496
        const auto row = totals(graph, component.rows[member]);
15 ✔
497
        bytes = ceilinged_add(bytes, chargeable(row, bytes_per_sigop));
15 ✔
498
    }
499

500
    return bytes;
3 ✔
501
}
502

503
constexpr bool algorithm::covered(uint64_t fee, uint64_t bytes,
4 ✔
504
    uint64_t rate) NOEXCEPT
505
{
506
    // Compared in satoshis per virtual kilobyte.
507
    return ceilinged_multiply(fee, 1'000_u64) >=
4 ✔
508
        ceilinged_multiply(rate, bytes);
4 ✔
509
}
510

511
// Transitions (frontier, table columns).
512
// ----------------------------------------------------------------------------
513

514
constexpr void algorithm::relabel(const columns_t& columns,
645 ✔
515
    const component_t& component) NOEXCEPT
516
{
517
    // Rows are sorted by collect, so the label is the first.
518
    const auto label = to_column(component.rows.front());
645 ✔
519
    for (size_t member{}; member < component.count; ++member)
7,493 ✔
520
        columns.cells[component.rows[member]] = label;
6,848 ✔
521
}
645 ✔
522

523
inline bool algorithm::admit(const columns_t& columns, link_t row,
3 ✔
524
    bool conflict) NOEXCEPT
525
{
526
    walk_t walk{};
3 ✔
527
    const graph_t graph{ columns };
3 ✔
528
    set_cell(graph, row, conflict ? bit_or(absent, conflicted) : unlabeled);
3 ✔
529

530
    // Its children are the rows adopted by it.
531
    walk.affected.push_back(row);
3 ✔
532
    walk.pending.push_back(row);
3 ✔
533
    each_child(graph, row, [&](link_t down) NOEXCEPT
3 ✔
534
    {
535
        walk.pending.push_back(down);
1 ✔
536
    });
1 ✔
537

538
    return spread(walk, columns);
6 ✔
539
}
3 ✔
540

541
inline bool algorithm::confirm(const columns_t& columns,
172 ✔
542
    const std::span<const link_t>& rows,
543
    const std::span<const link_t>& conflicts) NOEXCEPT
544
{
545
    walk_t walk{};
172 ✔
546
    const graph_t graph{ columns };
172 ✔
547
    for (const auto row: rows)
1,464 ✔
548
        change(walk, columns, row, boundary);
1,292 ✔
549

550
    for (const auto row: conflicts)
818 ✔
551
        if (!is_boundary(cell(graph, row)))
646 ✔
552
            change(walk, columns, row, raised(cell(graph, row), conflicted));
524 ✔
553

554
    return spread(walk, columns);
344 ✔
555
}
172 ✔
556

557
inline bool algorithm::unconfirm(const columns_t& columns,
90 ✔
558
    const std::span<const link_t>& rows,
559
    const std::span<const link_t>& conflicts) NOEXCEPT
560
{
561
    walk_t walk{};
90 ✔
562
    const graph_t graph{ columns };
90 ✔
563
    for (const auto row: rows)
755 ✔
564
    {
565
        if (!is_boundary(cell(graph, row)))
665 ✔
566
            continue;
8 ✔
567

568
        change(walk, columns, row, unlabeled);
657 ✔
569
        walk.pending.push_back(row);
657 ✔
570
    }
571

572
    for (const auto row: conflicts)
423 ✔
573
        change(walk, columns, row, lowered(cell(graph, row), conflicted));
333 ✔
574

575
    return spread(walk, columns);
180 ✔
576
}
90 ✔
577

578
// Template (frontier, table columns).
579
// ----------------------------------------------------------------------------
580

581
template <typename Word>
582
inline void algorithm::resolve(std::span<mark> marks,
7 ✔
583
    const columns_t& columns, size_t maximum_outcomes, uint64_t rate,
584
    uint32_t bytes_per_sigop) NOEXCEPT
585
{
586
    const graph_t graph{ columns };
7 ✔
587
    const auto count = columns.cells.size();
7 ✔
588
    for (size_t row{}; row < count; ++row)
40 ✔
589
    {
590
        const auto present = is_present(from_column(columns.cells[row]));
33 ✔
591
        marks[row] = present ? mark::unmarked : mark::excluded;
34 ✔
592
    }
593

594
    std::vector<mask_t> masks{};
7 ✔
595
    for (size_t at{}; at < count; ++at)
40 ✔
596
    {
597
        // A component is resolved at its label, its lowest member row.
598
        const auto row = possible_narrow_cast<link_t>(at);
33 ✔
599
        const auto label = cell(graph, row);
33 ✔
600
        if (!is_labeled(label) || label != row)
33 ✔
601
            continue;
28 ✔
602

603
        component_t component{};
6 ✔
604
        const auto collected = collect(component, graph, row);
6 ✔
605
        const auto related = collected && relate(component, graph);
6 ✔
606
        const auto limit = related ? maximum_outcomes : zero;
6 ✔
607
        const auto leaves = outcomes(component);
6 ✔
608
        const auto total = std::min(leaves, limit);
6 ✔
609

610
        if (is_zero(total))
6 ✔
611
        {
612
            forfeit(marks, graph, row);
1 ✔
613
            continue;
1 ✔
614
        }
615

616
        masks.resize(total);
5 ✔
617
        for (size_t index{}; index < total; ++index)
23 ✔
618
            masks[index] = outcome(component, index);
18 ✔
619

620
        // Leaves past the bound are represented by a greedy leaf.
621
        if (leaves > total)
5 ✔
622
            masks.push_back(greedy(component, graph, rate, bytes_per_sigop));
1 ✔
623

624
        const auto chosen = masks[best<Word>(masks, component, graph, rate,
5 ✔
625
            bytes_per_sigop)];
626

627
        for (size_t member{}; member < component.count; ++member)
30 ✔
628
            if (!get_right(chosen, member))
25 ✔
629
                discard(marks, graph, component.rows[member]);
11 ✔
630
    }
631
}
7 ✔
632

633
inline void algorithm::pack(std::vector<link_t>& out, std::span<mark> marks,
10 ✔
634
    const columns_t& columns, const totals_t& budget, size_t depth,
635
    uint32_t bytes_per_sigop) NOEXCEPT
636
{
637
    takes_t takes{};
10 ✔
638
    pack_(out, takes, marks, columns, budget, depth, bytes_per_sigop);
10 ✔
639
}
10 ✔
640

641
inline void algorithm::project(std::vector<link_t>& out,
23 ✔
642
    projection_t& projection, const columns_t& columns,
643
    const totals_t& budget, size_t depth, uint32_t bytes_per_sigop) NOEXCEPT
644
{
645
    takes_t takes{};
23 ✔
646
    auto& marks = projection.marks;
23 ✔
647
    pack_(out, takes, marks, columns, budget, depth, bytes_per_sigop);
23 ✔
648

649
    const auto left = std::ranges::find(marks, mark::unmarked) != marks.end();
23 ✔
650
    projection.exhausted = takes.empty() || !left;
23 ✔
651
    if (!takes.empty())
23 ✔
652
        projection.blocks.push_back(std::move(takes));
21 ✔
653
}
23 ✔
654

655
// Estimate (projected blocks).
656
// ----------------------------------------------------------------------------
657

658
constexpr uint64_t algorithm::above(const std::span<const take_t>& takes,
874 ✔
659
    uint64_t rate) NOEXCEPT
660
{
661
    uint64_t size{};
662
    for (const auto& take: takes)
2,468 ✔
663
        if (take.rate >= rate)
1,594 ✔
664
            size = ceilinged_add(size, take.size);
876 ✔
665

666
    return size;
874 ✔
667
}
668

669
template <typename Arrivals>
670
inline uint64_t algorithm::estimate(const projection_t& projection,
9 ✔
671
    size_t count, uint64_t space, const Arrivals& arrivals) NOEXCEPT
672
{
673
    uint64_t low{};
674
    auto high = max_uint64;
675
    if (!reaches(projection, count, space, high, arrivals))
9 ✔
676
        return high;
677

678
    // A rate that is taken implies that each higher rate is taken.
679
    while (low < high)
455 ✔
680
    {
681
        const auto middle = low + to_half(high - low);
448 ✔
682
        if (reaches(projection, count, space, middle, arrivals))
448 ✔
683
            high = middle;
684
        else
685
            low = add1(middle);
16 ✔
686
    }
687

688
    return low;
689
}
690

691
// Columns (whole table).
692
// ----------------------------------------------------------------------------
693

694
template <typename Word>
695
constexpr bool algorithm::collect(component_t& out, link_t label,
9 ✔
696
    const std::span<const link_t>& cells) NOEXCEPT
697
{
698
    out = {};
9 ✔
699
    return collect_<Word>(zero, out, label, cells);
9 ✔
700
}
701

702
template <typename Word>
703
inline void algorithm::find(std::vector<link_t>& out,
7 ✔
704
    const std::span<const link_t>& values, link_t value) NOEXCEPT
705
{
706
    out.clear();
7 ✔
707
    find_<Word>(zero, out, values, value);
7 ✔
708
}
7 ✔
709

710
// Internals.
711
// ----------------------------------------------------------------------------
712

713
constexpr size_t algorithm::rows(const graph_t& graph) NOEXCEPT
5,759,649 ✔
714
{
715
    return graph.table.cells.size();
5,759,649 ✔
716
}
717

718
constexpr algorithm::link_t algorithm::cell(const graph_t& graph,
1,498,374 ✔
719
    link_t row) NOEXCEPT
720
{
721
    const auto count = rows(graph);
1,498,374 ✔
722
    return from_column(row < count ? graph.table.cells[row] :
1,498,385 ✔
723
        graph.extra.cells[row - count]);
11 ✔
724
}
725

726
constexpr void algorithm::set_cell(const graph_t& graph, link_t row,
64,028 ✔
727
    link_t value) NOEXCEPT
728
{
729
    const auto count = rows(graph);
64,028 ✔
730
    auto& stored = row < count ? graph.table.cells[row] :
64,023 ✔
731
        graph.extra.cells[row - count];
64,028 ✔
732

733
    stored = to_column(value);
64,028 ✔
734
}
64,028 ✔
735

736
constexpr algorithm::edges_t algorithm::edges(const graph_t& graph,
2,309,492 ✔
737
    link_t row) NOEXCEPT
738
{
739
    const auto count = rows(graph);
2,309,492 ✔
740
    return from_column(row < count ? graph.table.edges[row] :
2,309,492 ✔
741
        graph.extra.edges[row - count]);
11 ✔
742
}
743

744
constexpr algorithm::totals_t algorithm::totals(const graph_t& graph,
3,061 ✔
745
    link_t row) NOEXCEPT
746
{
747
    const auto count = rows(graph);
3,061 ✔
748
    return from_column(row < count ? graph.table.totals[row] :
3,061 ✔
749
        graph.extra.totals[row - count]);
×
750
}
751

752
constexpr algorithm::link_t algorithm::child(const graph_t& graph,
41,235 ✔
753
    link_t row) NOEXCEPT
754
{
755
    const auto count = rows(graph);
41,235 ✔
756
    return from_column(row < count ? graph.table.children[row] :
41,239 ✔
757
        graph.extra.children[row - count]);
4 ✔
758
}
759

760
constexpr algorithm::link_t algorithm::parent(const graph_t& graph,
664,452 ✔
761
    link_t input) NOEXCEPT
762
{
763
    const auto count = graph.table.rows.size();
664,452 ✔
764
    return from_column(input < count ? graph.table.rows[input] :
664,460 ✔
765
        graph.extra.rows[input - count]);
8 ✔
766
}
767

768
constexpr algorithm::link_t algorithm::owner(const graph_t& graph,
214,221 ✔
769
    link_t input) NOEXCEPT
770
{
771
    // The last row whose first input is not beyond the input.
772
    const auto count = graph.table.rows.size();
214,221 ✔
773
    const auto& edges = input < count ? graph.table.edges : graph.extra.edges;
214,221 ✔
774
    const auto after = std::upper_bound(edges.begin(), edges.end(), input,
214,221 ✔
775
        [](link_t at, const edges_t& edge) NOEXCEPT
1,761,570 ✔
776
        {
777
            return at < from_column(edge.first);
1,761,570 ✔
778
        });
779

780
    const auto base = input < count ? zero : rows(graph);
214,221 ✔
781
    const auto offset = std::distance(edges.begin(), std::prev(after));
214,221 ✔
782
    return possible_narrow_cast<link_t>(base + offset);
214,221 ✔
783
}
784

785
constexpr algorithm::link_t algorithm::sibling(const graph_t& graph,
57,408 ✔
786
    link_t input) NOEXCEPT
787
{
788
    const auto count = graph.table.rows.size();
57,408 ✔
789
    return from_column(input < count ? graph.table.siblings[input] :
57,408 ✔
790
        graph.extra.siblings[input - count]);
×
791
}
792

793
constexpr algorithm::link_t algorithm::rival(const graph_t& graph,
1,132,886 ✔
794
    link_t input) NOEXCEPT
795
{
796
    const auto count = graph.table.rows.size();
1,132,886 ✔
797
    return from_column(input < count ? graph.table.rivals[input] :
1,132,900 ✔
798
        graph.extra.rivals[input - count]);
14 ✔
799
}
800

801
template <typename Visitor>
802
constexpr void algorithm::each_child(const graph_t& graph, link_t row,
41,235 ✔
803
    const Visitor& visit) NOEXCEPT
804
{
805
    for (auto input = child(graph, row); input != none;
98,643 ✔
806
        input = sibling(graph, input))
57,408 ✔
807
        visit(owner(graph, input));
57,408 ✔
808

809
    if (row < rows(graph))
41,235 ✔
810
        for (const auto& bridge: graph.children)
41,239 ✔
811
            if (bridge.from == row)
8 ✔
812
                visit(owner(graph, bridge.to));
2 ✔
813
}
41,235 ✔
814

815
template <typename Visitor>
816
constexpr void algorithm::each_rival(const graph_t& graph, link_t input,
503,746 ✔
817
    const Visitor& visit) NOEXCEPT
818
{
819
    // A candidate input enters the ring of its table rival, which excludes it.
820
    const auto count = graph.table.rows.size();
503,746 ✔
821
    const auto next = rival(graph, input);
503,746 ✔
822
    const auto start = (input >= count && next < count) ? next : input;
503,746 ✔
823
    auto at = start;
824

825
    do
826
    {
827
        if (at != input)
629,140 ✔
828
            visit(at);
125,398 ✔
829

830
        // A table input bridges to the candidate inputs spending its point.
831
        if (at < count)
629,140 ✔
832
            for (const auto& bridge: graph.rivals)
629,173 ✔
833
                if (bridge.from == at && bridge.to != input)
38 ✔
834
                    visit(bridge.to);
6 ✔
835

836
        at = rival(graph, at);
629,140 ✔
837
    }
838
    while (at != none && at != start);
629,140 ✔
839
}
503,746 ✔
840

841
constexpr bool algorithm::contested(const graph_t& graph, link_t row) NOEXCEPT
5,253 ✔
842
{
843
    auto out = false;
5,253 ✔
844
    const auto slice = edges(graph, row);
5,253 ✔
845
    for (auto input = slice.first; !out && input < slice.first + slice.count;
14,864 ✔
846
        ++input)
847
    {
848
        each_rival(graph, input, [&](link_t other) NOEXCEPT
9,611 ✔
849
        {
850
            if (is_present(cell(graph, owner(graph, other))))
2,229 ✔
851
                out = true;
1,621 ✔
852
        });
2,229 ✔
853
    }
854

855
    return out;
5,253 ✔
856
}
857

858
constexpr bool algorithm::descended(const graph_t& graph, link_t row) NOEXCEPT
4,139 ✔
859
{
860
    const auto slice = edges(graph, row);
4,139 ✔
861
    for (auto input = slice.first; input < slice.first + slice.count; ++input)
10,067 ✔
862
    {
863
        const auto up = parent(graph, input);
7,391 ✔
864
        if (up != none && is_labeled(cell(graph, up)))
7,391 ✔
865
            return true;
866
    }
867

868
    return false;
869
}
870

871
constexpr size_t algorithm::index(const component_t& component,
98,646 ✔
872
    link_t row) NOEXCEPT
873
{
874
    for (size_t member{}; member < component.count; ++member)
2,153,035 ✔
875
        if (component.rows[member] == row)
2,099,963 ✔
876
            return member;
877

878
    return maximum_members;
879
}
880

881
constexpr algorithm::mask_t algorithm::losers(const component_t& component,
177 ✔
882
    size_t index) NOEXCEPT
883
{
884
    mask_t out{};
885
    for (size_t contest{}; contest < component.contests; ++contest)
531 ✔
886
    {
887
        const auto clique = component.cliques[contest];
354 ✔
888
        const auto size = ones_count(clique);
354 ✔
889
        const auto digit = index % size;
354 ✔
890
        index /= size;
354 ✔
891

892
        // The winner is the clique's digit-th set bit.
893
        auto winner = clique;
894
        for (size_t cleared{}; cleared < digit; ++cleared)
523 ✔
895
            winner &= sub1(winner);
169 ✔
896

897
        winner &= twos_complement(winner);
354 ✔
898
        out |= bit_and(clique, bit_not(winner));
354 ✔
899
    }
900

901
    return out;
177 ✔
902
}
903

904
template <typename Word>
905
constexpr size_t algorithm::best(const std::span<const mask_t>& outcomes,
19 ✔
906
    const component_t& component, const graph_t& graph, uint64_t rate,
907
    uint32_t bytes_per_sigop) NOEXCEPT
908
{
909
    size_t out{};
19 ✔
910
    uint64_t most{};
19 ✔
911
    uint64_t least{};
19 ✔
912
    auto first = true;
19 ✔
913
    each_fee<Word>(zero, outcomes, component, graph,
19 ✔
914
        [&](size_t index, uint64_t fee) NOEXCEPT
625 ✔
915
        {
916
            const auto size = is_zero(rate) ? zero : chargeable(
303 ✔
917
                outcomes[index], component, graph, bytes_per_sigop);
918

919
            if (first || worth(fee, size, most, least, rate))
303 ✔
920
            {
921
                first = false;
30 ✔
922
                most = fee;
30 ✔
923
                least = size;
30 ✔
924
                out = index;
30 ✔
925
            }
926
        });
927

928
    return out;
19 ✔
929
}
930

931
constexpr algorithm::mask_t algorithm::greedy(const component_t& component,
2 ✔
932
    const graph_t& graph, uint64_t rate, uint32_t bytes_per_sigop) NOEXCEPT
933
{
934
    mask_t lost{};
935
    for (size_t contest{}; contest < component.contests; ++contest)
6 ✔
936
    {
937
        mask_t winner{};
938
        uint64_t fee{};
939
        uint64_t size{};
940
        const auto clique = component.cliques[contest];
4 ✔
941
        for (size_t member{}; member < component.count; ++member)
24 ✔
942
        {
943
            if (!get_right(clique, member) || get_right(lost, member))
20 ✔
944
                continue;
12 ✔
945

946
            const auto row = totals(graph, component.rows[member]);
8 ✔
947
            const auto bytes = chargeable(row, bytes_per_sigop);
8 ✔
948
            if (is_zero(winner) || worth(row.fee, bytes, fee, size, rate))
8 ✔
949
            {
950
                winner = set_right(mask_t{}, member);
6 ✔
951
                fee = row.fee;
6 ✔
952
                size = bytes;
953
            }
954
        }
955

956
        lost |= bit_and(clique, bit_not(winner));
4 ✔
957
    }
958

959
    auto out = bit_and(unmask_right<mask_t>(component.count), bit_not(lost));
2 ✔
960
    for (size_t member{}; member < component.count; ++member)
12 ✔
961
        if (is_nonzero(bit_and(component.ancestors[member], lost)))
10 ✔
962
            out = set_right(out, member, false);
2 ✔
963

964
    return out;
2 ✔
965
}
966

967
constexpr bool algorithm::worth(uint64_t fee, uint64_t size,
292 ✔
968
    uint64_t other_fee, uint64_t other_size, uint64_t rate) NOEXCEPT
969
{
970
    // Fee less the rate on size, compared in satoshis per virtual kilobyte.
971
    const auto value = ceilinged_add(ceilinged_multiply(fee, 1'000_u64),
292 ✔
972
        ceilinged_multiply(rate, other_size));
973
    const auto other = ceilinged_add(ceilinged_multiply(other_fee, 1'000_u64),
292 ✔
974
        ceilinged_multiply(rate, size));
975
    return value > other;
292 ✔
976
}
977

978
inline void algorithm::discard(std::span<mark> marks, const graph_t& graph,
16 ✔
979
    link_t row) NOEXCEPT
980
{
981
    std::vector<link_t> pending{ row };
16 ✔
982
    marks[row] = mark::excluded;
16 ✔
983

984
    while (!pending.empty())
39 ✔
985
    {
986
        const auto next = pending.back();
23 ✔
987
        pending.pop_back();
23 ✔
988
        each_child(graph, next, [&](link_t down) NOEXCEPT
23 ✔
989
        {
990
            if (marks[down] != mark::excluded)
7 ✔
991
            {
992
                marks[down] = mark::excluded;
7 ✔
993
                pending.push_back(down);
7 ✔
994
            }
995
        });
7 ✔
996
    }
997
}
16 ✔
998

999
inline void algorithm::forfeit(std::span<mark> marks, const graph_t& graph,
1 ✔
1000
    link_t row) NOEXCEPT
1001
{
1002
    std::vector<link_t> found{ row };
1 ✔
1003
    const auto add = [&](link_t next) NOEXCEPT
8 ✔
1004
    {
1005
        if (std::ranges::find(found, next) == found.end())
8 ✔
1006
            found.push_back(next);
4 ✔
1007
    };
9 ✔
1008

1009
    for (size_t at{}; at < found.size(); ++at)
6 ✔
1010
    {
1011
        const auto member = found[at];
5 ✔
1012
        const auto slice = edges(graph, member);
5 ✔
1013
        for (auto input = slice.first; input < slice.first + slice.count;
11 ✔
1014
            ++input)
1015
        {
1016
            const auto up = parent(graph, input);
6 ✔
1017
            if (up != none && is_labeled(cell(graph, up)))
6 ✔
1018
                add(up);
2 ✔
1019

1020
            each_rival(graph, input, [&](link_t other) NOEXCEPT
6 ✔
1021
            {
1022
                const auto rival_row = owner(graph, other);
4 ✔
1023
                if (is_present(cell(graph, rival_row)))
4 ✔
1024
                    add(rival_row);
4 ✔
1025
            });
4 ✔
1026
        }
1027

1028
        each_child(graph, member, [&](link_t down) NOEXCEPT
5 ✔
1029
        {
1030
            if (is_present(cell(graph, down)))
2 ✔
1031
                add(down);
2 ✔
1032
        });
2 ✔
1033
    }
1034

1035
    for (const auto member: found)
6 ✔
1036
        discard(marks, graph, member);
5 ✔
1037
}
1 ✔
1038

1039
inline void algorithm::pack_(std::vector<link_t>& out, takes_t& takes,
33 ✔
1040
    std::span<mark> marks, const columns_t& columns, const totals_t& budget,
1041
    size_t depth, uint32_t bytes_per_sigop) NOEXCEPT
1042
{
1043
    struct score_t
1044
    {
1045
        link_t row{};
1046
        uint64_t rate{};
1047
        totals_t sum{};
1048
        std::vector<link_t> rows{};
1049
        bool closed{};
1050
    };
1051

1052
    const graph_t graph{ columns };
33 ✔
1053
    const auto count = columns.cells.size();
33 ✔
1054
    std::vector<score_t> scores{};
33 ✔
1055
    std::vector<link_t> rows{};
33 ✔
1056
    std::vector<link_t> group{};
33 ✔
1057
    std::vector<bool> seen{};
33 ✔
1058
    totals_t used{};
33 ✔
1059
    out.clear();
33 ✔
1060
    takes.clear();
33 ✔
1061

1062
    const auto fits = [](const totals_t& sum, const totals_t& space) NOEXCEPT
87 ✔
1063
    {
1064
        return sum.size <= space.size && sum.sigops <= space.sigops;
87 ✔
1065
    };
1066

1067
    const auto available = [&]() NOEXCEPT -> totals_t
246 ✔
1068
    {
1069
        return
1070
        {
1071
            {},
1072
            floored_subtract(budget.size, used.size),
246 ✔
1073
            floored_subtract(budget.sigops, used.sigops)
246 ✔
1074
        };
246 ✔
1075
    };
33 ✔
1076

1077
    // A row's chunk, as a candidate for the round.
1078
    const auto score_row = [&](link_t row) NOEXCEPT
92 ✔
1079
    {
1080
        totals_t sum{};
92 ✔
1081
        if (chunk(rows, sum, marks, graph, row, depth, available()))
92 ✔
1082
            scores.push_back({ row, fee_rate(sum, bytes_per_sigop), sum,
67 ✔
1083
                rows, false });
1084
    };
159 ✔
1085

1086
    for (auto taken = true; taken;)
109 ✔
1087
    {
1088
        taken = false;
1089
        scores.clear();
76 ✔
1090
        seen.assign(count, false);
76 ✔
1091
        for (size_t at{}; at < count; ++at)
320 ✔
1092
        {
1093
            const auto row = possible_narrow_cast<link_t>(at);
244 ✔
1094
            if (marks[row] != mark::unmarked || seen[row])
244 ✔
1095
                continue;
197 ✔
1096

1097
            // A cluster offers its best closure, or each row its chunk.
1098
            const auto whole = cluster(group, marks, graph, row);
68 ✔
1099
            for (const auto member: group)
191 ✔
1100
                seen[member] = true;
123 ✔
1101

1102
            totals_t sum{};
68 ✔
1103
            if (whole)
68 ✔
1104
                closure(rows, sum, graph, group, bytes_per_sigop);
66 ✔
1105

1106
            if (whole && fits(sum, available()))
66 ✔
1107
            {
1108
                scores.push_back({ rows.front(),
21 ✔
1109
                    fee_rate(sum, bytes_per_sigop), sum, rows, true });
21 ✔
1110
                continue;
21 ✔
1111
            }
1112

1113
            for (const auto member: group)
139 ✔
1114
                score_row(member);
92 ✔
1115
        }
1116

1117
        std::sort(scores.begin(), scores.end(),
76 ✔
1118
            [](const score_t& left, const score_t& right) NOEXCEPT
89 ✔
1119
            {
1120
                return left.rate == right.rate ? left.row < right.row :
89 ✔
1121
                    left.rate > right.rate;
89 ✔
1122
            });
1123

1124
        for (const auto& score: scores)
164 ✔
1125
        {
1126
            totals_t sum{};
88 ✔
1127
            const auto space = available();
88 ✔
1128
            const auto unmarked = [&](link_t row) NOEXCEPT
98 ✔
1129
            {
1130
                return marks[row] == mark::unmarked;
98 ✔
1131
            };
88 ✔
1132

1133
            if (score.closed)
88 ✔
1134
            {
1135
                if (!std::ranges::all_of(score.rows, unmarked) ||
21 ✔
1136
                    !fits(score.sum, space))
21 ✔
1137
                    continue;
43 ✔
1138

1139
                rows = score.rows;
19 ✔
1140
                sum = score.sum;
19 ✔
1141
            }
1142
            else if (!unmarked(score.row) ||
134 ✔
1143
                !chunk(rows, sum, marks, graph, score.row, depth, space) ||
93 ✔
1144
                rows.size() != score.rows.size() ||
119 ✔
1145
                sum.fee != score.sum.fee)
26 ✔
1146
            {
1147
                continue;
41 ✔
1148
            }
1149

1150
            for (const auto row: rows)
100 ✔
1151
                marks[row] = mark::taken;
55 ✔
1152

1153
            out.insert(out.end(), rows.begin(), rows.end());
45 ✔
1154
            takes.push_back({ score.rate, chargeable(sum, bytes_per_sigop) });
45 ✔
1155
            used.fee = ceilinged_add(used.fee, sum.fee);
45 ✔
1156
            used.size = ceilinged_add(used.size, sum.size);
45 ✔
1157
            used.sigops = ceilinged_add(used.sigops, sum.sigops);
45 ✔
1158
            taken = true;
1159
        }
1160
    }
1161

1162
    std::sort(out.begin(), out.end());
33 ✔
1163
}
54 ✔
1164

1165
template <typename Arrivals>
1166
inline bool algorithm::reaches(const projection_t& projection, size_t count,
457 ✔
1167
    uint64_t space, uint64_t rate, const Arrivals& arrivals) NOEXCEPT
1168
{
1169
    const auto& blocks = projection.blocks;
457 ✔
1170
    const auto arriving = arrivals(rate);
457 ✔
1171
    uint64_t carry{};
1172

1173
    // A block that leaves rows is full, so its takes are its capacity.
1174
    for (size_t block{}; block < count; ++block)
499 ✔
1175
    {
1176
        std::span<const take_t> takes{};
481 ✔
1177
        if (block < blocks.size())
481 ✔
1178
            takes = blocks[block];
415 ✔
1179

1180
        const auto last = add1(block) >= blocks.size();
481 ✔
1181
        const auto full = !takes.empty() && !(last && projection.exhausted);
481 ✔
1182
        const auto capacity = full ? above(takes, zero) : space;
390 ✔
1183
        const auto demand = ceilinged_add(carry, above(takes, rate));
481 ✔
1184
        if (demand < capacity)
481 ✔
1185
            return true;
439 ✔
1186

1187
        const auto excess = floored_subtract(demand, capacity);
42 ✔
1188
        carry = ceilinged_add(excess, arriving);
42 ✔
1189
    }
1190

1191
    return false;
1192
}
1193

1194
inline bool algorithm::chunk(std::vector<link_t>& out, totals_t& sum,
159 ✔
1195
    const std::span<const mark>& marks, const graph_t& graph, link_t row,
1196
    size_t depth, const totals_t& available) NOEXCEPT
1197
{
1198
    sum = {};
159 ✔
1199
    out.assign(one, row);
159 ✔
1200

1201
    // Each level holds the untaken parents of the previous level.
1202
    for (size_t level{}, begin{}; begin < out.size(); ++level)
390 ✔
1203
    {
1204
        const auto end = out.size();
1205
        for (auto at = begin; at < end; ++at)
464 ✔
1206
        {
1207
            const auto slice = edges(graph, out[at]);
233 ✔
1208
            for (auto input = slice.first;
464 ✔
1209
                input < slice.first + slice.count; ++input)
464 ✔
1210
            {
1211
                const auto up = parent(graph, input);
233 ✔
1212
                if (up == none || marks[up] == mark::taken ||
233 ✔
1213
                    is_boundary(cell(graph, up)))
76 ✔
1214
                    continue;
157 ✔
1215

1216
                if (marks[up] == mark::excluded)
76 ✔
1217
                    return false;
2 ✔
1218

1219
                if (std::ranges::find(out, up) != out.end())
74 ✔
1220
                    continue;
×
1221

1222
                if (level == depth)
74 ✔
1223
                    return false;
1224

1225
                out.push_back(up);
74 ✔
1226
            }
1227
        }
1228

1229
        begin = end;
1230
    }
1231

1232
    std::sort(out.begin(), out.end());
157 ✔
1233
    auto cut = out.begin();
157 ✔
1234
    for (; cut != out.end(); ++cut)
302 ✔
1235
    {
1236
        const auto& add = totals(graph, *cut);
223 ✔
1237
        const auto size = ceilinged_add(sum.size, add.size);
223 ✔
1238
        const auto sigops = ceilinged_add(sum.sigops, add.sigops);
223 ✔
1239
        if (size > available.size || sigops > available.sigops)
223 ✔
1240
            break;
1241

1242
        sum.fee = ceilinged_add(sum.fee, add.fee);
145 ✔
1243
        sum.size = size;
145 ✔
1244
        sum.sigops = sigops;
145 ✔
1245
    }
1246

1247
    out.erase(cut, out.end());
157 ✔
1248
    return !out.empty();
157 ✔
1249
}
1250

1251
inline bool algorithm::cluster(std::vector<link_t>& out,
68 ✔
1252
    const std::span<const mark>& marks, const graph_t& graph,
1253
    link_t row) NOEXCEPT
1254
{
1255
    out.assign(one, row);
68 ✔
1256
    auto whole = true;
1257
    const auto push = [&](link_t found) NOEXCEPT
146 ✔
1258
    {
1259
        if (marks[found] != mark::unmarked ||
146 ✔
1260
            std::ranges::find(out, found) != out.end())
110 ✔
1261
            return;
91 ✔
1262

1263
        out.push_back(found);
55 ✔
1264
    };
68 ✔
1265

1266
    for (size_t at{}; at < out.size(); ++at)
191 ✔
1267
    {
1268
        const auto member = out[at];
123 ✔
1269
        const auto slice = edges(graph, member);
123 ✔
1270
        for (auto input = slice.first; input < slice.first + slice.count;
246 ✔
1271
            ++input)
1272
        {
1273
            const auto up = parent(graph, input);
123 ✔
1274
            if (up == none || is_boundary(cell(graph, up)))
123 ✔
1275
                continue;
31 ✔
1276

1277
            if (marks[up] == mark::excluded)
92 ✔
1278
                whole = false;
1279
            else
1280
                push(up);
90 ✔
1281
        }
1282

1283
        each_child(graph, member, [&](link_t down) NOEXCEPT
123 ✔
1284
        {
1285
            push(down);
56 ✔
1286
        });
56 ✔
1287
    }
1288

1289
    return whole && out.size() <= maximum_members;
68 ✔
1290
}
1291

1292
// Dinkelbach: the maximum weight closure at the rate of the best closure
1293
// found (fee times its size less size times its fee, a minimum cut) is
1294
// positive until no closure has a higher rate.
1295
inline void algorithm::closure(std::vector<link_t>& out, totals_t& sum,
66 ✔
1296
    const graph_t& graph, const std::vector<link_t>& cluster,
1297
    uint32_t bytes_per_sigop) NOEXCEPT
1298
{
1299
    const auto count = cluster.size();
66 ✔
1300
    const auto source = count;
66 ✔
1301
    const auto sink = add1(count);
66 ✔
1302
    const auto nodes = count + two;
66 ✔
1303
    std::vector<uint64_t> fees(count);
66 ✔
1304
    std::vector<uint64_t> sizes(count);
66 ✔
1305
    std::vector<std::vector<size_t>> parents(count);
66 ✔
1306
    for (size_t node{}; node < count; ++node)
187 ✔
1307
    {
1308
        const auto& row = totals(graph, cluster[node]);
121 ✔
1309
        fees[node] = row.fee;
121 ✔
1310
        sizes[node] = chargeable(row, bytes_per_sigop);
121 ✔
1311

1312
        const auto slice = edges(graph, cluster[node]);
121 ✔
1313
        for (auto input = slice.first; input < slice.first + slice.count;
242 ✔
1314
            ++input)
1315
        {
1316
            const auto it = std::ranges::find(cluster, parent(graph, input));
121 ✔
1317
            if (it != cluster.end())
121 ✔
1318
                parents[node].push_back(std::distance(cluster.begin(), it));
55 ✔
1319
        }
1320
    }
1321

1322
    const auto weigh = [&](const std::vector<bool>& in, uint64_t& fee,
102 ✔
1323
        uint64_t& size) NOEXCEPT
1324
    {
1325
        fee = zero;
102 ✔
1326
        size = zero;
102 ✔
1327
        for (size_t node{}; node < count; ++node)
314 ✔
1328
        {
1329
            if (in[node])
212 ✔
1330
            {
1331
                fee = ceilinged_add(fee, fees[node]);
121 ✔
1332
                size = ceilinged_add(size, sizes[node]);
121 ✔
1333
            }
1334
        }
1335
    };
168 ✔
1336

1337
    std::vector<bool> best(count, true);
66 ✔
1338
    uint64_t fee{}, size{};
66 ✔
1339
    weigh(best, fee, size);
66 ✔
1340

1341
    std::vector<uint128_t> capacity(nodes * nodes);
66 ✔
1342
    std::vector<size_t> from(nodes);
66 ✔
1343
    std::vector<bool> reached(nodes);
66 ✔
1344
    std::vector<size_t> queue{};
66 ✔
1345
    const auto at = [&](size_t left, size_t right) NOEXCEPT -> uint128_t&
2,496 ✔
1346
    {
1347
        return capacity[left * nodes + right];
2,496 ✔
1348
    };
66 ✔
1349

1350
    // Reachability from the source in the residual, the path in from.
1351
    const auto search = [&]() NOEXCEPT
180 ✔
1352
    {
1353
        reached.assign(nodes, false);
180 ✔
1354
        reached[source] = true;
180 ✔
1355
        queue.assign(one, source);
180 ✔
1356
        for (size_t next{}; next < queue.size(); ++next)
885 ✔
1357
        {
1358
            const auto node = queue[next];
705 ✔
1359
            for (size_t other{}; other < nodes; ++other)
4,009 ✔
1360
            {
1361
                if (!reached[other] && at(node, other) != uint128_t{})
4,392 ✔
1362
                {
1363
                    reached[other] = true;
525 ✔
1364
                    from[other] = node;
525 ✔
1365
                    queue.push_back(other);
525 ✔
1366
                }
1367
            }
1368
        }
1369

1370
        return reached[sink];
180 ✔
1371
    };
66 ✔
1372

1373
    while (count > one && size > zero)
66 ✔
1374
    {
1375
        uint128_t infinite{ one };
36 ✔
1376
        std::ranges::fill(capacity, uint128_t{});
72 ✔
1377
        for (size_t node{}; node < count; ++node)
127 ✔
1378
        {
1379
            at(source, node) = uint128_t{ fees[node] } * size;
91 ✔
1380
            at(node, sink) = uint128_t{ sizes[node] } * fee;
91 ✔
1381
            infinite += at(source, node);
91 ✔
1382
        }
1383

1384
        for (size_t node{}; node < count; ++node)
127 ✔
1385
            for (const auto up: parents[node])
146 ✔
1386
                at(node, up) = infinite;
55 ✔
1387

1388
        while (search())
180 ✔
1389
        {
1390
            auto flow = infinite;
144 ✔
1391
            for (auto node = sink; node != source; node = from[node])
504 ✔
1392
                flow = std::min(flow, at(from[node], node));
360 ✔
1393

1394
            for (auto node = sink; node != source; node = from[node])
504 ✔
1395
            {
1396
                at(from[node], node) -= flow;
360 ✔
1397
                at(node, from[node]) += flow;
360 ✔
1398
            }
1399
        }
1400

1401
        const std::vector<bool> found(reached.begin(),
1402
            std::next(reached.begin(), count));
72 ✔
1403

1404
        uint64_t found_fee{}, found_size{};
36 ✔
1405
        weigh(found, found_fee, found_size);
36 ✔
1406
        if (is_zero(found_size) || uint128_t{ found_fee } * size <=
36 ✔
NEW
1407
            uint128_t{ found_size } * fee)
×
1408
            break;
1409

NEW
1410
        best = found;
×
NEW
1411
        fee = found_fee;
×
NEW
1412
        size = found_size;
×
1413
    }
36 ✔
1414

1415
    out.clear();
66 ✔
1416
    sum = {};
66 ✔
1417
    for (size_t node{}; node < count; ++node)
187 ✔
1418
    {
1419
        if (best[node])
121 ✔
1420
        {
1421
            const auto& add = totals(graph, cluster[node]);
121 ✔
1422
            out.push_back(cluster[node]);
121 ✔
1423
            sum.fee = ceilinged_add(sum.fee, add.fee);
121 ✔
1424
            sum.size = ceilinged_add(sum.size, add.size);
121 ✔
1425
            sum.sigops = ceilinged_add(sum.sigops, add.sigops);
121 ✔
1426
        }
1427
    }
1428

1429
    std::sort(out.begin(), out.end());
66 ✔
1430
}
66 ✔
1431

1432
inline algorithm::link_t algorithm::resolved(const graph_t& graph,
4,353 ✔
1433
    link_t row) NOEXCEPT
1434
{
1435
    const auto own = cell(graph, row);
4,353 ✔
1436
    if (is_boundary(own))
4,353 ✔
1437
        return own;
1438

1439
    auto next = reduced(own);
3,758 ✔
1440
    const auto slice = edges(graph, row);
3,758 ✔
1441
    for (auto input = slice.first; input < slice.first + slice.count; ++input)
12,026 ✔
1442
    {
1443
        const auto up = parent(graph, input);
8,268 ✔
1444
        if (up != none && is_absent(cell(graph, up)))
8,268 ✔
1445
            next = raised(next, ancestor);
2,206 ✔
1446

1447
        each_rival(graph, input, [&](link_t other) NOEXCEPT
8,268 ✔
1448
        {
1449
            if (is_boundary(cell(graph, owner(graph, other))))
1,557 ✔
1450
                next = raised(next, rivaled);
488 ✔
1451
        });
1,557 ✔
1452
    }
1453

1454
    return next;
3,758 ✔
1455
}
1456

1457
// The children of a row depend on its absence, and its rivals on its
1458
// confirmation. A labeled row that leaves its component leaves the rest of it
1459
// to relabel, and a row made present joins one.
1460
inline void algorithm::change(walk_t& walk, const columns_t& columns,
7,159 ✔
1461
    link_t row, link_t next) NOEXCEPT
1462
{
1463
    const graph_t graph{ columns };
7,159 ✔
1464
    const auto own = cell(graph, row);
7,159 ✔
1465
    if (next == own)
7,159 ✔
1466
        return;
5,462 ✔
1467

1468
    if (is_labeled(own) && !is_present(next))
5,153 ✔
1469
    {
1470
        component_t former{};
1,290 ✔
1471
        if (collect(former, graph, row))
1,290 ✔
1472
            walk.affected.insert(walk.affected.end(), former.rows.cbegin(),
960 ✔
1473
                std::next(former.rows.cbegin(), former.count));
960 ✔
1474
        else
1475
            walk.complete = false;
330 ✔
1476
    }
1477

1478
    set_cell(graph, row, next);
5,153 ✔
1479
    if (is_present(next) && !is_present(own))
5,153 ✔
1480
        walk.affected.push_back(row);
1,787 ✔
1481

1482
    if (is_absent(next) != is_absent(own))
5,153 ✔
1483
    {
1484
        each_child(graph, row, [&](link_t down) NOEXCEPT
3,333 ✔
1485
        {
1486
            walk.pending.push_back(down);
3,094 ✔
1487
        });
3,094 ✔
1488
    }
1489

1490
    if (is_boundary(next) == is_boundary(own))
5,153 ✔
1491
        return;
1492

1493
    const auto slice = edges(graph, row);
1,697 ✔
1494
    for (auto input = slice.first; input < slice.first + slice.count; ++input)
5,040 ✔
1495
    {
1496
        each_rival(graph, input, [&](link_t other) NOEXCEPT
3,343 ✔
1497
        {
1498
            walk.pending.push_back(owner(graph, other));
598 ✔
1499
        });
598 ✔
1500
    }
1501
}
1502

1503
inline bool algorithm::spread(walk_t& walk, const columns_t& columns) NOEXCEPT
265 ✔
1504
{
1505
    const graph_t graph{ columns };
265 ✔
1506
    while (!walk.pending.empty())
4,618 ✔
1507
    {
1508
        const auto row = walk.pending.back();
4,353 ✔
1509
        walk.pending.pop_back();
4,353 ✔
1510
        change(walk, columns, row, resolved(graph, row));
4,353 ✔
1511
    }
1512

1513
    return reform(columns, walk.affected) && walk.complete;
265 ✔
1514
}
1515

1516
inline bool algorithm::reform(const columns_t& columns,
265 ✔
1517
    const std::span<const link_t>& rows) NOEXCEPT
1518
{
1519
    const graph_t graph{ columns };
265 ✔
1520
    for (const auto row: rows)
10,140 ✔
1521
        if (is_present(cell(graph, row)))
9,875 ✔
1522
            set_cell(graph, row, unlabeled);
6,975 ✔
1523

1524
    // Relevance closes over the rows in at most count passes.
1525
    for (auto changed = true; changed;)
730 ✔
1526
    {
1527
        changed = false;
1528
        for (const auto row: rows)
19,932 ✔
1529
        {
1530
            if (!is_present(cell(graph, row)) || is_labeled(cell(graph, row)))
19,467 ✔
1531
                continue;
14,217 ✔
1532

1533
            if (contested(graph, row) || descended(graph, row))
5,250 ✔
1534
            {
1535
                set_cell(graph, row, row);
2,575 ✔
1536
                changed = true;
1537
            }
1538
        }
1539
    }
1540

1541
    auto complete = true;
1542
    for (const auto row: rows)
10,140 ✔
1543
    {
1544
        // A row relabeled by a previous component carries a lower label.
1545
        if (cell(graph, row) != row)
9,875 ✔
1546
            continue;
8,984 ✔
1547

1548
        component_t component{};
891 ✔
1549
        if (collect(component, graph, row))
891 ✔
1550
            relabel(columns, component);
644 ✔
1551
        else
1552
            complete = false;
1553
    }
1554

1555
    return complete;
265 ✔
1556
}
1557

1558
template <typename Word>
1559
INLINE constexpr Word algorithm::fees(Word outcomes,
1560
    const component_t& component, const graph_t& graph) NOEXCEPT
1561
{
1562
    constexpr auto lane = bits<mask_t>;
1563
    auto sum = f::broadcast<Word>(mask_t{});
1564
    for (size_t member{}; member < component.count; ++member)
2,694 ✔
1565
    {
1566
        const auto bit = f::broadcast<Word>(set_right(mask_t{}, member));
2,245 ✔
1567
        const auto& total = totals(graph, component.rows[member]);
2,245 ✔
1568
        const auto fee = f::broadcast<Word>(total.fee);
2,245 ✔
1569
        const auto selected = f::eq<lane>(f::and_(outcomes, bit), bit);
1570
        sum = f::add<lane>(sum, f::and_(selected, fee));
1571
    }
1572

1573
    return sum;
1574
}
1575

1576
template <typename Word, typename Visitor>
1577
constexpr void algorithm::each_fee(size_t index,
45 ✔
1578
    const std::span<const mask_t>& outcomes, const component_t& component,
1579
    const graph_t& graph, const Visitor& visit) NOEXCEPT
1580
{
1581
    const auto count = outcomes.size();
27 ✔
1582
    if constexpr (is_extended<Word>)
1583
    {
1584
        if constexpr (have<Word>)
1585
        {
1586
            constexpr auto lanes = mask_lanes<Word>;
1587
            aligned_array<uint64_t, lanes> sums{};
1588
            for (; index + lanes <= count; index += lanes)
1589
            {
1590
                const auto word = load<Word>(&outcomes[index]);
1591
                store(sums.data(), fees<Word>(word, component, graph));
1592

1593
                for (size_t lane{}; lane < lanes; ++lane)
1594
                    visit(index + lane, sums[lane]);
1595
            }
1596
        }
1597

1598
        using next = narrower<Word, mask_t>;
1599
        each_fee<next>(index, outcomes, component, graph, visit);
18 ✔
1600
    }
1601
    else
1602
    {
1603
        for (; index < count; ++index)
476 ✔
1604
            visit(index, fees<mask_t>(outcomes[index], component, graph));
898 ✔
1605
    }
1606
}
45 ✔
1607

1608
template <typename Word>
1609
INLINE constexpr Word algorithm::native(Word word) NOEXCEPT
1610
{
1611
    if constexpr (is_little_endian)
1612
        return word;
1613
    else
1614
        return f::byteswap<link_t>(word);
1615
}
1616

1617
template <typename Word>
1618
constexpr bool algorithm::collect_(size_t index, component_t& out,
15 ✔
1619
    link_t label, const std::span<const link_t>& cells) NOEXCEPT
1620
{
1621
    const auto count = cells.size();
9 ✔
1622
    const auto stored = to_column(label);
9 ✔
1623
    const auto add = [&](size_t row) NOEXCEPT
241 ✔
1624
    {
1625
        if (out.count == maximum_members)
226 ✔
1626
            return false;
1627

1628
        out.rows[out.count++] = possible_narrow_cast<link_t>(row);
225 ✔
1629
        return true;
225 ✔
1630
    };
1631

1632
    if constexpr (is_extended<Word>)
1633
    {
1634
        if constexpr (have<Word>)
1635
        {
1636
            constexpr auto lanes = link_lanes<Word>;
1637
            const auto wanted = f::broadcast<Word>(stored);
1638
            for (; index + lanes <= count; index += lanes)
1639
            {
1640
                const auto word = load<Word>(&cells[index]);
1641
                const auto found = f::eq<bits<link_t>>(word, wanted);
1642

1643
                if (f::any(found))
1644
                    for (auto row = index; row < index + lanes; ++row)
1645
                        if (cells[row] == stored && !add(row))
1646
                            return false;
1647
            }
1648
        }
1649

1650
        return collect_<narrower<Word, link_t>>(index, out, label, cells);
6 ✔
1651
    }
1652
    else
1653
    {
1654
        for (; index < count; ++index)
557 ✔
1655
            if (cells[index] == stored && !add(index))
549 ✔
1656
                return false;
1657

1658
        return true;
1659
    }
1660
}
1661

1662
template <typename Word>
1663
inline void algorithm::find_(size_t index, std::vector<link_t>& out,
13 ✔
1664
    const std::span<const link_t>& values, link_t value) NOEXCEPT
1665
{
1666
    const auto count = values.size();
7 ✔
1667
    const auto stored = to_column(value);
7 ✔
1668
    if constexpr (is_extended<Word>)
1669
    {
1670
        if constexpr (have<Word>)
1671
        {
1672
            constexpr auto lanes = link_lanes<Word>;
1673
            const auto wanted = f::broadcast<Word>(stored);
1674
            for (; index + lanes <= count; index += lanes)
1675
            {
1676
                const auto word = load<Word>(&values[index]);
1677
                const auto found = f::eq<bits<link_t>>(word, wanted);
1678

1679
                if (f::any(found))
1680
                    for (auto row = index; row < index + lanes; ++row)
1681
                        if (values[row] == stored)
1682
                            out.push_back(possible_narrow_cast<link_t>(row));
1683
            }
1684
        }
1685

1686
        find_<narrower<Word, link_t>>(index, out, values, value);
6 ✔
1687
    }
1688
    else
1689
    {
1690
        for (; index < count; ++index)
298 ✔
1691
            if (values[index] == stored)
291 ✔
1692
                out.push_back(possible_narrow_cast<link_t>(index));
71 ✔
1693
    }
1694
}
13 ✔
1695

1696
template <typename Word, typename Integral>
1697
INLINE constexpr Word algorithm::load(const Integral* at) NOEXCEPT
1698
{
1699
    if constexpr (is_extended<Word>)
1700
        return f::load<Word>(pointer_cast<const uint8_t>(at));
1701
    else
1702
        return *at;
1703
}
1704

1705
template <typename Word, typename Integral>
1706
INLINE constexpr void algorithm::store(Integral* at, Word word) NOEXCEPT
1707
{
1708
    if constexpr (is_extended<Word>)
1709
        f::store(pointer_cast<uint8_t>(at), word);
1710
    else
1711
        *at = word;
1712
}
1713

1714
BC_POP_WARNING()
1715
BC_POP_WARNING()
1716
BC_POP_WARNING()
1717
BC_POP_WARNING()
1718

1719
} // namespace pool
1720
} // namespace system
1721
} // namespace libbitcoin
1722

1723
#endif
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