Bitcoin Core 29.99.0
P2P Digital Currency
cluster_linearize.h
Go to the documentation of this file.
1// Copyright (c) The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_CLUSTER_LINEARIZE_H
6#define BITCOIN_CLUSTER_LINEARIZE_H
7
8#include <algorithm>
9#include <numeric>
10#include <optional>
11#include <stdint.h>
12#include <vector>
13#include <utility>
14
15#include <random.h>
16#include <span.h>
17#include <util/feefrac.h>
18#include <util/vecdeque.h>
19
21
23using DepGraphIndex = uint32_t;
24
27template<typename SetType>
29{
31 struct Entry
32 {
36 SetType ancestors;
38 SetType descendants;
39
41 friend bool operator==(const Entry&, const Entry&) noexcept = default;
42
44 Entry() noexcept = default;
46 Entry(const FeeFrac& f, const SetType& a, const SetType& d) noexcept : feerate(f), ancestors(a), descendants(d) {}
47 };
48
50 std::vector<Entry> entries;
51
53 SetType m_used;
54
55public:
57 friend bool operator==(const DepGraph& a, const DepGraph& b) noexcept
58 {
59 if (a.m_used != b.m_used) return false;
60 // Only compare the used positions within the entries vector.
61 for (auto idx : a.m_used) {
62 if (a.entries[idx] != b.entries[idx]) return false;
63 }
64 return true;
65 }
66
67 // Default constructors.
68 DepGraph() noexcept = default;
69 DepGraph(const DepGraph&) noexcept = default;
70 DepGraph(DepGraph&&) noexcept = default;
71 DepGraph& operator=(const DepGraph&) noexcept = default;
72 DepGraph& operator=(DepGraph&&) noexcept = default;
73
89 DepGraph(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> mapping, DepGraphIndex pos_range) noexcept : entries(pos_range)
90 {
91 Assume(mapping.size() == depgraph.PositionRange());
92 Assume((pos_range == 0) == (depgraph.TxCount() == 0));
93 for (DepGraphIndex i : depgraph.Positions()) {
94 auto new_idx = mapping[i];
95 Assume(new_idx < pos_range);
96 // Add transaction.
97 entries[new_idx].ancestors = SetType::Singleton(new_idx);
98 entries[new_idx].descendants = SetType::Singleton(new_idx);
99 m_used.Set(new_idx);
100 // Fill in fee and size.
101 entries[new_idx].feerate = depgraph.entries[i].feerate;
102 }
103 for (DepGraphIndex i : depgraph.Positions()) {
104 // Fill in dependencies by mapping direct parents.
105 SetType parents;
106 for (auto j : depgraph.GetReducedParents(i)) parents.Set(mapping[j]);
107 AddDependencies(parents, mapping[i]);
108 }
109 // Verify that the provided pos_range was correct (no unused positions at the end).
110 Assume(m_used.None() ? (pos_range == 0) : (pos_range == m_used.Last() + 1));
111 }
112
114 const SetType& Positions() const noexcept { return m_used; }
116 DepGraphIndex PositionRange() const noexcept { return entries.size(); }
118 auto TxCount() const noexcept { return m_used.Count(); }
120 const FeeFrac& FeeRate(DepGraphIndex i) const noexcept { return entries[i].feerate; }
122 FeeFrac& FeeRate(DepGraphIndex i) noexcept { return entries[i].feerate; }
124 const SetType& Ancestors(DepGraphIndex i) const noexcept { return entries[i].ancestors; }
126 const SetType& Descendants(DepGraphIndex i) const noexcept { return entries[i].descendants; }
127
133 DepGraphIndex AddTransaction(const FeeFrac& feefrac) noexcept
134 {
135 static constexpr auto ALL_POSITIONS = SetType::Fill(SetType::Size());
136 auto available = ALL_POSITIONS - m_used;
137 Assume(available.Any());
138 DepGraphIndex new_idx = available.First();
139 if (new_idx == entries.size()) {
140 entries.emplace_back(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx));
141 } else {
142 entries[new_idx] = Entry(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx));
143 }
144 m_used.Set(new_idx);
145 return new_idx;
146 }
147
157 void RemoveTransactions(const SetType& del) noexcept
158 {
159 m_used -= del;
160 // Remove now-unused trailing entries.
161 while (!entries.empty() && !m_used[entries.size() - 1]) {
162 entries.pop_back();
163 }
164 // Remove the deleted transactions from ancestors/descendants of other transactions. Note
165 // that the deleted positions will retain old feerate and dependency information. This does
166 // not matter as they will be overwritten by AddTransaction if they get used again.
167 for (auto& entry : entries) {
168 entry.ancestors &= m_used;
169 entry.descendants &= m_used;
170 }
171 }
172
177 void AddDependencies(const SetType& parents, DepGraphIndex child) noexcept
178 {
179 Assume(m_used[child]);
180 Assume(parents.IsSubsetOf(m_used));
181 // Compute the ancestors of parents that are not already ancestors of child.
182 SetType par_anc;
183 for (auto par : parents - Ancestors(child)) {
184 par_anc |= Ancestors(par);
185 }
186 par_anc -= Ancestors(child);
187 // Bail out if there are no such ancestors.
188 if (par_anc.None()) return;
189 // To each such ancestor, add as descendants the descendants of the child.
190 const auto& chl_des = entries[child].descendants;
191 for (auto anc_of_par : par_anc) {
192 entries[anc_of_par].descendants |= chl_des;
193 }
194 // To each descendant of the child, add those ancestors.
195 for (auto dec_of_chl : Descendants(child)) {
196 entries[dec_of_chl].ancestors |= par_anc;
197 }
198 }
199
208 SetType GetReducedParents(DepGraphIndex i) const noexcept
209 {
210 SetType parents = Ancestors(i);
211 parents.Reset(i);
212 for (auto parent : parents) {
213 if (parents[parent]) {
214 parents -= Ancestors(parent);
215 parents.Set(parent);
216 }
217 }
218 return parents;
219 }
220
229 SetType GetReducedChildren(DepGraphIndex i) const noexcept
230 {
231 SetType children = Descendants(i);
232 children.Reset(i);
233 for (auto child : children) {
234 if (children[child]) {
235 children -= Descendants(child);
236 children.Set(child);
237 }
238 }
239 return children;
240 }
241
246 FeeFrac FeeRate(const SetType& elems) const noexcept
247 {
248 FeeFrac ret;
249 for (auto pos : elems) ret += entries[pos].feerate;
250 return ret;
251 }
252
265 SetType FindConnectedComponent(const SetType& todo) const noexcept
266 {
267 if (todo.None()) return todo;
268 auto to_add = SetType::Singleton(todo.First());
269 SetType ret;
270 do {
271 SetType old = ret;
272 for (auto add : to_add) {
273 ret |= Descendants(add);
274 ret |= Ancestors(add);
275 }
276 ret &= todo;
277 to_add = ret - old;
278 } while (to_add.Any());
279 return ret;
280 }
281
286 bool IsConnected(const SetType& subset) const noexcept
287 {
288 return FindConnectedComponent(subset) == subset;
289 }
290
295 bool IsConnected() const noexcept { return IsConnected(m_used); }
296
301 void AppendTopo(std::vector<DepGraphIndex>& list, const SetType& select) const noexcept
302 {
303 DepGraphIndex old_len = list.size();
304 for (auto i : select) list.push_back(i);
305 std::sort(list.begin() + old_len, list.end(), [&](DepGraphIndex a, DepGraphIndex b) noexcept {
306 const auto a_anc_count = entries[a].ancestors.Count();
307 const auto b_anc_count = entries[b].ancestors.Count();
308 if (a_anc_count != b_anc_count) return a_anc_count < b_anc_count;
309 return a < b;
310 });
311 }
312
314 bool IsAcyclic() const noexcept
315 {
316 for (auto i : Positions()) {
317 if ((Ancestors(i) & Descendants(i)) != SetType::Singleton(i)) {
318 return false;
319 }
320 }
321 return true;
322 }
323};
324
326template<typename SetType>
328{
333
335 SetInfo() noexcept = default;
336
338 SetInfo(const SetType& txn, const FeeFrac& fr) noexcept : transactions(txn), feerate(fr) {}
339
341 explicit SetInfo(const DepGraph<SetType>& depgraph, DepGraphIndex pos) noexcept :
342 transactions(SetType::Singleton(pos)), feerate(depgraph.FeeRate(pos)) {}
343
345 explicit SetInfo(const DepGraph<SetType>& depgraph, const SetType& txn) noexcept :
346 transactions(txn), feerate(depgraph.FeeRate(txn)) {}
347
349 void Set(const DepGraph<SetType>& depgraph, DepGraphIndex pos) noexcept
350 {
351 Assume(!transactions[pos]);
352 transactions.Set(pos);
353 feerate += depgraph.FeeRate(pos);
354 }
355
357 SetInfo& operator|=(const SetInfo& other) noexcept
358 {
359 Assume(!transactions.Overlaps(other.transactions));
360 transactions |= other.transactions;
361 feerate += other.feerate;
362 return *this;
363 }
364
367 [[nodiscard]] SetInfo Add(const DepGraph<SetType>& depgraph, const SetType& txn) const noexcept
368 {
369 return {transactions | txn, feerate + depgraph.FeeRate(txn - transactions)};
370 }
371
373 friend void swap(SetInfo& a, SetInfo& b) noexcept
374 {
375 swap(a.transactions, b.transactions);
376 swap(a.feerate, b.feerate);
377 }
378
380 friend bool operator==(const SetInfo&, const SetInfo&) noexcept = default;
381};
382
384template<typename SetType>
385std::vector<FeeFrac> ChunkLinearization(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> linearization) noexcept
386{
387 std::vector<FeeFrac> ret;
388 for (DepGraphIndex i : linearization) {
390 auto new_chunk = depgraph.FeeRate(i);
391 // As long as the new chunk has a higher feerate than the last chunk so far, absorb it.
392 while (!ret.empty() && new_chunk >> ret.back()) {
393 new_chunk += ret.back();
394 ret.pop_back();
395 }
396 // Actually move that new chunk into the chunking.
397 ret.push_back(std::move(new_chunk));
398 }
399 return ret;
400}
401
403template<typename SetType>
405{
408
410 std::span<const DepGraphIndex> m_linearization;
411
413 std::vector<SetInfo<SetType>> m_chunks;
414
417
419 SetType m_todo;
420
422 void BuildChunks() noexcept
423 {
424 // Caller must clear m_chunks.
425 Assume(m_chunks.empty());
426
427 // Chop off the initial part of m_linearization that is already done.
428 while (!m_linearization.empty() && !m_todo[m_linearization.front()]) {
429 m_linearization = m_linearization.subspan(1);
430 }
431
432 // Iterate over the remaining entries in m_linearization. This is effectively the same
433 // algorithm as ChunkLinearization, but supports skipping parts of the linearization and
434 // keeps track of the sets themselves instead of just their feerates.
435 for (auto idx : m_linearization) {
436 if (!m_todo[idx]) continue;
437 // Start with an initial chunk containing just element idx.
438 SetInfo add(m_depgraph, idx);
439 // Absorb existing final chunks into add while they have lower feerate.
440 while (!m_chunks.empty() && add.feerate >> m_chunks.back().feerate) {
441 add |= m_chunks.back();
442 m_chunks.pop_back();
443 }
444 // Remember new chunk.
445 m_chunks.push_back(std::move(add));
446 }
447 }
448
449public:
451 explicit LinearizationChunking(const DepGraph<SetType>& depgraph LIFETIMEBOUND, std::span<const DepGraphIndex> lin LIFETIMEBOUND) noexcept :
452 m_depgraph(depgraph), m_linearization(lin)
453 {
454 // Mark everything in lin as todo still.
455 for (auto i : m_linearization) m_todo.Set(i);
456 // Compute the initial chunking.
457 m_chunks.reserve(depgraph.TxCount());
458 BuildChunks();
459 }
460
462 DepGraphIndex NumChunksLeft() const noexcept { return m_chunks.size() - m_chunks_skip; }
463
465 const SetInfo<SetType>& GetChunk(DepGraphIndex n) const noexcept
466 {
467 Assume(n + m_chunks_skip < m_chunks.size());
468 return m_chunks[n + m_chunks_skip];
469 }
470
472 void MarkDone(SetType subset) noexcept
473 {
474 Assume(subset.Any());
475 Assume(subset.IsSubsetOf(m_todo));
476 m_todo -= subset;
477 if (GetChunk(0).transactions == subset) {
478 // If the newly done transactions exactly match the first chunk of the remainder of
479 // the linearization, we do not need to rechunk; just remember to skip one
480 // additional chunk.
482 // With subset marked done, some prefix of m_linearization will be done now. How long
483 // that prefix is depends on how many done elements were interspersed with subset,
484 // but at least as many transactions as there are in subset.
485 m_linearization = m_linearization.subspan(subset.Count());
486 } else {
487 // Otherwise rechunk what remains of m_linearization.
488 m_chunks.clear();
489 m_chunks_skip = 0;
490 BuildChunks();
491 }
492 }
493
504 {
505 Assume(subset.transactions.IsSubsetOf(m_todo));
506 SetInfo<SetType> accumulator;
507 // Iterate over all chunks of the remaining linearization.
508 for (DepGraphIndex i = 0; i < NumChunksLeft(); ++i) {
509 // Find what (if any) intersection the chunk has with subset.
510 const SetType to_add = GetChunk(i).transactions & subset.transactions;
511 if (to_add.Any()) {
512 // If adding that to accumulator makes us hit all of subset, we are done as no
513 // shorter intersection with higher/equal feerate exists.
514 accumulator.transactions |= to_add;
515 if (accumulator.transactions == subset.transactions) break;
516 // Otherwise update the accumulator feerate.
517 accumulator.feerate += m_depgraph.FeeRate(to_add);
518 // If that does result in something better, or something with the same feerate but
519 // smaller, return that. Even if a longer, higher-feerate intersection exists, it
520 // does not hurt to return the shorter one (the remainder of the longer intersection
521 // will generally be found in the next call to Intersect, but even if not, it is not
522 // required for the improvement guarantee this function makes).
523 if (!(accumulator.feerate << subset.feerate)) return accumulator;
524 }
525 }
526 return subset;
527 }
528};
529
539template<typename SetType>
541{
545 SetType m_todo;
547 std::vector<FeeFrac> m_ancestor_set_feerates;
548
549public:
555 m_depgraph(depgraph),
556 m_todo{depgraph.Positions()},
557 m_ancestor_set_feerates(depgraph.PositionRange())
558 {
559 // Precompute ancestor-set feerates.
560 for (DepGraphIndex i : m_depgraph.Positions()) {
562 SetType anc_to_add = m_depgraph.Ancestors(i);
563 FeeFrac anc_feerate;
564 // Reuse accumulated feerate from first ancestor, if usable.
565 Assume(anc_to_add.Any());
566 DepGraphIndex first = anc_to_add.First();
567 if (first < i) {
568 anc_feerate = m_ancestor_set_feerates[first];
569 Assume(!anc_feerate.IsEmpty());
570 anc_to_add -= m_depgraph.Ancestors(first);
571 }
572 // Add in other ancestors (which necessarily include i itself).
573 Assume(anc_to_add[i]);
574 anc_feerate += m_depgraph.FeeRate(anc_to_add);
575 // Store the result.
576 m_ancestor_set_feerates[i] = anc_feerate;
577 }
578 }
579
586 void MarkDone(SetType select) noexcept
587 {
588 Assume(select.Any());
589 Assume(select.IsSubsetOf(m_todo));
590 m_todo -= select;
591 for (auto i : select) {
592 auto feerate = m_depgraph.FeeRate(i);
593 for (auto j : m_depgraph.Descendants(i) & m_todo) {
594 m_ancestor_set_feerates[j] -= feerate;
595 }
596 }
597 }
598
600 bool AllDone() const noexcept
601 {
602 return m_todo.None();
603 }
604
607 {
608 return m_todo.Count();
609 }
610
617 {
618 Assume(!AllDone());
619 std::optional<DepGraphIndex> best;
620 for (auto i : m_todo) {
621 if (best.has_value()) {
622 Assume(!m_ancestor_set_feerates[i].IsEmpty());
623 if (!(m_ancestor_set_feerates[i] > m_ancestor_set_feerates[*best])) continue;
624 }
625 best = i;
626 }
627 Assume(best.has_value());
628 return {m_depgraph.Ancestors(*best) & m_todo, m_ancestor_set_feerates[*best]};
629 }
630};
631
641template<typename SetType>
643{
647 std::vector<DepGraphIndex> m_sorted_to_original;
649 std::vector<DepGraphIndex> m_original_to_sorted;
654 SetType m_todo;
655
657 SetType SortedToOriginal(const SetType& arg) const noexcept
658 {
659 SetType ret;
660 for (auto pos : arg) ret.Set(m_sorted_to_original[pos]);
661 return ret;
662 }
663
665 SetType OriginalToSorted(const SetType& arg) const noexcept
666 {
667 SetType ret;
668 for (auto pos : arg) ret.Set(m_original_to_sorted[pos]);
669 return ret;
670 }
671
672public:
680 SearchCandidateFinder(const DepGraph<SetType>& depgraph, uint64_t rng_seed) noexcept :
681 m_rng(rng_seed),
682 m_sorted_to_original(depgraph.TxCount()),
683 m_original_to_sorted(depgraph.PositionRange())
684 {
685 // Determine reordering mapping, by sorting by decreasing feerate. Unused positions are
686 // not included, as they will never be looked up anyway.
687 DepGraphIndex sorted_pos{0};
688 for (auto i : depgraph.Positions()) {
689 m_sorted_to_original[sorted_pos++] = i;
690 }
691 std::sort(m_sorted_to_original.begin(), m_sorted_to_original.end(), [&](auto a, auto b) {
692 auto feerate_cmp = depgraph.FeeRate(a) <=> depgraph.FeeRate(b);
693 if (feerate_cmp == 0) return a < b;
694 return feerate_cmp > 0;
695 });
696 // Compute reverse mapping.
697 for (DepGraphIndex i = 0; i < m_sorted_to_original.size(); ++i) {
699 }
700 // Compute reordered dependency graph.
702 m_todo = m_sorted_depgraph.Positions();
703 }
704
706 bool AllDone() const noexcept
707 {
708 return m_todo.None();
709 }
710
728 std::pair<SetInfo<SetType>, uint64_t> FindCandidateSet(uint64_t max_iterations, SetInfo<SetType> best) noexcept
729 {
730 Assume(!AllDone());
731
732 // Convert the provided best to internal sorted indices.
733 best.transactions = OriginalToSorted(best.transactions);
734
736 struct WorkItem
737 {
744 SetType und;
751 FeeFrac pot_feerate;
752
754 WorkItem(SetInfo<SetType>&& i, SetType&& u, FeeFrac&& p_f) noexcept :
755 inc(std::move(i)), und(std::move(u)), pot_feerate(std::move(p_f))
756 {
757 Assume(pot_feerate.IsEmpty() == inc.feerate.IsEmpty());
758 }
759
761 void Swap(WorkItem& other) noexcept
762 {
763 swap(inc, other.inc);
764 swap(und, other.und);
765 swap(pot_feerate, other.pot_feerate);
766 }
767 };
768
770 VecDeque<WorkItem> queue;
771 queue.reserve(std::max<size_t>(256, 2 * m_todo.Count()));
772
773 // Create initial entries per connected component of m_todo. While clusters themselves are
774 // generally connected, this is not necessarily true after some parts have already been
775 // removed from m_todo. Without this, effort can be wasted on searching "inc" sets that
776 // span multiple components.
777 auto to_cover = m_todo;
778 do {
779 auto component = m_sorted_depgraph.FindConnectedComponent(to_cover);
780 to_cover -= component;
781 // If best is not provided, set it to the first component, so that during the work
782 // processing loop below, and during the add_fn/split_fn calls, we do not need to deal
783 // with the best=empty case.
784 if (best.feerate.IsEmpty()) best = SetInfo(m_sorted_depgraph, component);
785 queue.emplace_back(/*inc=*/SetInfo<SetType>{},
786 /*und=*/std::move(component),
787 /*pot_feerate=*/FeeFrac{});
788 } while (to_cover.Any());
789
791 uint64_t iterations_left = max_iterations;
792
794 SetType imp = m_todo;
795 while (imp.Any()) {
796 DepGraphIndex check = imp.Last();
797 if (m_sorted_depgraph.FeeRate(check) >> best.feerate) break;
798 imp.Reset(check);
799 }
800
808 auto add_fn = [&](SetInfo<SetType> inc, SetType und) noexcept {
811 auto pot = inc;
812 if (!inc.feerate.IsEmpty()) {
813 // Add entries to pot. We iterate over all undecided transactions whose feerate is
814 // higher than best. While undecided transactions of lower feerate may improve pot,
815 // the resulting pot feerate cannot possibly exceed best's (and this item will be
816 // skipped in split_fn anyway).
817 for (auto pos : imp & und) {
818 // Determine if adding transaction pos to pot (ignoring topology) would improve
819 // it. If not, we're done updating pot. This relies on the fact that
820 // m_sorted_depgraph, and thus the transactions iterated over, are in decreasing
821 // individual feerate order.
822 if (!(m_sorted_depgraph.FeeRate(pos) >> pot.feerate)) break;
823 pot.Set(m_sorted_depgraph, pos);
824 }
825
826 // The "jump ahead" optimization: whenever pot has a topologically-valid subset,
827 // that subset can be added to inc. Any subset of (pot - inc) has the property that
828 // its feerate exceeds that of any set compatible with this work item (superset of
829 // inc, subset of (inc | und)). Thus, if T is a topological subset of pot, and B is
830 // the best topologically-valid set compatible with this work item, and (T - B) is
831 // non-empty, then (T | B) is better than B and also topological. This is in
832 // contradiction with the assumption that B is best. Thus, (T - B) must be empty,
833 // or T must be a subset of B.
834 //
835 // See https://delvingbitcoin.org/t/how-to-linearize-your-cluster/303 section 2.4.
836 const auto init_inc = inc.transactions;
837 for (auto pos : pot.transactions - inc.transactions) {
838 // If the transaction's ancestors are a subset of pot, we can add it together
839 // with its ancestors to inc. Just update the transactions here; the feerate
840 // update happens below.
841 auto anc_todo = m_sorted_depgraph.Ancestors(pos) & m_todo;
842 if (anc_todo.IsSubsetOf(pot.transactions)) inc.transactions |= anc_todo;
843 }
844 // Finally update und and inc's feerate to account for the added transactions.
845 und -= inc.transactions;
846 inc.feerate += m_sorted_depgraph.FeeRate(inc.transactions - init_inc);
847
848 // If inc's feerate is better than best's, remember it as our new best.
849 if (inc.feerate > best.feerate) {
850 best = inc;
851 // See if we can remove any entries from imp now.
852 while (imp.Any()) {
853 DepGraphIndex check = imp.Last();
854 if (m_sorted_depgraph.FeeRate(check) >> best.feerate) break;
855 imp.Reset(check);
856 }
857 }
858
859 // If no potential transactions exist beyond the already included ones, no
860 // improvement is possible anymore.
861 if (pot.feerate.size == inc.feerate.size) return;
862 // At this point und must be non-empty. If it were empty then pot would equal inc.
863 Assume(und.Any());
864 } else {
865 Assume(inc.transactions.None());
866 // If inc is empty, we just make sure there are undecided transactions left to
867 // split on.
868 if (und.None()) return;
869 }
870
871 // Actually construct a new work item on the queue. Due to the switch to DFS when queue
872 // space runs out (see below), we know that no reallocation of the queue should ever
873 // occur.
874 Assume(queue.size() < queue.capacity());
875 queue.emplace_back(/*inc=*/std::move(inc),
876 /*und=*/std::move(und),
877 /*pot_feerate=*/std::move(pot.feerate));
878 };
879
883 auto split_fn = [&](WorkItem&& elem) noexcept {
884 // Any queue element must have undecided transactions left, otherwise there is nothing
885 // to explore anymore.
886 Assume(elem.und.Any());
887 // The included and undecided set are all subsets of m_todo.
888 Assume(elem.inc.transactions.IsSubsetOf(m_todo) && elem.und.IsSubsetOf(m_todo));
889 // Included transactions cannot be undecided.
890 Assume(!elem.inc.transactions.Overlaps(elem.und));
891 // If pot is empty, then so is inc.
892 Assume(elem.inc.feerate.IsEmpty() == elem.pot_feerate.IsEmpty());
893
894 const DepGraphIndex first = elem.und.First();
895 if (!elem.inc.feerate.IsEmpty()) {
896 // If no undecided transactions remain with feerate higher than best, this entry
897 // cannot be improved beyond best.
898 if (!elem.und.Overlaps(imp)) return;
899 // We can ignore any queue item whose potential feerate isn't better than the best
900 // seen so far.
901 if (elem.pot_feerate <= best.feerate) return;
902 } else {
903 // In case inc is empty use a simpler alternative check.
904 if (m_sorted_depgraph.FeeRate(first) <= best.feerate) return;
905 }
906
907 // Decide which transaction to split on. Splitting is how new work items are added, and
908 // how progress is made. One split transaction is chosen among the queue item's
909 // undecided ones, and:
910 // - A work item is (potentially) added with that transaction plus its remaining
911 // descendants excluded (removed from the und set).
912 // - A work item is (potentially) added with that transaction plus its remaining
913 // ancestors included (added to the inc set).
914 //
915 // To decide what to split on, consider the undecided ancestors of the highest
916 // individual feerate undecided transaction. Pick the one which reduces the search space
917 // most. Let I(t) be the size of the undecided set after including t, and E(t) the size
918 // of the undecided set after excluding t. Then choose the split transaction t such
919 // that 2^I(t) + 2^E(t) is minimal, tie-breaking by highest individual feerate for t.
921 const auto select = elem.und & m_sorted_depgraph.Ancestors(first);
922 Assume(select.Any());
923 std::optional<std::pair<DepGraphIndex, DepGraphIndex>> split_counts;
924 for (auto t : select) {
925 // Call max = max(I(t), E(t)) and min = min(I(t), E(t)). Let counts = {max,min}.
926 // Sorting by the tuple counts is equivalent to sorting by 2^I(t) + 2^E(t). This
927 // expression is equal to 2^max + 2^min = 2^max * (1 + 1/2^(max - min)). The second
928 // factor (1 + 1/2^(max - min)) there is in (1,2]. Thus increasing max will always
929 // increase it, even when min decreases. Because of this, we can first sort by max.
930 std::pair<DepGraphIndex, DepGraphIndex> counts{
931 (elem.und - m_sorted_depgraph.Ancestors(t)).Count(),
932 (elem.und - m_sorted_depgraph.Descendants(t)).Count()};
933 if (counts.first < counts.second) std::swap(counts.first, counts.second);
934 // Remember the t with the lowest counts.
935 if (!split_counts.has_value() || counts < *split_counts) {
936 split = t;
937 split_counts = counts;
938 }
939 }
940 // Since there was at least one transaction in select, we must always find one.
941 Assume(split_counts.has_value());
942
943 // Add a work item corresponding to exclusion of the split transaction.
944 const auto& desc = m_sorted_depgraph.Descendants(split);
945 add_fn(/*inc=*/elem.inc,
946 /*und=*/elem.und - desc);
947
948 // Add a work item corresponding to inclusion of the split transaction.
949 const auto anc = m_sorted_depgraph.Ancestors(split) & m_todo;
950 add_fn(/*inc=*/elem.inc.Add(m_sorted_depgraph, anc),
951 /*und=*/elem.und - anc);
952
953 // Account for the performed split.
954 --iterations_left;
955 };
956
957 // Work processing loop.
958 //
959 // New work items are always added at the back of the queue, but items to process use a
960 // hybrid approach where they can be taken from the front or the back.
961 //
962 // Depth-first search (DFS) corresponds to always taking from the back of the queue. This
963 // is very memory-efficient (linear in the number of transactions). Breadth-first search
964 // (BFS) corresponds to always taking from the front, which potentially uses more memory
965 // (up to exponential in the transaction count), but seems to work better in practice.
966 //
967 // The approach here combines the two: use BFS (plus random swapping) until the queue grows
968 // too large, at which point we temporarily switch to DFS until the size shrinks again.
969 while (!queue.empty()) {
970 // Randomly swap the first two items to randomize the search order.
971 if (queue.size() > 1 && m_rng.randbool()) {
972 queue[0].Swap(queue[1]);
973 }
974
975 // Processing the first queue item, and then using DFS for everything it gives rise to,
976 // may increase the queue size by the number of undecided elements in there, minus 1
977 // for the first queue item being removed. Thus, only when that pushes the queue over
978 // its capacity can we not process from the front (BFS), and should we use DFS.
979 while (queue.size() - 1 + queue.front().und.Count() > queue.capacity()) {
980 if (!iterations_left) break;
981 auto elem = queue.back();
982 queue.pop_back();
983 split_fn(std::move(elem));
984 }
985
986 // Process one entry from the front of the queue (BFS exploration)
987 if (!iterations_left) break;
988 auto elem = queue.front();
989 queue.pop_front();
990 split_fn(std::move(elem));
991 }
992
993 // Return the found best set (converted to the original transaction indices), and the
994 // number of iterations performed.
995 best.transactions = SortedToOriginal(best.transactions);
996 return {std::move(best), max_iterations - iterations_left};
997 }
998
1003 void MarkDone(const SetType& done) noexcept
1004 {
1005 const auto done_sorted = OriginalToSorted(done);
1006 Assume(done_sorted.Any());
1007 Assume(done_sorted.IsSubsetOf(m_todo));
1008 m_todo -= done_sorted;
1009 }
1010};
1011
1029template<typename SetType>
1030std::pair<std::vector<DepGraphIndex>, bool> Linearize(const DepGraph<SetType>& depgraph, uint64_t max_iterations, uint64_t rng_seed, std::span<const DepGraphIndex> old_linearization = {}) noexcept
1031{
1032 Assume(old_linearization.empty() || old_linearization.size() == depgraph.TxCount());
1033 if (depgraph.TxCount() == 0) return {{}, true};
1034
1035 uint64_t iterations_left = max_iterations;
1036 std::vector<DepGraphIndex> linearization;
1037
1038 AncestorCandidateFinder anc_finder(depgraph);
1039 std::optional<SearchCandidateFinder<SetType>> src_finder;
1040 linearization.reserve(depgraph.TxCount());
1041 bool optimal = true;
1042
1043 // Treat the initialization of SearchCandidateFinder as taking N^2/64 (rounded up) iterations
1044 // (largely due to the cost of constructing the internal sorted-by-feerate DepGraph inside
1045 // SearchCandidateFinder), a rough approximation based on benchmark. If we don't have that
1046 // many, don't start it.
1047 uint64_t start_iterations = (uint64_t{depgraph.TxCount()} * depgraph.TxCount() + 63) / 64;
1048 if (iterations_left > start_iterations) {
1049 iterations_left -= start_iterations;
1050 src_finder.emplace(depgraph, rng_seed);
1051 }
1052
1054 LinearizationChunking old_chunking(depgraph, old_linearization);
1055
1056 while (true) {
1057 // Find the highest-feerate prefix of the remainder of old_linearization.
1058 SetInfo<SetType> best_prefix;
1059 if (old_chunking.NumChunksLeft()) best_prefix = old_chunking.GetChunk(0);
1060
1061 // Then initialize best to be either the best remaining ancestor set, or the first chunk.
1062 auto best = anc_finder.FindCandidateSet();
1063 if (!best_prefix.feerate.IsEmpty() && best_prefix.feerate >= best.feerate) best = best_prefix;
1064
1065 uint64_t iterations_done_now = 0;
1066 uint64_t max_iterations_now = 0;
1067 if (src_finder) {
1068 // Treat the invocation of SearchCandidateFinder::FindCandidateSet() as costing N/4
1069 // up-front (rounded up) iterations (largely due to the cost of connected-component
1070 // splitting), a rough approximation based on benchmarks.
1071 uint64_t base_iterations = (anc_finder.NumRemaining() + 3) / 4;
1072 if (iterations_left > base_iterations) {
1073 // Invoke bounded search to update best, with up to half of our remaining
1074 // iterations as limit.
1075 iterations_left -= base_iterations;
1076 max_iterations_now = (iterations_left + 1) / 2;
1077 std::tie(best, iterations_done_now) = src_finder->FindCandidateSet(max_iterations_now, best);
1078 iterations_left -= iterations_done_now;
1079 }
1080 }
1081
1082 if (iterations_done_now == max_iterations_now) {
1083 optimal = false;
1084 // If the search result is not (guaranteed to be) optimal, run intersections to make
1085 // sure we don't pick something that makes us unable to reach further diagram points
1086 // of the old linearization.
1087 if (old_chunking.NumChunksLeft() > 0) {
1088 best = old_chunking.IntersectPrefixes(best);
1089 }
1090 }
1091
1092 // Add to output in topological order.
1093 depgraph.AppendTopo(linearization, best.transactions);
1094
1095 // Update state to reflect best is no longer to be linearized.
1096 anc_finder.MarkDone(best.transactions);
1097 if (anc_finder.AllDone()) break;
1098 if (src_finder) src_finder->MarkDone(best.transactions);
1099 if (old_chunking.NumChunksLeft() > 0) {
1100 old_chunking.MarkDone(best.transactions);
1101 }
1102 }
1103
1104 return {std::move(linearization), optimal};
1105}
1106
1123template<typename SetType>
1124void PostLinearize(const DepGraph<SetType>& depgraph, std::span<DepGraphIndex> linearization)
1125{
1126 // This algorithm performs a number of passes (currently 2); the even ones operate from back to
1127 // front, the odd ones from front to back. Each results in an equal-or-better linearization
1128 // than the one started from.
1129 // - One pass in either direction guarantees that the resulting chunks are connected.
1130 // - Each direction corresponds to one shape of tree being linearized optimally (forward passes
1131 // guarantee this for graphs where each transaction has at most one child; backward passes
1132 // guarantee this for graphs where each transaction has at most one parent).
1133 // - Starting with a backward pass guarantees the moved-tree property.
1134 //
1135 // During an odd (forward) pass, the high-level operation is:
1136 // - Start with an empty list of groups L=[].
1137 // - For every transaction i in the old linearization, from front to back:
1138 // - Append a new group C=[i], containing just i, to the back of L.
1139 // - While L has at least one group before C, and the group immediately before C has feerate
1140 // lower than C:
1141 // - If C depends on P:
1142 // - Merge P into C, making C the concatenation of P+C, continuing with the combined C.
1143 // - Otherwise:
1144 // - Swap P with C, continuing with the now-moved C.
1145 // - The output linearization is the concatenation of the groups in L.
1146 //
1147 // During even (backward) passes, i iterates from the back to the front of the existing
1148 // linearization, and new groups are prepended instead of appended to the list L. To enable
1149 // more code reuse, both passes append groups, but during even passes the meanings of
1150 // parent/child, and of high/low feerate are reversed, and the final concatenation is reversed
1151 // on output.
1152 //
1153 // In the implementation below, the groups are represented by singly-linked lists (pointing
1154 // from the back to the front), which are themselves organized in a singly-linked circular
1155 // list (each group pointing to its predecessor, with a special sentinel group at the front
1156 // that points back to the last group).
1157 //
1158 // Information about transaction t is stored in entries[t + 1], while the sentinel is in
1159 // entries[0].
1160
1162 static constexpr DepGraphIndex SENTINEL{0};
1164 static constexpr DepGraphIndex NO_PREV_TX{0};
1165
1166
1168 struct TxEntry
1169 {
1172 DepGraphIndex prev_tx;
1173
1174 // The fields below are only used for transactions that are the last one in a group
1175 // (referred to as tail transactions below).
1176
1178 DepGraphIndex first_tx;
1181 DepGraphIndex prev_group;
1183 SetType group;
1185 SetType deps;
1187 FeeFrac feerate;
1188 };
1189
1190 // As an example, consider the state corresponding to the linearization [1,0,3,2], with
1191 // groups [1,0,3] and [2], in an odd pass. The linked lists would be:
1192 //
1193 // +-----+
1194 // 0<-P-- | 0 S | ---\ Legend:
1195 // +-----+ |
1196 // ^ | - digit in box: entries index
1197 // /--------------F---------+ G | (note: one more than tx value)
1198 // v \ | | - S: sentinel group
1199 // +-----+ +-----+ +-----+ | (empty feerate)
1200 // 0<-P-- | 2 | <--P-- | 1 | <--P-- | 4 T | | - T: tail transaction, contains
1201 // +-----+ +-----+ +-----+ | fields beyond prev_tv.
1202 // ^ | - P: prev_tx reference
1203 // G G - F: first_tx reference
1204 // | | - G: prev_group reference
1205 // +-----+ |
1206 // 0<-P-- | 3 T | <--/
1207 // +-----+
1208 // ^ |
1209 // \-F-/
1210 //
1211 // During an even pass, the diagram above would correspond to linearization [2,3,0,1], with
1212 // groups [2] and [3,0,1].
1213
1214 std::vector<TxEntry> entries(depgraph.PositionRange() + 1);
1215
1216 // Perform two passes over the linearization.
1217 for (int pass = 0; pass < 2; ++pass) {
1218 int rev = !(pass & 1);
1219 // Construct a sentinel group, identifying the start of the list.
1220 entries[SENTINEL].prev_group = SENTINEL;
1221 Assume(entries[SENTINEL].feerate.IsEmpty());
1222
1223 // Iterate over all elements in the existing linearization.
1224 for (DepGraphIndex i = 0; i < linearization.size(); ++i) {
1225 // Even passes are from back to front; odd passes from front to back.
1226 DepGraphIndex idx = linearization[rev ? linearization.size() - 1 - i : i];
1227 // Construct a new group containing just idx. In even passes, the meaning of
1228 // parent/child and high/low feerate are swapped.
1229 DepGraphIndex cur_group = idx + 1;
1230 entries[cur_group].group = SetType::Singleton(idx);
1231 entries[cur_group].deps = rev ? depgraph.Descendants(idx): depgraph.Ancestors(idx);
1232 entries[cur_group].feerate = depgraph.FeeRate(idx);
1233 if (rev) entries[cur_group].feerate.fee = -entries[cur_group].feerate.fee;
1234 entries[cur_group].prev_tx = NO_PREV_TX; // No previous transaction in group.
1235 entries[cur_group].first_tx = cur_group; // Transaction itself is first of group.
1236 // Insert the new group at the back of the groups linked list.
1237 entries[cur_group].prev_group = entries[SENTINEL].prev_group;
1238 entries[SENTINEL].prev_group = cur_group;
1239
1240 // Start merge/swap cycle.
1241 DepGraphIndex next_group = SENTINEL; // We inserted at the end, so next group is sentinel.
1242 DepGraphIndex prev_group = entries[cur_group].prev_group;
1243 // Continue as long as the current group has higher feerate than the previous one.
1244 while (entries[cur_group].feerate >> entries[prev_group].feerate) {
1245 // prev_group/cur_group/next_group refer to (the last transactions of) 3
1246 // consecutive entries in groups list.
1247 Assume(cur_group == entries[next_group].prev_group);
1248 Assume(prev_group == entries[cur_group].prev_group);
1249 // The sentinel has empty feerate, which is neither higher or lower than other
1250 // feerates. Thus, the while loop we are in here guarantees that cur_group and
1251 // prev_group are not the sentinel.
1252 Assume(cur_group != SENTINEL);
1253 Assume(prev_group != SENTINEL);
1254 if (entries[cur_group].deps.Overlaps(entries[prev_group].group)) {
1255 // There is a dependency between cur_group and prev_group; merge prev_group
1256 // into cur_group. The group/deps/feerate fields of prev_group remain unchanged
1257 // but become unused.
1258 entries[cur_group].group |= entries[prev_group].group;
1259 entries[cur_group].deps |= entries[prev_group].deps;
1260 entries[cur_group].feerate += entries[prev_group].feerate;
1261 // Make the first of the current group point to the tail of the previous group.
1262 entries[entries[cur_group].first_tx].prev_tx = prev_group;
1263 // The first of the previous group becomes the first of the newly-merged group.
1264 entries[cur_group].first_tx = entries[prev_group].first_tx;
1265 // The previous group becomes whatever group was before the former one.
1266 prev_group = entries[prev_group].prev_group;
1267 entries[cur_group].prev_group = prev_group;
1268 } else {
1269 // There is no dependency between cur_group and prev_group; swap them.
1270 DepGraphIndex preprev_group = entries[prev_group].prev_group;
1271 // If PP, P, C, N were the old preprev, prev, cur, next groups, then the new
1272 // layout becomes [PP, C, P, N]. Update prev_groups to reflect that order.
1273 entries[next_group].prev_group = prev_group;
1274 entries[prev_group].prev_group = cur_group;
1275 entries[cur_group].prev_group = preprev_group;
1276 // The current group remains the same, but the groups before/after it have
1277 // changed.
1278 next_group = prev_group;
1279 prev_group = preprev_group;
1280 }
1281 }
1282 }
1283
1284 // Convert the entries back to linearization (overwriting the existing one).
1285 DepGraphIndex cur_group = entries[0].prev_group;
1286 DepGraphIndex done = 0;
1287 while (cur_group != SENTINEL) {
1288 DepGraphIndex cur_tx = cur_group;
1289 // Traverse the transactions of cur_group (from back to front), and write them in the
1290 // same order during odd passes, and reversed (front to back) in even passes.
1291 if (rev) {
1292 do {
1293 *(linearization.begin() + (done++)) = cur_tx - 1;
1294 cur_tx = entries[cur_tx].prev_tx;
1295 } while (cur_tx != NO_PREV_TX);
1296 } else {
1297 do {
1298 *(linearization.end() - (++done)) = cur_tx - 1;
1299 cur_tx = entries[cur_tx].prev_tx;
1300 } while (cur_tx != NO_PREV_TX);
1301 }
1302 cur_group = entries[cur_group].prev_group;
1303 }
1304 Assume(done == linearization.size());
1305 }
1306}
1307
1312template<typename SetType>
1313std::vector<DepGraphIndex> MergeLinearizations(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> lin1, std::span<const DepGraphIndex> lin2)
1314{
1315 Assume(lin1.size() == depgraph.TxCount());
1316 Assume(lin2.size() == depgraph.TxCount());
1317
1319 LinearizationChunking chunking1(depgraph, lin1), chunking2(depgraph, lin2);
1321 std::vector<DepGraphIndex> ret;
1322 if (depgraph.TxCount() == 0) return ret;
1323 ret.reserve(depgraph.TxCount());
1324
1325 while (true) {
1326 // As long as we are not done, both linearizations must have chunks left.
1327 Assume(chunking1.NumChunksLeft() > 0);
1328 Assume(chunking2.NumChunksLeft() > 0);
1329 // Find the set to output by taking the best remaining chunk, and then intersecting it with
1330 // prefixes of remaining chunks of the other linearization.
1331 SetInfo<SetType> best;
1332 const auto& lin1_firstchunk = chunking1.GetChunk(0);
1333 const auto& lin2_firstchunk = chunking2.GetChunk(0);
1334 if (lin2_firstchunk.feerate >> lin1_firstchunk.feerate) {
1335 best = chunking1.IntersectPrefixes(lin2_firstchunk);
1336 } else {
1337 best = chunking2.IntersectPrefixes(lin1_firstchunk);
1338 }
1339 // Append the result to the output and mark it as done.
1340 depgraph.AppendTopo(ret, best.transactions);
1341 chunking1.MarkDone(best.transactions);
1342 if (chunking1.NumChunksLeft() == 0) break;
1343 chunking2.MarkDone(best.transactions);
1344 }
1345
1346 Assume(ret.size() == depgraph.TxCount());
1347 return ret;
1348}
1349
1351template<typename SetType>
1352void FixLinearization(const DepGraph<SetType>& depgraph, std::span<DepGraphIndex> linearization) noexcept
1353{
1354 // This algorithm can be summarized as moving every element in the linearization backwards
1355 // until it is placed after all its ancestors.
1356 SetType done;
1357 const auto len = linearization.size();
1358 // Iterate over the elements of linearization from back to front (i is distance from back).
1359 for (DepGraphIndex i = 0; i < len; ++i) {
1361 DepGraphIndex elem = linearization[len - 1 - i];
1363 DepGraphIndex j = i;
1364 // Figure out which elements need to be moved before elem.
1365 SetType place_before = done & depgraph.Ancestors(elem);
1366 // Find which position to place elem in (updating j), continuously moving the elements
1367 // in between forward.
1368 while (place_before.Any()) {
1369 // j cannot be 0 here; if it was, then there was necessarily nothing earlier which
1370 // elem needs to be place before anymore, and place_before would be empty.
1371 Assume(j > 0);
1372 auto to_swap = linearization[len - 1 - (j - 1)];
1373 place_before.Reset(to_swap);
1374 linearization[len - 1 - (j--)] = to_swap;
1375 }
1376 // Put elem in its final position and mark it as done.
1377 linearization[len - 1 - j] = elem;
1378 done.Set(elem);
1379 }
1380}
1381
1382} // namespace cluster_linearize
1383
1384#endif // BITCOIN_CLUSTER_LINEARIZE_H
#define LIFETIMEBOUND
Definition: attributes.h:16
int ret
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
xoroshiro128++ PRNG.
Definition: random.h:416
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:316
Data structure largely mimicking std::deque, but using single preallocated ring buffer.
Definition: vecdeque.h:25
bool empty() const noexcept
Test whether the contents of this deque is empty.
Definition: vecdeque.h:310
void pop_front()
Remove the first element of the deque.
Definition: vecdeque.h:250
size_t size() const noexcept
Get the number of elements in this deque.
Definition: vecdeque.h:312
void pop_back()
Remove the last element of the deque.
Definition: vecdeque.h:260
void emplace_back(Args &&... args)
Construct a new element at the end of the deque.
Definition: vecdeque.h:219
T & front() noexcept
Get a mutable reference to the first element of the deque.
Definition: vecdeque.h:268
void reserve(size_t capacity)
Increase the capacity to capacity.
Definition: vecdeque.h:206
size_t capacity() const noexcept
Get the capacity of this deque (maximum size it can have without reallocating).
Definition: vecdeque.h:314
T & back() noexcept
Get a mutable reference to the last element of the deque.
Definition: vecdeque.h:282
Class encapsulating the state needed to find the best remaining ancestor set.
void MarkDone(SetType select) noexcept
Remove a set of transactions from the set of to-be-linearized ones.
DepGraphIndex NumRemaining() const noexcept
Count the number of remaining unlinearized transactions.
SetInfo< SetType > FindCandidateSet() const noexcept
Find the best (highest-feerate, smallest among those in case of a tie) ancestor set among the remaini...
const DepGraph< SetType > & m_depgraph
Internal dependency graph.
AncestorCandidateFinder(const DepGraph< SetType > &depgraph LIFETIMEBOUND) noexcept
Construct an AncestorCandidateFinder for a given cluster.
std::vector< FeeFrac > m_ancestor_set_feerates
Precomputed ancestor-set feerates (only kept up-to-date for indices in m_todo).
SetType m_todo
Which transaction are left to include.
bool AllDone() const noexcept
Check whether any unlinearized transactions remain.
Data structure that holds a transaction graph's preprocessed data (fee, size, ancestors,...
const SetType & Ancestors(DepGraphIndex i) const noexcept
Get the ancestors of a given transaction i.
FeeFrac & FeeRate(DepGraphIndex i) noexcept
Get the mutable feerate of a given transaction i.
SetType GetReducedChildren(DepGraphIndex i) const noexcept
Compute the (reduced) set of children of node i in this graph.
SetType GetReducedParents(DepGraphIndex i) const noexcept
Compute the (reduced) set of parents of node i in this graph.
void AppendTopo(std::vector< DepGraphIndex > &list, const SetType &select) const noexcept
Append the entries of select to list in a topologically valid order.
const FeeFrac & FeeRate(DepGraphIndex i) const noexcept
Get the feerate of a given transaction i.
bool IsConnected() const noexcept
Determine if this entire graph is connected.
bool IsConnected(const SetType &subset) const noexcept
Determine if a subset is connected.
DepGraphIndex PositionRange() const noexcept
Get the range of positions in this DepGraph.
SetType FindConnectedComponent(const SetType &todo) const noexcept
Find some connected component within the subset "todo" of this graph.
DepGraphIndex AddTransaction(const FeeFrac &feefrac) noexcept
Add a new unconnected transaction to this transaction graph (in the first available position),...
void RemoveTransactions(const SetType &del) noexcept
Remove the specified positions from this DepGraph.
auto TxCount() const noexcept
Get the number of transactions in the graph.
std::vector< Entry > entries
Data for each transaction.
const SetType & Descendants(DepGraphIndex i) const noexcept
Get the descendants of a given transaction i.
friend bool operator==(const DepGraph &a, const DepGraph &b) noexcept
Equality operator (primarily for testing purposes).
DepGraph() noexcept=default
SetType m_used
Which positions are used.
const SetType & Positions() const noexcept
Get the set of transactions positions in use.
FeeFrac FeeRate(const SetType &elems) const noexcept
Compute the aggregate feerate of a set of nodes in this graph.
void AddDependencies(const SetType &parents, DepGraphIndex child) noexcept
Modify this transaction graph, adding multiple parents to a specified child.
bool IsAcyclic() const noexcept
Check if this graph is acyclic.
Data structure encapsulating the chunking of a linearization, permitting removal of subsets.
std::span< const DepGraphIndex > m_linearization
The linearization we started from, possibly with removed prefix stripped.
DepGraphIndex NumChunksLeft() const noexcept
Determine how many chunks remain in the linearization.
const SetInfo< SetType > & GetChunk(DepGraphIndex n) const noexcept
Access a chunk.
SetType m_todo
Which transactions remain in the linearization.
SetInfo< SetType > IntersectPrefixes(const SetInfo< SetType > &subset) const noexcept
Find the shortest intersection between subset and the prefixes of remaining chunks of the linearizati...
void BuildChunks() noexcept
Fill the m_chunks variable, and remove the done prefix of m_linearization.
void MarkDone(SetType subset) noexcept
Remove some subset of transactions from the linearization.
DepGraphIndex m_chunks_skip
How large a prefix of m_chunks corresponds to removed transactions.
const DepGraph< SetType > & m_depgraph
The depgraph this linearization is for.
std::vector< SetInfo< SetType > > m_chunks
Chunk sets and their feerates, of what remains of the linearization.
LinearizationChunking(const DepGraph< SetType > &depgraph LIFETIMEBOUND, std::span< const DepGraphIndex > lin LIFETIMEBOUND) noexcept
Initialize a LinearizationSubset object for a given length of linearization.
Class encapsulating the state needed to perform search for good candidate sets.
bool AllDone() const noexcept
Check whether any unlinearized transactions remain.
std::vector< DepGraphIndex > m_sorted_to_original
m_sorted_to_original[i] is the original position that sorted transaction position i had.
std::vector< DepGraphIndex > m_original_to_sorted
m_original_to_sorted[i] is the sorted position original transaction position i has.
void MarkDone(const SetType &done) noexcept
Remove a subset of transactions from the cluster being linearized.
InsecureRandomContext m_rng
Internal RNG.
SetType OriginalToSorted(const SetType &arg) const noexcept
Given a set of transactions with original indices, get their sorted indices.
SetType m_todo
Which transactions are left to do (indices in m_sorted_depgraph's order).
SetType SortedToOriginal(const SetType &arg) const noexcept
Given a set of transactions with sorted indices, get their original indices.
SearchCandidateFinder(const DepGraph< SetType > &depgraph, uint64_t rng_seed) noexcept
Construct a candidate finder for a graph.
DepGraph< SetType > m_sorted_depgraph
Internal dependency graph for the cluster (with transactions in decreasing individual feerate order).
std::pair< SetInfo< SetType >, uint64_t > FindCandidateSet(uint64_t max_iterations, SetInfo< SetType > best) noexcept
Find a high-feerate topologically-valid subset of what remains of the cluster.
std::vector< FeeFrac > ChunkLinearization(const DepGraph< SetType > &depgraph, std::span< const DepGraphIndex > linearization) noexcept
Compute the feerates of the chunks of linearization.
std::pair< std::vector< DepGraphIndex >, bool > Linearize(const DepGraph< SetType > &depgraph, uint64_t max_iterations, uint64_t rng_seed, std::span< const DepGraphIndex > old_linearization={}) noexcept
Find or improve a linearization for a cluster.
void FixLinearization(const DepGraph< SetType > &depgraph, std::span< DepGraphIndex > linearization) noexcept
Make linearization topological, retaining its ordering where possible.
std::vector< DepGraphIndex > MergeLinearizations(const DepGraph< SetType > &depgraph, std::span< const DepGraphIndex > lin1, std::span< const DepGraphIndex > lin2)
Merge two linearizations for the same cluster into one that is as good as both.
uint32_t DepGraphIndex
Data type to represent transaction indices in DepGraphs and the clusters they represent.
void PostLinearize(const DepGraph< SetType > &depgraph, std::span< DepGraphIndex > linearization)
Improve a given linearization.
static std::vector< std::string > split(const std::string &str, const std::string &delims=" \t")
Definition: subprocess.h:303
Data structure storing a fee and size, ordered by increasing fee/size.
Definition: feefrac.h:39
int64_t fee
Definition: feefrac.h:63
int32_t size
Definition: feefrac.h:64
bool IsEmpty() const noexcept
Check if this is empty (size and fee are 0).
Definition: feefrac.h:76
Information about a single transaction.
SetType descendants
All descendants of the transaction (including itself).
friend bool operator==(const Entry &, const Entry &) noexcept=default
Equality operator (primarily for for testing purposes).
Entry() noexcept=default
Construct an empty entry.
FeeFrac feerate
Fee and size of transaction itself.
SetType ancestors
All ancestors of the transaction (including itself).
A set of transactions together with their aggregate feerate.
SetInfo(const DepGraph< SetType > &depgraph, DepGraphIndex pos) noexcept
Construct a SetInfo for a given transaction in a depgraph.
FeeFrac feerate
Their combined fee and size.
SetInfo() noexcept=default
Construct a SetInfo for the empty set.
void Set(const DepGraph< SetType > &depgraph, DepGraphIndex pos) noexcept
Add a transaction to this SetInfo (which must not yet be in it).
SetType transactions
The transactions in the set.
friend void swap(SetInfo &a, SetInfo &b) noexcept
Swap two SetInfo objects.
SetInfo(const DepGraph< SetType > &depgraph, const SetType &txn) noexcept
Construct a SetInfo for a set of transactions in a depgraph.
SetInfo Add(const DepGraph< SetType > &depgraph, const SetType &txn) const noexcept
Construct a new SetInfo equal to this, with more transactions added (which may overlap with the exist...
SetInfo & operator|=(const SetInfo &other) noexcept
Add the transactions of other to this SetInfo (no overlap allowed).
friend bool operator==(const SetInfo &, const SetInfo &) noexcept=default
Permit equality testing.