Branch data Line data Source code
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 <cstdint>
10 : : #include <numeric>
11 : : #include <optional>
12 : : #include <utility>
13 : : #include <vector>
14 : :
15 : : #include <attributes.h>
16 : : #include <memusage.h>
17 : : #include <random.h>
18 : : #include <span.h>
19 : : #include <util/feefrac.h>
20 : : #include <util/vecdeque.h>
21 : :
22 : : namespace cluster_linearize {
23 : :
24 : : /** Data type to represent transaction indices in DepGraphs and the clusters they represent. */
25 : : using DepGraphIndex = uint32_t;
26 : :
27 : : /** Data structure that holds a transaction graph's preprocessed data (fee, size, ancestors,
28 : : * descendants). */
29 : : template<typename SetType>
30 [ + + + - : 7309 : class DepGraph
+ - ][ + -
+ - + - +
- + - ]
31 : : {
32 : : /** Information about a single transaction. */
33 : : struct Entry
34 : : {
35 : : /** Fee and size of transaction itself. */
36 : 50090 : FeeFrac feerate;
37 : : /** All ancestors of the transaction (including itself). */
38 : 50090 : SetType ancestors;
39 : : /** All descendants of the transaction (including itself). */
40 : 50090 : SetType descendants;
41 : :
42 : : /** Equality operator (primarily for testing purposes). */
43 [ + - + - : 100180 : friend bool operator==(const Entry&, const Entry&) noexcept = default;
- + ]
44 : :
45 : : /** Construct an empty entry. */
46 : 75582 : Entry() noexcept = default;
47 : : /** Construct an entry with a given feerate, ancestor set, descendant set. */
48 : 82853 : Entry(const FeeFrac& f, const SetType& a, const SetType& d) noexcept : feerate(f), ancestors(a), descendants(d) {}
49 : : };
50 : :
51 : : /** Data for each transaction. */
52 : : std::vector<Entry> entries;
53 : :
54 : : /** Which positions are used. */
55 : : SetType m_used;
56 : :
57 : : public:
58 : : /** Equality operator (primarily for testing purposes). */
59 : 1883 : friend bool operator==(const DepGraph& a, const DepGraph& b) noexcept
60 : : {
61 [ + - ]: 1883 : if (a.m_used != b.m_used) return false;
62 : : // Only compare the used positions within the entries vector.
63 [ + + + + ]: 52695 : for (auto idx : a.m_used) {
64 [ + - ]: 50090 : if (a.entries[idx] != b.entries[idx]) return false;
65 : : }
66 : : return true;
67 : : }
68 : :
69 : : // Default constructors.
70 : 1968 : DepGraph() noexcept = default;
71 : : DepGraph(const DepGraph&) noexcept = default;
72 : : DepGraph(DepGraph&&) noexcept = default;
73 : 326 : DepGraph& operator=(const DepGraph&) noexcept = default;
74 : 5433 : DepGraph& operator=(DepGraph&&) noexcept = default;
75 : :
76 : : /** Construct a DepGraph object given another DepGraph and a mapping from old to new.
77 : : *
78 : : * @param depgraph The original DepGraph that is being remapped.
79 : : *
80 : : * @param mapping A span such that mapping[i] gives the position in the new DepGraph
81 : : * for position i in the old depgraph. Its size must be equal to
82 : : * depgraph.PositionRange(). The value of mapping[i] is ignored if
83 : : * position i is a hole in depgraph (i.e., if !depgraph.Positions()[i]).
84 : : *
85 : : * @param pos_range The PositionRange() for the new DepGraph. It must equal the largest
86 : : * value in mapping for any used position in depgraph plus 1, or 0 if
87 : : * depgraph.TxCount() == 0.
88 : : *
89 : : * Complexity: O(N^2) where N=depgraph.TxCount().
90 : : */
91 [ - + ]: 2814 : DepGraph(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> mapping, DepGraphIndex pos_range) noexcept : entries(pos_range)
92 : : {
93 [ - + ]: 2814 : Assume(mapping.size() == depgraph.PositionRange());
94 : 2814 : Assume((pos_range == 0) == (depgraph.TxCount() == 0));
95 [ + + ]: 77919 : for (DepGraphIndex i : depgraph.Positions()) {
96 : 75105 : auto new_idx = mapping[i];
97 : 75105 : Assume(new_idx < pos_range);
98 : : // Add transaction.
99 : 75105 : entries[new_idx].ancestors = SetType::Singleton(new_idx);
100 : 75105 : entries[new_idx].descendants = SetType::Singleton(new_idx);
101 : 75105 : m_used.Set(new_idx);
102 : : // Fill in fee and size.
103 : 75105 : entries[new_idx].feerate = depgraph.entries[i].feerate;
104 : : }
105 [ + + ]: 77919 : for (DepGraphIndex i : depgraph.Positions()) {
106 : : // Fill in dependencies by mapping direct parents.
107 : 75105 : SetType parents;
108 [ + + + + ]: 321075 : for (auto j : depgraph.GetReducedParents(i)) parents.Set(mapping[j]);
109 : 75105 : AddDependencies(parents, mapping[i]);
110 : : }
111 : : // Verify that the provided pos_range was correct (no unused positions at the end).
112 [ + - ]: 4551 : Assume(m_used.None() ? (pos_range == 0) : (pos_range == m_used.Last() + 1));
113 : 2814 : }
114 : :
115 : : /** Get the set of transactions positions in use. Complexity: O(1). */
116 [ + + + + : 96706 : const SetType& Positions() const noexcept { return m_used; }
+ - + - +
+ + + + +
+ - + + +
+ + - + -
+ - + - +
- + - ]
117 : : /** Get the range of positions in this DepGraph. All entries in Positions() are in [0, PositionRange() - 1]. */
118 [ - + - + : 67983 : DepGraphIndex PositionRange() const noexcept { return entries.size(); }
- + - + -
+ ][ - + -
+ + + - +
- + - + +
- - + - +
- + + - -
+ + - - +
- + - + +
- - + + -
- + - + -
+ + - - +
+ - - + -
+ - + + -
- + + - -
+ - + - +
+ - - + +
- - + - +
- + - + -
+ ]
119 : : /** Get the number of transactions in the graph. Complexity: O(1). */
120 [ - + - + ]: 571021 : auto TxCount() const noexcept { return m_used.Count(); }
[ + - + -
+ + + - +
- + - + -
+ - + - +
- + - + -
- + - + -
+ - + - +
- + - + -
+ - + -
+ ]
121 : : /** Get the feerate of a given transaction i. Complexity: O(1). */
122 [ + - + + : 362667 : const FeeFrac& FeeRate(DepGraphIndex i) const noexcept { return entries[i].feerate; }
+ - + + +
- + + + -
+ + + - +
+ ]
123 : : /** Get the mutable feerate of a given transaction i. Complexity: O(1). */
124 [ + - + - ]: 443 : FeeFrac& FeeRate(DepGraphIndex i) noexcept { return entries[i].feerate; }
125 : : /** Get the ancestors of a given transaction i. Complexity: O(1). */
126 [ + - + + : 30109513 : const SetType& Ancestors(DepGraphIndex i) const noexcept { return entries[i].ancestors; }
- + ][ + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - + - +
+ + - + -
+ - + - +
- + - - +
- + + - +
- - + + -
- + - + -
+ + - + -
- + - + +
- + - - +
- + + - +
- - + + -
- + - + -
+ + - ]
127 : : /** Get the descendants of a given transaction i. Complexity: O(1). */
128 [ + - ][ + + : 1890566 : const SetType& Descendants(DepGraphIndex i) const noexcept { return entries[i].descendants; }
+ + + - +
- - + - +
- + - + -
+ - + - +
- + - + -
+ - + -
+ ]
129 : :
130 : : /** Add a new unconnected transaction to this transaction graph (in the first available
131 : : * position), and return its DepGraphIndex.
132 : : *
133 : : * Complexity: O(1) (amortized, due to resizing of backing vector).
134 : : */
135 : 82853 : DepGraphIndex AddTransaction(const FeeFrac& feefrac) noexcept
136 : : {
137 : : static constexpr auto ALL_POSITIONS = SetType::Fill(SetType::Size());
138 [ + - ]: 82853 : auto available = ALL_POSITIONS - m_used;
139 [ + - ]: 130778 : Assume(available.Any());
140 : 82853 : DepGraphIndex new_idx = available.First();
141 [ - + + - ]: 82853 : if (new_idx == entries.size()) {
142 : 82853 : entries.emplace_back(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx));
143 : : } else {
144 : 0 : entries[new_idx] = Entry(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx));
145 : : }
146 : 82853 : m_used.Set(new_idx);
147 : 82853 : return new_idx;
148 : : }
149 : :
150 : : /** Remove the specified positions from this DepGraph.
151 : : *
152 : : * The specified positions will no longer be part of Positions(), and dependencies with them are
153 : : * removed. Note that due to DepGraph only tracking ancestors/descendants (and not direct
154 : : * dependencies), if a parent is removed while a grandparent remains, the grandparent will
155 : : * remain an ancestor.
156 : : *
157 : : * Complexity: O(N) where N=TxCount().
158 : : */
159 : 1482 : void RemoveTransactions(const SetType& del) noexcept
160 : : {
161 : 1482 : m_used -= del;
162 : : // Remove now-unused trailing entries.
163 [ + + - + : 6545 : while (!entries.empty() && !m_used[entries.size() - 1]) {
+ + ]
164 : 5063 : entries.pop_back();
165 : : }
166 : : // Remove the deleted transactions from ancestors/descendants of other transactions. Note
167 : : // that the deleted positions will retain old feerate and dependency information. This does
168 : : // not matter as they will be overwritten by AddTransaction if they get used again.
169 [ + + ]: 2271 : for (auto& entry : entries) {
170 : 789 : entry.ancestors &= m_used;
171 : 789 : entry.descendants &= m_used;
172 : : }
173 : 1482 : }
174 : :
175 : : /** Modify this transaction graph, adding multiple parents to a specified child.
176 : : *
177 : : * Complexity: O(N) where N=TxCount().
178 : : */
179 : 163852 : void AddDependencies(const SetType& parents, DepGraphIndex child) noexcept
180 : : {
181 [ + + ]: 163852 : Assume(m_used[child]);
182 : 259702 : Assume(parents.IsSubsetOf(m_used));
183 : : // Compute the ancestors of parents that are not already ancestors of child.
184 [ + + ]: 163852 : SetType par_anc;
185 [ + + + + ]: 853745 : for (auto par : parents - Ancestors(child)) {
186 : 1051638 : par_anc |= Ancestors(par);
187 : : }
188 [ + + ]: 163852 : par_anc -= Ancestors(child);
189 : : // Bail out if there are no such ancestors.
190 [ + + ]: 163852 : if (par_anc.None()) return;
191 : : // To each such ancestor, add as descendants the descendants of the child.
192 : 123901 : const auto& chl_des = entries[child].descendants;
193 [ + + ]: 993755 : for (auto anc_of_par : par_anc) {
194 : 1399036 : entries[anc_of_par].descendants |= chl_des;
195 : : }
196 : : // To each descendant of the child, add those ancestors.
197 [ + + + + ]: 296134 : for (auto dec_of_chl : Descendants(child)) {
198 : 199496 : entries[dec_of_chl].ancestors |= par_anc;
199 : : }
200 : : }
201 : :
202 : : /** Compute the (reduced) set of parents of node i in this graph.
203 : : *
204 : : * This returns the minimal subset of the parents of i whose ancestors together equal all of
205 : : * i's ancestors (unless i is part of a cycle of dependencies). Note that DepGraph does not
206 : : * store the set of parents; this information is inferred from the ancestor sets.
207 : : *
208 : : * Complexity: O(N) where N=Ancestors(i).Count() (which is bounded by TxCount()).
209 : : */
210 [ + + ]: 5208562 : SetType GetReducedParents(DepGraphIndex i) const noexcept
211 : : {
212 [ + + ]: 5208562 : SetType parents = Ancestors(i);
213 : 5208562 : parents.Reset(i);
214 [ + + + + : 33154741 : for (auto parent : parents) {
+ + ]
215 [ + + ]: 26413889 : if (parents[parent]) {
216 : 22350541 : parents -= Ancestors(parent);
217 : 22350541 : parents.Set(parent);
218 : : }
219 : : }
220 : 5208562 : return parents;
221 : : }
222 : :
223 : : /** Compute the (reduced) set of children of node i in this graph.
224 : : *
225 : : * This returns the minimal subset of the children of i whose descendants together equal all of
226 : : * i's descendants (unless i is part of a cycle of dependencies). Note that DepGraph does not
227 : : * store the set of children; this information is inferred from the descendant sets.
228 : : *
229 : : * Complexity: O(N) where N=Descendants(i).Count() (which is bounded by TxCount()).
230 : : */
231 [ + + ]: 50070 : SetType GetReducedChildren(DepGraphIndex i) const noexcept
232 : : {
233 [ + + ]: 50070 : SetType children = Descendants(i);
234 : 50070 : children.Reset(i);
235 [ + + + + : 293106 : for (auto child : children) {
+ + ]
236 [ + + ]: 233772 : if (children[child]) {
237 : 167192 : children -= Descendants(child);
238 : 167192 : children.Set(child);
239 : : }
240 : : }
241 : 50070 : return children;
242 : : }
243 : :
244 : : /** Compute the aggregate feerate of a set of nodes in this graph.
245 : : *
246 : : * Complexity: O(N) where N=elems.Count().
247 : : **/
248 : : FeeFrac FeeRate(const SetType& elems) const noexcept
249 : : {
250 : : FeeFrac ret;
251 : : for (auto pos : elems) ret += entries[pos].feerate;
252 : : return ret;
253 : : }
254 : :
255 : : /** Get the connected component within the subset "todo" that contains tx (which must be in
256 : : * todo).
257 : : *
258 : : * Two transactions are considered connected if they are both in `todo`, and one is an ancestor
259 : : * of the other in the entire graph (so not just within `todo`), or transitively there is a
260 : : * path of transactions connecting them. This does mean that if `todo` contains a transaction
261 : : * and a grandparent, but misses the parent, they will still be part of the same component.
262 : : *
263 : : * Complexity: O(ret.Count()).
264 : : */
265 : 243449 : SetType GetConnectedComponent(const SetType& todo, DepGraphIndex tx) const noexcept
266 : : {
267 : 243449 : Assume(todo[tx]);
268 : 243449 : Assume(todo.IsSubsetOf(m_used));
269 : 243449 : auto to_add = SetType::Singleton(tx);
270 : 243449 : SetType ret;
271 : : do {
272 : 491277 : SetType old = ret;
273 [ + - + + ]: 1804787 : for (auto add : to_add) {
274 : 822233 : ret |= Descendants(add);
275 : 822233 : ret |= Ancestors(add);
276 : : }
277 [ + + ]: 491277 : ret &= todo;
278 : 491277 : to_add = ret - old;
279 [ + + ]: 491277 : } while (to_add.Any());
280 : 243449 : return ret;
281 : : }
282 : :
283 : : /** Find some connected component within the subset "todo" of this graph.
284 : : *
285 : : * Specifically, this finds the connected component which contains the first transaction of
286 : : * todo (if any).
287 : : *
288 : : * Complexity: O(ret.Count()).
289 : : */
290 [ - + ]: 243449 : SetType FindConnectedComponent(const SetType& todo) const noexcept
291 : : {
292 [ - + ]: 243449 : if (todo.None()) return todo;
293 : 243449 : return GetConnectedComponent(todo, todo.First());
294 : : }
295 : :
296 : : /** Determine if a subset is connected.
297 : : *
298 : : * Complexity: O(subset.Count()).
299 : : */
300 : 243038 : bool IsConnected(const SetType& subset) const noexcept
301 : : {
302 [ - + ]: 243038 : return FindConnectedComponent(subset) == subset;
303 : : }
304 : :
305 : : /** Determine if this entire graph is connected.
306 : : *
307 : : * Complexity: O(TxCount()).
308 : : */
309 : : bool IsConnected() const noexcept { return IsConnected(m_used); }
310 : :
311 : : /** Append the entries of select to list in a topologically valid order.
312 : : *
313 : : * Complexity: O(select.Count() * log(select.Count())).
314 : : */
315 : : void AppendTopo(std::vector<DepGraphIndex>& list, const SetType& select) const noexcept
316 : : {
317 : : DepGraphIndex old_len = list.size();
318 : : for (auto i : select) list.push_back(i);
319 : : std::sort(list.begin() + old_len, list.end(), [&](DepGraphIndex a, DepGraphIndex b) noexcept {
320 : : const auto a_anc_count = entries[a].ancestors.Count();
321 : : const auto b_anc_count = entries[b].ancestors.Count();
322 : : if (a_anc_count != b_anc_count) return a_anc_count < b_anc_count;
323 : : return a < b;
324 : : });
325 : : }
326 : :
327 : : /** Check if this graph is acyclic. */
328 : 60348 : bool IsAcyclic() const noexcept
329 : : {
330 [ + + + - : 388190 : for (auto i : Positions()) {
+ + ]
331 [ + - ]: 268074 : if ((Ancestors(i) & Descendants(i)) != SetType::Singleton(i)) {
332 : : return false;
333 : : }
334 : : }
335 : : return true;
336 : : }
337 : :
338 : : unsigned CountDependencies() const noexcept
339 : : {
340 : : unsigned ret = 0;
341 : : for (auto i : Positions()) {
342 : : ret += GetReducedParents(i).Count();
343 : : }
344 : : return ret;
345 : : }
346 : :
347 : : /** Reduce memory usage if possible. No observable effect. */
348 : 6987 : void Compact() noexcept
349 : : {
350 : 6987 : entries.shrink_to_fit();
351 : : }
352 : :
353 : 73851 : size_t DynamicMemoryUsage() const noexcept
354 : : {
355 [ - + ]: 73851 : return memusage::DynamicUsage(entries);
356 : : }
357 : : };
358 : :
359 : : /** A set of transactions together with their aggregate feerate. */
360 : : template<typename SetType>
361 : : struct SetInfo
362 : : {
363 : : /** The transactions in the set. */
364 : : SetType transactions;
365 : : /** Their combined fee and size. */
366 : : FeeFrac feerate;
367 : :
368 : : /** Construct a SetInfo for the empty set. */
369 : 1899760 : SetInfo() noexcept = default;
370 : :
371 : : /** Construct a SetInfo for a specified set and feerate. */
372 : 1355795 : SetInfo(const SetType& txn, const FeeFrac& fr) noexcept : transactions(txn), feerate(fr) {}
373 : :
374 : : /** Construct a SetInfo for a given transaction in a depgraph. */
375 : 327026 : explicit SetInfo(const DepGraph<SetType>& depgraph, DepGraphIndex pos) noexcept :
376 : 327026 : transactions(SetType::Singleton(pos)), feerate(depgraph.FeeRate(pos)) {}
377 : :
378 : : /** Construct a SetInfo for a set of transactions in a depgraph. */
379 : : explicit SetInfo(const DepGraph<SetType>& depgraph, const SetType& txn) noexcept :
380 : : transactions(txn), feerate(depgraph.FeeRate(txn)) {}
381 : :
382 : : /** Add a transaction to this SetInfo (which must not yet be in it). */
383 : : void Set(const DepGraph<SetType>& depgraph, DepGraphIndex pos) noexcept
384 : : {
385 : : Assume(!transactions[pos]);
386 : : transactions.Set(pos);
387 : : feerate += depgraph.FeeRate(pos);
388 : : }
389 : :
390 : : /** Add the transactions of other to this SetInfo (no overlap allowed). */
391 : 35913049 : SetInfo& operator|=(const SetInfo& other) noexcept
392 : : {
393 : 58932409 : Assume(!transactions.Overlaps(other.transactions));
394 : 35913049 : transactions |= other.transactions;
395 : 35913049 : feerate += other.feerate;
396 : 35913049 : return *this;
397 : : }
398 : :
399 : : /** Remove the transactions of other from this SetInfo (which must be a subset). */
400 : 15279998 : SetInfo& operator-=(const SetInfo& other) noexcept
401 : : {
402 : 25131144 : Assume(other.transactions.IsSubsetOf(transactions));
403 : 15279998 : transactions -= other.transactions;
404 : 15279998 : feerate -= other.feerate;
405 : 15279998 : return *this;
406 : : }
407 : :
408 : : /** Compute the difference between this and other SetInfo (which must be a subset). */
409 : 1355795 : SetInfo operator-(const SetInfo& other) const noexcept
410 : : {
411 : 1355795 : Assume(other.transactions.IsSubsetOf(transactions));
412 : 1355795 : return {transactions - other.transactions, feerate - other.feerate};
413 : : }
414 : :
415 : : /** Swap two SetInfo objects. */
416 : : friend void swap(SetInfo& a, SetInfo& b) noexcept
417 : : {
418 : : swap(a.transactions, b.transactions);
419 : : swap(a.feerate, b.feerate);
420 : : }
421 : :
422 : : /** Permit equality testing. */
423 : : friend bool operator==(const SetInfo&, const SetInfo&) noexcept = default;
424 : : };
425 : :
426 : : /** Compute the chunks of linearization as SetInfos. */
427 : : template<typename SetType>
428 : 65637 : std::vector<SetInfo<SetType>> ChunkLinearizationInfo(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> linearization) noexcept
429 : : {
430 : 65637 : std::vector<SetInfo<SetType>> ret;
431 [ + + ]: 392663 : for (DepGraphIndex i : linearization) {
432 : : /** The new chunk to be added, initially a singleton. */
433 : 327026 : SetInfo<SetType> new_chunk(depgraph, i);
434 : : // As long as the new chunk has a higher feerate than the last chunk so far, absorb it.
435 [ + + + + ]: 356717 : while (!ret.empty() && new_chunk.feerate >> ret.back().feerate) {
436 : 29691 : new_chunk |= ret.back();
437 : 29691 : ret.pop_back();
438 : : }
439 : : // Actually move that new chunk into the chunking.
440 : 327026 : ret.emplace_back(std::move(new_chunk));
441 : : }
442 : 65637 : return ret;
443 : : }
444 : :
445 : : /** Compute the feerates of the chunks of linearization. Identical to ChunkLinearizationInfo, but
446 : : * only returns the chunk feerates, not the corresponding transaction sets. */
447 : : template<typename SetType>
448 : 399 : std::vector<FeeFrac> ChunkLinearization(const DepGraph<SetType>& depgraph, std::span<const DepGraphIndex> linearization) noexcept
449 : : {
450 : 399 : std::vector<FeeFrac> ret;
451 [ + + ]: 2284 : for (DepGraphIndex i : linearization) {
452 : : /** The new chunk to be added, initially a singleton. */
453 : 1885 : auto new_chunk = depgraph.FeeRate(i);
454 : : // As long as the new chunk has a higher feerate than the last chunk so far, absorb it.
455 [ + + + + ]: 2523 : while (!ret.empty() && new_chunk >> ret.back()) {
456 : 638 : new_chunk += ret.back();
457 : 638 : ret.pop_back();
458 : : }
459 : : // Actually move that new chunk into the chunking.
460 : 1885 : ret.push_back(std::move(new_chunk));
461 : : }
462 : 399 : return ret;
463 : : }
464 : :
465 : : /** Concept for function objects that return std::strong_ordering when invoked with two Args. */
466 : : template<typename F, typename Arg>
467 : : concept StrongComparator =
468 : : std::regular_invocable<F, Arg, Arg> &&
469 : : std::is_same_v<std::invoke_result_t<F, Arg, Arg>, std::strong_ordering>;
470 : :
471 : : /** Simple default transaction ordering function for SpanningForestState::GetLinearization() and
472 : : * Linearize(), which just sorts by DepGraphIndex. */
473 : : using IndexTxOrder = std::compare_three_way;
474 : :
475 : : /** Class to represent the internal state of the spanning-forest linearization (SFL) algorithm.
476 : : *
477 : : * At all times, each dependency is marked as either "active" or "inactive". The subset of active
478 : : * dependencies is the state of the SFL algorithm. The implementation maintains several other
479 : : * values to speed up operations, but everything is ultimately a function of what that subset of
480 : : * active dependencies is.
481 : : *
482 : : * Given such a subset, define a chunk as the set of transactions that are connected through active
483 : : * dependencies (ignoring their parent/child direction). Thus, every state implies a particular
484 : : * partitioning of the graph into chunks (including potential singletons). In the extreme, each
485 : : * transaction may be in its own chunk, or in the other extreme all transactions may form a single
486 : : * chunk. A chunk's feerate is its total fee divided by its total size.
487 : : *
488 : : * The algorithm consists of switching dependencies between active and inactive. The final
489 : : * linearization that is produced at the end consists of these chunks, sorted from high to low
490 : : * feerate, each individually sorted in an arbitrary but topological (= no child before parent)
491 : : * way.
492 : : *
493 : : * We define four quality properties the state can have:
494 : : *
495 : : * - acyclic: The state is acyclic whenever no cycle of active dependencies exists within the
496 : : * graph, ignoring the parent/child direction. This is equivalent to saying that within
497 : : * each chunk the set of active dependencies form a tree, and thus the overall set of
498 : : * active dependencies in the graph form a spanning forest, giving the algorithm its
499 : : * name. Being acyclic is also equivalent to every chunk of N transactions having
500 : : * exactly N-1 active dependencies.
501 : : *
502 : : * For example in a diamond graph, D->{B,C}->A, the 4 dependencies cannot be
503 : : * simultaneously active. If at least one is inactive, the state is acyclic.
504 : : *
505 : : * The algorithm maintains an acyclic state at *all* times as an invariant. This implies
506 : : * that activating a dependency always corresponds to merging two chunks, and that
507 : : * deactivating one always corresponds to splitting two chunks.
508 : : *
509 : : * - topological: We say the state is topological whenever it is acyclic and no inactive dependency
510 : : * exists between two distinct chunks such that the child chunk has higher or equal
511 : : * feerate than the parent chunk.
512 : : *
513 : : * The relevance is that whenever the state is topological, the produced output
514 : : * linearization will be topological too (i.e., not have children before parents).
515 : : * Note that the "or equal" part of the definition matters: if not, one can end up
516 : : * in a situation with mutually-dependent equal-feerate chunks that cannot be
517 : : * linearized. For example C->{A,B} and D->{A,B}, with C->A and D->B active. The AC
518 : : * chunk depends on DB through C->B, and the BD chunk depends on AC through D->A.
519 : : * Merging them into a single ABCD chunk fixes this.
520 : : *
521 : : * The algorithm attempts to keep the state topological as much as possible, so it
522 : : * can be interrupted to produce an output whenever, but will sometimes need to
523 : : * temporarily deviate from it when improving the state.
524 : : *
525 : : * - optimal: For every active dependency, define its top and bottom set as the set of transactions
526 : : * in the chunks that would result if the dependency were deactivated; the top being the
527 : : * one with the dependency's parent, and the bottom being the one with the child. Note
528 : : * that due to acyclicity, every deactivation splits a chunk exactly in two.
529 : : *
530 : : * We say the state is optimal whenever it is topological and it has no active
531 : : * dependency whose top feerate is strictly higher than its bottom feerate. The
532 : : * relevance is that it can be proven that whenever the state is optimal, the produced
533 : : * linearization will also be optimal (in the convexified feerate diagram sense). It can
534 : : * also be proven that for every graph at least one optimal state exists.
535 : : *
536 : : * Note that it is possible for the SFL state to not be optimal, but the produced
537 : : * linearization to still be optimal. This happens when the chunks of a state are
538 : : * identical to those of an optimal state, but the exact set of active dependencies
539 : : * within a chunk differ in such a way that the state optimality condition is not
540 : : * satisfied. Thus, the state being optimal is more a "the eventual output is *known*
541 : : * to be optimal".
542 : : *
543 : : * - minimal: We say the state is minimal when it is:
544 : : * - acyclic
545 : : * - topological, except that inactive dependencies between equal-feerate chunks are
546 : : * allowed as long as they do not form a loop.
547 : : * - like optimal, no active dependencies whose top feerate is strictly higher than
548 : : * the bottom feerate are allowed.
549 : : * - no chunk contains a proper non-empty subset which includes all its own in-chunk
550 : : * dependencies of the same feerate as the chunk itself.
551 : : *
552 : : * A minimal state effectively corresponds to an optimal state, where every chunk has
553 : : * been split into its minimal equal-feerate components.
554 : : *
555 : : * The algorithm terminates whenever a minimal state is reached.
556 : : *
557 : : *
558 : : * This leads to the following high-level algorithm:
559 : : * - Start with all dependencies inactive, and thus all transactions in their own chunk. This is
560 : : * definitely acyclic.
561 : : * - Activate dependencies (merging chunks) until the state is topological.
562 : : * - Loop until optimal (no dependencies with higher-feerate top than bottom), or time runs out:
563 : : * - Deactivate a violating dependency, potentially making the state non-topological.
564 : : * - Activate other dependencies to make the state topological again.
565 : : * - If there is time left and the state is optimal:
566 : : * - Attempt to split chunks into equal-feerate parts without mutual dependencies between them.
567 : : * When this succeeds, recurse into them.
568 : : * - If no such chunks can be found, the state is minimal.
569 : : * - Output the chunks from high to low feerate, each internally sorted topologically.
570 : : *
571 : : * When merging, we always either:
572 : : * - Merge upwards: merge a chunk with the lowest-feerate other chunk it depends on, among those
573 : : * with lower or equal feerate than itself.
574 : : * - Merge downwards: merge a chunk with the highest-feerate other chunk that depends on it, among
575 : : * those with higher or equal feerate than itself.
576 : : *
577 : : * Using these strategies in the improvement loop above guarantees that the output linearization
578 : : * after a deactivate + merge step is never worse or incomparable (in the convexified feerate
579 : : * diagram sense) than the output linearization that would be produced before the step. With that,
580 : : * we can refine the high-level algorithm to:
581 : : * - Start with all dependencies inactive.
582 : : * - Perform merges as described until none are possible anymore, making the state topological.
583 : : * - Loop until optimal or time runs out:
584 : : * - Pick a dependency D to deactivate among those with higher feerate top than bottom.
585 : : * - Deactivate D, causing the chunk it is in to split into top T and bottom B.
586 : : * - Do an upwards merge of T, if possible. If so, repeat the same with the merged result.
587 : : * - Do a downwards merge of B, if possible. If so, repeat the same with the merged result.
588 : : * - Split chunks further to obtain a minimal state, see below.
589 : : * - Output the chunks from high to low feerate, each internally sorted topologically.
590 : : *
591 : : * Instead of performing merges arbitrarily to make the initial state topological, it is possible
592 : : * to do so guided by an existing linearization. This has the advantage that the state's would-be
593 : : * output linearization is immediately as good as the existing linearization it was based on:
594 : : * - Start with all dependencies inactive.
595 : : * - For each transaction t in the existing linearization:
596 : : * - Find the chunk C that transaction is in (which will be singleton).
597 : : * - Do an upwards merge of C, if possible. If so, repeat the same with the merged result.
598 : : * No downwards merges are needed in this case.
599 : : *
600 : : * After reaching an optimal state, it can be transformed into a minimal state by attempting to
601 : : * split chunks further into equal-feerate parts. To do so, pick a specific transaction in each
602 : : * chunk (the pivot), and rerun the above split-then-merge procedure again:
603 : : * - first, while pretending the pivot transaction has an infinitesimally higher (or lower) fee
604 : : * than it really has. If a split exists with the pivot in the top part (or bottom part), this
605 : : * will find it.
606 : : * - if that fails to split, repeat while pretending the pivot transaction has an infinitesimally
607 : : * lower (or higher) fee. If a split exists with the pivot in the bottom part (or top part), this
608 : : * will find it.
609 : : * - if either succeeds, repeat the procedure for the newly found chunks to split them further.
610 : : * If not, the chunk is already minimal.
611 : : * If the chunk can be split into equal-feerate parts, then the pivot must exist in either the top
612 : : * or bottom part of that potential split. By trying both with the same pivot, if a split exists,
613 : : * it will be found.
614 : : *
615 : : * What remains to be specified are a number of heuristics:
616 : : *
617 : : * - How to decide which chunks to merge:
618 : : * - The merge upwards and downward rules specify that the lowest-feerate respectively
619 : : * highest-feerate candidate chunk is merged with, but if there are multiple equal-feerate
620 : : * candidates, a uniformly random one among them is picked.
621 : : *
622 : : * - How to decide what dependency to activate (when merging chunks):
623 : : * - After picking two chunks to be merged (see above), a uniformly random dependency between the
624 : : * two chunks is activated.
625 : : *
626 : : * - How to decide which chunk to find a dependency to split in:
627 : : * - A round-robin queue of chunks to improve is maintained. The initial ordering of this queue
628 : : * is uniformly randomly permuted.
629 : : *
630 : : * - How to decide what dependency to deactivate (when splitting chunks):
631 : : * - Inside the selected chunk (see above), among the dependencies whose top feerate is strictly
632 : : * higher than its bottom feerate in the selected chunk, if any, a uniformly random dependency
633 : : * is deactivated.
634 : : *
635 : : * - How to decide the exact output linearization:
636 : : * - When there are multiple equal-feerate chunks with no dependencies between them, output a
637 : : * uniformly random one among the ones with no missing dependent chunks first.
638 : : * - Within chunks, repeatedly pick a uniformly random transaction among those with no missing
639 : : * dependencies.
640 : : */
641 : : template<typename SetType>
642 : : class SpanningForestState
643 : : {
644 : : private:
645 : : /** Internal RNG. */
646 : : InsecureRandomContext m_rng;
647 : :
648 : : /** Data type to represent indexing into m_tx_data. */
649 : : using TxIdx = DepGraphIndex;
650 : : /** Data type to represent indexing into m_dep_data. */
651 : : using DepIdx = uint32_t;
652 : :
653 : : /** Structure with information about a single transaction. For transactions that are the
654 : : * representative for the chunk they are in, this also stores chunk information. */
655 : 7012720 : struct TxData {
656 : : /** The dependencies to children of this transaction. Immutable after construction. */
657 : : std::vector<DepIdx> child_deps;
658 : : /** The set of parent transactions of this transaction. Immutable after construction. */
659 : : SetType parents;
660 : : /** The set of child transactions of this transaction. Immutable after construction. */
661 : : SetType children;
662 : : /** Which transaction holds the chunk_setinfo for the chunk this transaction is in
663 : : * (the representative for the chunk). */
664 : : TxIdx chunk_rep;
665 : : /** (Only if this transaction is the representative for the chunk it is in) the total
666 : : * chunk set and feerate. */
667 : : SetInfo<SetType> chunk_setinfo;
668 : : };
669 : :
670 : : /** Structure with information about a single dependency. */
671 : 15043838 : struct DepData {
672 : : /** Whether this dependency is active. */
673 : : bool active;
674 : : /** What the parent and child transactions are. Immutable after construction. */
675 : : TxIdx parent, child;
676 : : /** (Only if this dependency is active) the would-be top chunk and its feerate that would
677 : : * be formed if this dependency were to be deactivated. */
678 : : SetInfo<SetType> top_setinfo;
679 : : };
680 : :
681 : : /** The set of all TxIdx's of transactions in the cluster indexing into m_tx_data. */
682 : : SetType m_transaction_idxs;
683 : : /** Information about each transaction (and chunks). Keeps the "holes" from DepGraph during
684 : : * construction. Indexed by TxIdx. */
685 : : std::vector<TxData> m_tx_data;
686 : : /** Information about each dependency. Indexed by DepIdx. */
687 : : std::vector<DepData> m_dep_data;
688 : : /** A FIFO of chunk representatives of chunks that may be improved still. */
689 : : VecDeque<TxIdx> m_suboptimal_chunks;
690 : : /** A FIFO of chunk representatives with a pivot transaction in them, and a flag to indicate
691 : : * their status:
692 : : * - bit 1: currently attempting to move the pivot down, rather than up.
693 : : * - bit 2: this is the second stage, so we have already tried moving the pivot in the other
694 : : * direction.
695 : : */
696 : : VecDeque<std::tuple<TxIdx, TxIdx, unsigned>> m_nonminimal_chunks;
697 : :
698 : : /** The number of updated transactions in activations/deactivations. */
699 : : uint64_t m_cost{0};
700 : :
701 : : /** The DepGraph we are trying to linearize. */
702 : : const DepGraph<SetType>& m_depgraph;
703 : :
704 : : /** Pick a random transaction within a set (which must be non-empty). */
705 : 1794121 : TxIdx PickRandomTx(const SetType& tx_idxs) noexcept
706 : : {
707 : 2901521 : Assume(tx_idxs.Any());
708 : 1794121 : unsigned pos = m_rng.randrange<unsigned>(tx_idxs.Count());
709 [ + - + - ]: 4397122 : for (auto tx_idx : tx_idxs) {
710 [ + + ]: 3710401 : if (pos == 0) return tx_idx;
711 : 1916280 : --pos;
712 : : }
713 : 0 : Assume(false);
714 : 0 : return TxIdx(-1);
715 : : }
716 : :
717 : : /** Update a chunk:
718 : : * - All transactions have their chunk representative set to `chunk_rep`.
719 : : * - All dependencies which have `query` in their top_setinfo get `dep_change` added to it
720 : : * (if `!Subtract`) or removed from it (if `Subtract`).
721 : : */
722 : : template<bool Subtract>
723 : 12000682 : void UpdateChunk(const SetType& chunk, TxIdx query, TxIdx chunk_rep, const SetInfo<SetType>& dep_change) noexcept
724 : : {
725 : : // Iterate over all the chunk's transactions.
726 [ + + + + ]: 106103958 : for (auto tx_idx : chunk) {
727 [ - + ]: 89623150 : auto& tx_data = m_tx_data[tx_idx];
728 : : // Update the chunk representative.
729 : 89623150 : tx_data.chunk_rep = chunk_rep;
730 : : // Iterate over all active dependencies with tx_idx as parent. Combined with the outer
731 : : // loop this iterates over all internal active dependencies of the chunk.
732 [ - + ]: 89623150 : auto child_deps = std::span{tx_data.child_deps};
733 [ + + ]: 594692666 : for (auto dep_idx : child_deps) {
734 [ + + ]: 505069516 : auto& dep_entry = m_dep_data[dep_idx];
735 [ + + ]: 505069516 : Assume(dep_entry.parent == tx_idx);
736 : : // Skip inactive dependencies.
737 [ + + ]: 505069516 : if (!dep_entry.active) continue;
738 : : // If this dependency's top_setinfo contains query, update it to add/remove
739 : : // dep_change.
740 [ + + ]: 77622468 : if (dep_entry.top_setinfo.transactions[query]) {
741 : : if constexpr (Subtract) {
742 : 15279998 : dep_entry.top_setinfo -= dep_change;
743 : : } else {
744 : 31238812 : dep_entry.top_setinfo |= dep_change;
745 : : }
746 : : }
747 : : }
748 : : }
749 : 12000682 : }
750 : :
751 : : /** Make a specified inactive dependency active. Returns the merged chunk representative. */
752 : 4644546 : TxIdx Activate(DepIdx dep_idx) noexcept
753 : : {
754 : 4644546 : auto& dep_data = m_dep_data[dep_idx];
755 : 4644546 : Assume(!dep_data.active);
756 : 4644546 : auto& child_tx_data = m_tx_data[dep_data.child];
757 : 4644546 : auto& parent_tx_data = m_tx_data[dep_data.parent];
758 : :
759 : : // Gather information about the parent and child chunks.
760 : 4644546 : Assume(parent_tx_data.chunk_rep != child_tx_data.chunk_rep);
761 : 4644546 : auto& par_chunk_data = m_tx_data[parent_tx_data.chunk_rep];
762 : 4644546 : auto& chl_chunk_data = m_tx_data[child_tx_data.chunk_rep];
763 : 4644546 : TxIdx top_rep = parent_tx_data.chunk_rep;
764 : 4644546 : auto top_part = par_chunk_data.chunk_setinfo;
765 : 4644546 : auto bottom_part = chl_chunk_data.chunk_setinfo;
766 : : // Update the parent chunk to also contain the child.
767 : 4644546 : par_chunk_data.chunk_setinfo |= bottom_part;
768 : 4644546 : m_cost += par_chunk_data.chunk_setinfo.transactions.Count();
769 : :
770 : : // Consider the following example:
771 : : //
772 : : // A A There are two chunks, ABC and DEF, and the inactive E->C dependency
773 : : // / \ / \ is activated, resulting in a single chunk ABCDEF.
774 : : // B C B C
775 : : // : ==> | Dependency | top set before | top set after | change
776 : : // D E D E B->A | AC | ACDEF | +DEF
777 : : // \ / \ / C->A | AB | AB |
778 : : // F F F->D | D | D |
779 : : // F->E | E | ABCE | +ABC
780 : : //
781 : : // The common pattern here is that any dependency which has the parent or child of the
782 : : // dependency being activated (E->C here) in its top set, will have the opposite part added
783 : : // to it. This is true for B->A and F->E, but not for C->A and F->D.
784 : : //
785 : : // Let UpdateChunk traverse the old parent chunk top_part (ABC in example), and add
786 : : // bottom_part (DEF) to every dependency's top_set which has the parent (C) in it. The
787 : : // representative of each of these transactions was already top_rep, so that is not being
788 : : // changed here.
789 : 4644546 : UpdateChunk<false>(/*chunk=*/top_part.transactions, /*query=*/dep_data.parent,
790 : : /*chunk_rep=*/top_rep, /*dep_change=*/bottom_part);
791 : : // Let UpdateChunk traverse the old child chunk bottom_part (DEF in example), and add
792 : : // top_part (ABC) to every dependency's top_set which has the child (E) in it. At the same
793 : : // time, change the representative of each of these transactions to be top_rep, which
794 : : // becomes the representative for the merged chunk.
795 : 4644546 : UpdateChunk<false>(/*chunk=*/bottom_part.transactions, /*query=*/dep_data.child,
796 : : /*chunk_rep=*/top_rep, /*dep_change=*/top_part);
797 : : // Make active.
798 : 4644546 : dep_data.active = true;
799 : 4644546 : dep_data.top_setinfo = top_part;
800 : 4644546 : return top_rep;
801 : : }
802 : :
803 : : /** Make a specified active dependency inactive. */
804 : 1355795 : void Deactivate(DepIdx dep_idx) noexcept
805 : : {
806 : 1355795 : auto& dep_data = m_dep_data[dep_idx];
807 : 1355795 : Assume(dep_data.active);
808 : 1355795 : auto& parent_tx_data = m_tx_data[dep_data.parent];
809 : : // Make inactive.
810 : 1355795 : dep_data.active = false;
811 : : // Update representatives.
812 : 1355795 : auto& chunk_data = m_tx_data[parent_tx_data.chunk_rep];
813 : 1355795 : m_cost += chunk_data.chunk_setinfo.transactions.Count();
814 : 1355795 : auto top_part = dep_data.top_setinfo;
815 : 1355795 : auto bottom_part = chunk_data.chunk_setinfo - top_part;
816 : 1355795 : TxIdx bottom_rep = dep_data.child;
817 : 1355795 : auto& bottom_chunk_data = m_tx_data[bottom_rep];
818 : 1355795 : bottom_chunk_data.chunk_setinfo = bottom_part;
819 : 1355795 : TxIdx top_rep = dep_data.parent;
820 : 1355795 : auto& top_chunk_data = m_tx_data[top_rep];
821 : 1355795 : top_chunk_data.chunk_setinfo = top_part;
822 : :
823 : : // See the comment above in Activate(). We perform the opposite operations here,
824 : : // removing instead of adding.
825 : : //
826 : : // Let UpdateChunk traverse the old parent chunk top_part, and remove bottom_part from
827 : : // every dependency's top_set which has the parent in it. At the same time, change the
828 : : // representative of each of these transactions to be top_rep.
829 : 1355795 : UpdateChunk<true>(/*chunk=*/top_part.transactions, /*query=*/dep_data.parent,
830 : : /*chunk_rep=*/top_rep, /*dep_change=*/bottom_part);
831 : : // Let UpdateChunk traverse the old child chunk bottom_part, and remove top_part from every
832 : : // dependency's top_set which has the child in it. At the same time, change the
833 : : // representative of each of these transactions to be bottom_rep.
834 : 1355795 : UpdateChunk<true>(/*chunk=*/bottom_part.transactions, /*query=*/dep_data.child,
835 : : /*chunk_rep=*/bottom_rep, /*dep_change=*/top_part);
836 : 1355795 : }
837 : :
838 : : /** Activate a dependency from the chunk represented by bottom_idx to the chunk represented by
839 : : * top_idx. Return the representative of the merged chunk, or TxIdx(-1) if no merge is
840 : : * possible. */
841 : 4932641 : TxIdx MergeChunks(TxIdx top_rep, TxIdx bottom_rep) noexcept
842 : : {
843 [ + - ]: 4932641 : auto& top_chunk = m_tx_data[top_rep];
844 [ + - ]: 4932641 : Assume(top_chunk.chunk_rep == top_rep);
845 : 4932641 : auto& bottom_chunk = m_tx_data[bottom_rep];
846 : 4932641 : Assume(bottom_chunk.chunk_rep == bottom_rep);
847 : : // Count the number of dependencies between bottom_chunk and top_chunk.
848 : 4932641 : TxIdx num_deps{0};
849 [ + + + + ]: 47113265 : for (auto tx : top_chunk.chunk_setinfo.transactions) {
850 : 40318522 : auto& tx_data = m_tx_data[tx];
851 : 40318522 : num_deps += (tx_data.children & bottom_chunk.chunk_setinfo.transactions).Count();
852 : : }
853 [ + + ]: 4932641 : if (num_deps == 0) return TxIdx(-1);
854 : : // Uniformly randomly pick one of them and activate it.
855 : 4644546 : TxIdx pick = m_rng.randrange(num_deps);
856 [ + - + - ]: 18569115 : for (auto tx : top_chunk.chunk_setinfo.transactions) {
857 [ + + ]: 16848508 : auto& tx_data = m_tx_data[tx];
858 [ + + ]: 16848508 : auto intersect = tx_data.children & bottom_chunk.chunk_setinfo.transactions;
859 : 16848508 : auto count = intersect.Count();
860 [ + + ]: 16848508 : if (pick < count) {
861 [ + - ]: 30744177 : for (auto dep : tx_data.child_deps) {
862 [ + + ]: 30744177 : auto& dep_data = m_dep_data[dep];
863 [ + + ]: 30744177 : if (bottom_chunk.chunk_setinfo.transactions[dep_data.child]) {
864 [ + + ]: 6074964 : if (pick == 0) return Activate(dep);
865 : 1430418 : --pick;
866 : : }
867 : : }
868 : : break;
869 : : }
870 : 12203962 : pick -= count;
871 : : }
872 : 0 : Assume(false);
873 : 0 : return TxIdx(-1);
874 : : }
875 : :
876 : : /** Perform an upward or downward merge step, on the specified chunk representative. Returns
877 : : * the representative of the merged chunk, or TxIdx(-1) if no merge took place. */
878 : : template<bool DownWard>
879 : 12936197 : TxIdx MergeStep(TxIdx chunk_rep) noexcept
880 : : {
881 : : /** Information about the chunk that tx_idx is currently in. */
882 [ + - ]: 12936197 : auto& chunk_data = m_tx_data[chunk_rep];
883 : 12936197 : SetType chunk_txn = chunk_data.chunk_setinfo.transactions;
884 : : // Iterate over all transactions in the chunk, figuring out which other chunk each
885 : : // depends on, but only testing each other chunk once. For those depended-on chunks,
886 : : // remember the highest-feerate (if DownWard) or lowest-feerate (if !DownWard) one.
887 : : // If multiple equal-feerate candidate chunks to merge with exist, pick a random one
888 : : // among them.
889 : :
890 : : /** Which transactions have been reached from this chunk already. Initialize with the
891 : : * chunk itself, so internal dependencies within the chunk are ignored. */
892 : 12936197 : SetType explored = chunk_txn;
893 : : /** The minimum feerate (if downward) or maximum feerate (if upward) to consider when
894 : : * looking for candidate chunks to merge with. Initially, this is the original chunk's
895 : : * feerate, but is updated to be the current best candidate whenever one is found. */
896 : 12936197 : FeeFrac best_other_chunk_feerate = chunk_data.chunk_setinfo.feerate;
897 : : /** The representative for the best candidate chunk to merge with. -1 if none. */
898 : 12936197 : TxIdx best_other_chunk_rep = TxIdx(-1);
899 : : /** We generate random tiebreak values to pick between equal-feerate candidate chunks.
900 : : * This variable stores the tiebreak of the current best candidate. */
901 : 12936197 : uint64_t best_other_chunk_tiebreak{0};
902 [ + + + + ]: 139931424 : for (auto tx : chunk_txn) {
903 : 122235448 : auto& tx_data = m_tx_data[tx];
904 : : /** The transactions reached by following dependencies from tx that have not been
905 : : * explored before. */
906 : 122235448 : auto newly_reached = (DownWard ? tx_data.children : tx_data.parents) - explored;
907 : 151176128 : explored |= newly_reached;
908 [ + + ]: 273846751 : while (newly_reached.Any()) {
909 : : // Find a chunk inside newly_reached, and remove it from newly_reached.
910 [ + + ]: 44341982 : auto reached_chunk_rep = m_tx_data[newly_reached.First()].chunk_rep;
911 : 44341982 : auto& reached_chunk = m_tx_data[reached_chunk_rep].chunk_setinfo;
912 [ + + ]: 44341982 : newly_reached -= reached_chunk.transactions;
913 : : // See if it has an acceptable feerate.
914 [ + + ]: 10185330 : auto cmp = DownWard ? FeeRateCompare(best_other_chunk_feerate, reached_chunk.feerate)
915 [ + + ]: 34156652 : : FeeRateCompare(reached_chunk.feerate, best_other_chunk_feerate);
916 [ + + ]: 44341982 : if (cmp > 0) continue;
917 [ + + ]: 7150618 : uint64_t tiebreak = m_rng.rand64();
918 [ + + + + ]: 7150618 : if (cmp < 0 || tiebreak >= best_other_chunk_tiebreak) {
919 : 6247567 : best_other_chunk_feerate = reached_chunk.feerate;
920 : 6247567 : best_other_chunk_rep = reached_chunk_rep;
921 : 6247567 : best_other_chunk_tiebreak = tiebreak;
922 : : }
923 : : }
924 : : }
925 : : // Stop if there are no candidate chunks to merge with.
926 [ + + ]: 12936197 : if (best_other_chunk_rep == TxIdx(-1)) return TxIdx(-1);
927 : : if constexpr (DownWard) {
928 : 439320 : chunk_rep = MergeChunks(chunk_rep, best_other_chunk_rep);
929 : : } else {
930 : 4204558 : chunk_rep = MergeChunks(best_other_chunk_rep, chunk_rep);
931 : : }
932 : 4643878 : Assume(chunk_rep != TxIdx(-1));
933 : 4643878 : return chunk_rep;
934 : : }
935 : :
936 : :
937 : : /** Perform an upward or downward merge sequence on the specified transaction. */
938 : : template<bool DownWard>
939 : 2134064 : void MergeSequence(TxIdx tx_idx) noexcept
940 : : {
941 : 2134064 : auto chunk_rep = m_tx_data[tx_idx].chunk_rep;
942 : 867450 : while (true) {
943 : 3001514 : auto merged_rep = MergeStep<DownWard>(chunk_rep);
944 [ + + ]: 3001514 : if (merged_rep == TxIdx(-1)) break;
945 : 867450 : chunk_rep = merged_rep;
946 : : }
947 : : // Add the chunk to the queue of improvable chunks.
948 : 2134064 : m_suboptimal_chunks.push_back(chunk_rep);
949 : 2134064 : }
950 : :
951 : : /** Split a chunk, and then merge the resulting two chunks to make the graph topological
952 : : * again. */
953 : 1067032 : void Improve(DepIdx dep_idx) noexcept
954 : : {
955 : 1067032 : auto& dep_data = m_dep_data[dep_idx];
956 : 1067032 : Assume(dep_data.active);
957 : : // Deactivate the specified dependency, splitting it into two new chunks: a top containing
958 : : // the parent, and a bottom containing the child. The top should have a higher feerate.
959 : 1067032 : Deactivate(dep_idx);
960 : :
961 : : // At this point we have exactly two chunks which may violate topology constraints (the
962 : : // parent chunk and child chunk that were produced by deactivating dep_idx). We can fix
963 : : // these using just merge sequences, one upwards and one downwards, avoiding the need for a
964 : : // full MakeTopological.
965 : :
966 : : // Merge the top chunk with lower-feerate chunks it depends on (which may be the bottom it
967 : : // was just split from, or other pre-existing chunks).
968 : 1067032 : MergeSequence<false>(dep_data.parent);
969 : : // Merge the bottom chunk with higher-feerate chunks that depend on it.
970 : 1067032 : MergeSequence<true>(dep_data.child);
971 : 1067032 : }
972 : :
973 : : public:
974 : : /** Construct a spanning forest for the given DepGraph, with every transaction in its own chunk
975 : : * (not topological). */
976 : 191932 : explicit SpanningForestState(const DepGraph<SetType>& depgraph LIFETIMEBOUND, uint64_t rng_seed) noexcept :
977 [ - + ]: 191932 : m_rng(rng_seed), m_depgraph(depgraph)
978 : : {
979 : 191932 : m_transaction_idxs = depgraph.Positions();
980 [ - + ]: 191932 : auto num_transactions = m_transaction_idxs.Count();
981 [ - + ]: 191932 : m_tx_data.resize(depgraph.PositionRange());
982 : : // Reserve the maximum number of (reserved) dependencies the cluster can have, so
983 : : // m_dep_data won't need any reallocations during construction. For a cluster with N
984 : : // transactions, the worst case consists of two sets of transactions, the parents and the
985 : : // children, where each child depends on each parent and nothing else. For even N, both
986 : : // sets can be sized N/2, which means N^2/4 dependencies. For odd N, one can be (N + 1)/2
987 : : // and the other can be (N - 1)/2, meaning (N^2 - 1)/4 dependencies. Because N^2 is odd in
988 : : // this case, N^2/4 (with rounding-down division) is the correct value in both cases.
989 : 191932 : m_dep_data.reserve((num_transactions * num_transactions) / 4);
990 [ + + + + ]: 5351024 : for (auto tx : m_transaction_idxs) {
991 : : // Fill in transaction data.
992 : 5082960 : auto& tx_data = m_tx_data[tx];
993 : 5082960 : tx_data.chunk_rep = tx;
994 : 5082960 : tx_data.chunk_setinfo.transactions = SetType::Singleton(tx);
995 : 5082960 : tx_data.chunk_setinfo.feerate = depgraph.FeeRate(tx);
996 : : // Add its dependencies.
997 : 5082960 : SetType parents = depgraph.GetReducedParents(tx);
998 [ + + + + ]: 21623416 : for (auto par : parents) {
999 [ - + ]: 15043838 : auto& par_tx_data = m_tx_data[par];
1000 [ - + ]: 15043838 : auto dep_idx = m_dep_data.size();
1001 : : // Construct new dependency.
1002 : 15043838 : auto& dep = m_dep_data.emplace_back();
1003 : 15043838 : dep.active = false;
1004 : 15043838 : dep.parent = par;
1005 : 15043838 : dep.child = tx;
1006 : : // Add it as parent of the child.
1007 : 15043838 : tx_data.parents.Set(par);
1008 : : // Add it as child of the parent.
1009 : 15043838 : par_tx_data.child_deps.push_back(dep_idx);
1010 : 15043838 : par_tx_data.children.Set(tx);
1011 : : }
1012 : : }
1013 : 191932 : }
1014 : :
1015 : : /** Load an existing linearization. Must be called immediately after constructor. The result is
1016 : : * topological if the linearization is valid. Otherwise, MakeTopological still needs to be
1017 : : * called. */
1018 : 144656 : void LoadLinearization(std::span<const DepGraphIndex> old_linearization) noexcept
1019 : : {
1020 : : // Add transactions one by one, in order of existing linearization.
1021 [ + + ]: 3952593 : for (DepGraphIndex tx : old_linearization) {
1022 : 3807937 : auto chunk_rep = m_tx_data[tx].chunk_rep;
1023 : : // Merge the chunk upwards, as long as merging succeeds.
1024 : : while (true) {
1025 : 6588346 : chunk_rep = MergeStep<false>(chunk_rep);
1026 [ + + ]: 6588346 : if (chunk_rep == TxIdx(-1)) break;
1027 : : }
1028 : : }
1029 : 144656 : }
1030 : :
1031 : : /** Make state topological. Can be called after constructing, or after LoadLinearization. */
1032 : 99376 : void MakeTopological() noexcept
1033 : : {
1034 [ + + + + ]: 2732668 : for (auto tx : m_transaction_idxs) {
1035 [ + + ]: 2592376 : auto& tx_data = m_tx_data[tx];
1036 [ + + ]: 2592376 : if (tx_data.chunk_rep == tx) {
1037 : 1612272 : m_suboptimal_chunks.emplace_back(tx);
1038 : : // Randomize the initial order of suboptimal chunks in the queue.
1039 : 1612272 : TxIdx j = m_rng.randrange<TxIdx>(m_suboptimal_chunks.size());
1040 [ + + ]: 1612272 : if (j != m_suboptimal_chunks.size() - 1) {
1041 : 1337142 : std::swap(m_suboptimal_chunks.back(), m_suboptimal_chunks[j]);
1042 : : }
1043 : : }
1044 : : }
1045 [ + + ]: 2707667 : while (!m_suboptimal_chunks.empty()) {
1046 : : // Pop an entry from the potentially-suboptimal chunk queue.
1047 : 2608291 : TxIdx chunk = m_suboptimal_chunks.front();
1048 : 2608291 : m_suboptimal_chunks.pop_front();
1049 [ + + ]: 2608291 : auto& chunk_data = m_tx_data[chunk];
1050 : : // If what was popped is not currently a chunk representative, continue. This may
1051 : : // happen when it was merged with something else since being added.
1052 [ + + ]: 2608291 : if (chunk_data.chunk_rep != chunk) continue;
1053 : 1967797 : int flip = m_rng.randbool();
1054 [ + + ]: 4318115 : for (int i = 0; i < 2; ++i) {
1055 [ + + ]: 3346337 : if (i ^ flip) {
1056 : : // Attempt to merge the chunk upwards.
1057 : 1719093 : auto result_up = MergeStep<false>(chunk);
1058 [ + + ]: 1719093 : if (result_up != TxIdx(-1)) {
1059 : 588631 : m_suboptimal_chunks.push_back(result_up);
1060 : : break;
1061 : : }
1062 : : } else {
1063 : : // Attempt to merge the chunk downwards.
1064 : 1627244 : auto result_down = MergeStep<true>(chunk);
1065 [ + + ]: 1627244 : if (result_down != TxIdx(-1)) {
1066 : 407388 : m_suboptimal_chunks.push_back(result_down);
1067 : : break;
1068 : : }
1069 : : }
1070 : : }
1071 : : }
1072 : 99376 : }
1073 : :
1074 : : /** Initialize the data structure for optimization. It must be topological already. */
1075 : 191848 : void StartOptimizing() noexcept
1076 : : {
1077 : : // Mark chunks suboptimal.
1078 [ + + + + ]: 5345708 : for (auto tx : m_transaction_idxs) {
1079 [ + + ]: 5077812 : auto& tx_data = m_tx_data[tx];
1080 [ + + ]: 5077812 : if (tx_data.chunk_rep == tx) {
1081 : 1306444 : m_suboptimal_chunks.push_back(tx);
1082 : : // Randomize the initial order of suboptimal chunks in the queue.
1083 : 1306444 : TxIdx j = m_rng.randrange<TxIdx>(m_suboptimal_chunks.size());
1084 [ + + ]: 1306444 : if (j != m_suboptimal_chunks.size() - 1) {
1085 : 922432 : std::swap(m_suboptimal_chunks.back(), m_suboptimal_chunks[j]);
1086 : : }
1087 : : }
1088 : : }
1089 : 191848 : }
1090 : :
1091 : : /** Try to improve the forest. Returns false if it is optimal, true otherwise. */
1092 : 2713955 : bool OptimizeStep() noexcept
1093 : : {
1094 [ + - ]: 3440508 : while (!m_suboptimal_chunks.empty()) {
1095 : : // Pop an entry from the potentially-suboptimal chunk queue.
1096 : 3440508 : TxIdx chunk = m_suboptimal_chunks.front();
1097 : 3440508 : m_suboptimal_chunks.pop_front();
1098 [ + + ]: 3440508 : auto& chunk_data = m_tx_data[chunk];
1099 : : // If what was popped is not currently a chunk representative, continue. This may
1100 : : // happen when a split chunk merges in Improve() with one or more existing chunks that
1101 : : // are themselves on the suboptimal queue already.
1102 [ + + ]: 3440508 : if (chunk_data.chunk_rep != chunk) continue;
1103 : : // Remember the best dependency seen so far.
1104 : 2713955 : DepIdx candidate_dep = DepIdx(-1);
1105 : 2713955 : uint64_t candidate_tiebreak = 0;
1106 : : // Iterate over all transactions.
1107 [ + + + + ]: 36905853 : for (auto tx : chunk_data.chunk_setinfo.transactions) {
1108 [ - + ]: 33216826 : const auto& tx_data = m_tx_data[tx];
1109 : : // Iterate over all active child dependencies of the transaction.
1110 [ - + ]: 33216826 : const auto children = std::span{tx_data.child_deps};
1111 [ + + ]: 250160367 : for (DepIdx dep_idx : children) {
1112 [ + + ]: 216943541 : const auto& dep_data = m_dep_data[dep_idx];
1113 [ + + ]: 216943541 : if (!dep_data.active) continue;
1114 : : // Skip if this dependency is ineligible (the top chunk that would be created
1115 : : // does not have higher feerate than the chunk it is currently part of).
1116 [ + + ]: 30502871 : auto cmp = FeeRateCompare(dep_data.top_setinfo.feerate, chunk_data.chunk_setinfo.feerate);
1117 [ + + ]: 30502871 : if (cmp <= 0) continue;
1118 : : // Generate a random tiebreak for this dependency, and reject it if its tiebreak
1119 : : // is worse than the best so far. This means that among all eligible
1120 : : // dependencies, a uniformly random one will be chosen.
1121 : 4901231 : uint64_t tiebreak = m_rng.rand64();
1122 [ + + ]: 4901231 : if (tiebreak < candidate_tiebreak) continue;
1123 : : // Remember this as our (new) candidate dependency.
1124 : : candidate_dep = dep_idx;
1125 : : candidate_tiebreak = tiebreak;
1126 : : }
1127 : : }
1128 : : // If a candidate with positive gain was found, deactivate it and then make the state
1129 : : // topological again with a sequence of merges.
1130 [ + + ]: 2713955 : if (candidate_dep != DepIdx(-1)) Improve(candidate_dep);
1131 : : // Stop processing for now, even if nothing was activated, as the loop above may have
1132 : : // had a nontrivial cost.
1133 : 2713955 : return !m_suboptimal_chunks.empty();
1134 : : }
1135 : : // No improvable chunk was found, we are done.
1136 : : return false;
1137 : : }
1138 : :
1139 : : /** Initialize data structure for minimizing the chunks. Can only be called if state is known
1140 : : * to be optimal. OptimizeStep() cannot be called anymore afterwards. */
1141 : 191848 : void StartMinimizing() noexcept
1142 : : {
1143 [ + - ]: 191848 : m_nonminimal_chunks.clear();
1144 [ + - ]: 191848 : m_nonminimal_chunks.reserve(m_transaction_idxs.Count());
1145 : : // Gather all chunks, and for each, add it with a random pivot in it, and a random initial
1146 : : // direction, to m_nonminimal_chunks.
1147 [ + + + + ]: 5345708 : for (auto tx : m_transaction_idxs) {
1148 [ + + ]: 5077812 : auto& tx_data = m_tx_data[tx];
1149 [ + + ]: 5077812 : if (tx_data.chunk_rep == tx) {
1150 : 1506026 : TxIdx pivot_idx = PickRandomTx(tx_data.chunk_setinfo.transactions);
1151 : 1506026 : m_nonminimal_chunks.emplace_back(tx, pivot_idx, m_rng.randbits<1>());
1152 : : // Randomize the initial order of nonminimal chunks in the queue.
1153 : 1506026 : TxIdx j = m_rng.randrange<TxIdx>(m_nonminimal_chunks.size());
1154 [ + + ]: 1506026 : if (j != m_nonminimal_chunks.size() - 1) {
1155 : 1104457 : std::swap(m_nonminimal_chunks.back(), m_nonminimal_chunks[j]);
1156 : : }
1157 : : }
1158 : : }
1159 : 191848 : }
1160 : :
1161 : : /** Try to reduce a chunk's size. Returns false if all chunks are minimal, true otherwise. */
1162 : 2325179 : bool MinimizeStep() noexcept
1163 : : {
1164 : : // If the queue of potentially-non-minimal chunks is empty, we are done.
1165 [ + + ]: 2325179 : if (m_nonminimal_chunks.empty()) return false;
1166 : : // Pop an entry from the potentially-non-minimal chunk queue.
1167 : 2133437 : auto [chunk_rep, pivot_idx, flags] = m_nonminimal_chunks.front();
1168 : 2133437 : m_nonminimal_chunks.pop_front();
1169 [ + - ]: 2133437 : auto& chunk_data = m_tx_data[chunk_rep];
1170 [ + - ]: 2133437 : Assume(chunk_data.chunk_rep == chunk_rep);
1171 : : /** Whether to move the pivot down rather than up. */
1172 : 2133437 : bool move_pivot_down = flags & 1;
1173 : : /** Whether this is already the second stage. */
1174 : 2133437 : bool second_stage = flags & 2;
1175 : :
1176 : : // Find a random dependency whose top and bottom set feerates are equal, and which has
1177 : : // pivot in bottom set (if move_pivot_down) or in top set (if !move_pivot_down).
1178 : 2133437 : DepIdx candidate_dep = DepIdx(-1);
1179 : 2133437 : uint64_t candidate_tiebreak{0};
1180 : 2133437 : bool have_any = false;
1181 : : // Iterate over all transactions.
1182 [ + + + + ]: 11479510 : for (auto tx_idx : chunk_data.chunk_setinfo.transactions) {
1183 : 8489565 : const auto& tx_data = m_tx_data[tx_idx];
1184 : : // Iterate over all active child dependencies of the transaction.
1185 [ + + ]: 28987576 : for (auto dep_idx : tx_data.child_deps) {
1186 [ + + ]: 20498011 : auto& dep_data = m_dep_data[dep_idx];
1187 : : // Skip inactive child dependencies.
1188 [ + + ]: 20498011 : if (!dep_data.active) continue;
1189 : : // Skip if this dependency does not have equal top and bottom set feerates. Note
1190 : : // that the top cannot have higher feerate than the bottom, or OptimizeSteps would
1191 : : // have dealt with it.
1192 [ + + ]: 6356128 : if (dep_data.top_setinfo.feerate << chunk_data.chunk_setinfo.feerate) continue;
1193 : 3076261 : have_any = true;
1194 : : // Skip if this dependency does not have pivot in the right place.
1195 [ + + ]: 3076261 : if (move_pivot_down == dep_data.top_setinfo.transactions[pivot_idx]) continue;
1196 : : // Remember this as our chosen dependency if it has a better tiebreak.
1197 : 2427627 : uint64_t tiebreak = m_rng.rand64() | 1;
1198 [ + + ]: 2427627 : if (tiebreak > candidate_tiebreak) {
1199 : 625528 : candidate_tiebreak = tiebreak;
1200 : 625528 : candidate_dep = dep_idx;
1201 : : }
1202 : : }
1203 : : }
1204 : : // If no dependencies have equal top and bottom set feerate, this chunk is minimal.
1205 [ + + ]: 2133437 : if (!have_any) return true;
1206 : : // If all found dependencies have the pivot in the wrong place, try moving it in the other
1207 : : // direction. If this was the second stage already, we are done.
1208 [ + + ]: 339999 : if (candidate_tiebreak == 0) {
1209 : : // Switch to other direction, and to second phase.
1210 : 51236 : flags ^= 3;
1211 [ + - ]: 51236 : if (!second_stage) m_nonminimal_chunks.emplace_back(chunk_rep, pivot_idx, flags);
1212 : 51236 : return true;
1213 : : }
1214 : :
1215 : : // Otherwise, deactivate the dependency that was found.
1216 : 288763 : Deactivate(candidate_dep);
1217 : 288763 : auto& dep_data = m_dep_data[candidate_dep];
1218 : 288763 : auto parent_chunk_rep = m_tx_data[dep_data.parent].chunk_rep;
1219 : 288763 : auto child_chunk_rep = m_tx_data[dep_data.child].chunk_rep;
1220 : : // Try to activate a dependency between the new bottom and the new top (opposite from the
1221 : : // dependency that was just deactivated).
1222 : 288763 : auto merged_chunk_rep = MergeChunks(child_chunk_rep, parent_chunk_rep);
1223 [ + + ]: 288763 : if (merged_chunk_rep != TxIdx(-1)) {
1224 : : // A self-merge happened.
1225 : : // Re-insert the chunk into the queue, in the same direction. Note that the chunk_rep
1226 : : // will have changed.
1227 : 668 : m_nonminimal_chunks.emplace_back(merged_chunk_rep, pivot_idx, flags);
1228 : : } else {
1229 : : // No self-merge happens, and thus we have found a way to split the chunk. Create two
1230 : : // smaller chunks, and add them to the queue. The one that contains the current pivot
1231 : : // gets to continue with it in the same direction, to minimize the number of times we
1232 : : // alternate direction. If we were in the second phase already, the newly created chunk
1233 : : // inherits that too, because we know no split with the pivot on the other side is
1234 : : // possible already. The new chunk without the current pivot gets a new randomly-chosen
1235 : : // one.
1236 [ + + ]: 288095 : if (move_pivot_down) {
1237 : 80686 : auto parent_pivot_idx = PickRandomTx(m_tx_data[parent_chunk_rep].chunk_setinfo.transactions);
1238 : 80686 : m_nonminimal_chunks.emplace_back(parent_chunk_rep, parent_pivot_idx, m_rng.randbits<1>());
1239 : 80686 : m_nonminimal_chunks.emplace_back(child_chunk_rep, pivot_idx, flags);
1240 : : } else {
1241 : 207409 : auto child_pivot_idx = PickRandomTx(m_tx_data[child_chunk_rep].chunk_setinfo.transactions);
1242 : 207409 : m_nonminimal_chunks.emplace_back(parent_chunk_rep, pivot_idx, flags);
1243 : 207409 : m_nonminimal_chunks.emplace_back(child_chunk_rep, child_pivot_idx, m_rng.randbits<1>());
1244 : : }
1245 [ + + ]: 288095 : if (m_rng.randbool()) {
1246 : 143801 : std::swap(m_nonminimal_chunks.back(), m_nonminimal_chunks[m_nonminimal_chunks.size() - 2]);
1247 : : }
1248 : : }
1249 : : return true;
1250 : : }
1251 : :
1252 : : /** Construct a topologically-valid linearization from the current forest state. Must be
1253 : : * topological. fallback_order is a comparator that defines a strong order for DepGraphIndexes
1254 : : * in this cluster, used to order equal-feerate transactions and chunks.
1255 : : *
1256 : : * Specifically, the resulting order consists of:
1257 : : * - The chunks of the current SFL state, sorted by (in decreasing order of priority):
1258 : : * - topology (parents before children)
1259 : : * - highest chunk feerate first
1260 : : * - smallest chunk size first
1261 : : * - the chunk with the lowest maximum transaction, by fallback_order, first
1262 : : * - The transactions within a chunk, sorted by (in decreasing order of priority):
1263 : : * - topology (parents before children)
1264 : : * - highest tx feerate first
1265 : : * - smallest tx size first
1266 : : * - the lowest transaction, by fallback_order, first
1267 : : */
1268 : 191932 : std::vector<DepGraphIndex> GetLinearization(const StrongComparator<DepGraphIndex> auto& fallback_order) const noexcept
1269 : : {
1270 : : /** The output linearization. */
1271 : 191932 : std::vector<DepGraphIndex> ret;
1272 : 191932 : ret.reserve(m_transaction_idxs.Count());
1273 : : /** A heap with all chunks (by representative) that can currently be included, sorted by
1274 : : * chunk feerate (high to low), chunk size (small to large), and by least maximum element
1275 : : * according to the fallback order (which is the second pair element). */
1276 : 191932 : std::vector<std::pair<TxIdx, TxIdx>> ready_chunks;
1277 : : /** Information about chunks:
1278 : : * - The first value is only used for chunk representatives, and counts the number of
1279 : : * unmet dependencies this chunk has on other chunks (not including dependencies within
1280 : : * the chunk itself).
1281 : : * - The second value is the number of unmet dependencies overall.
1282 : : */
1283 [ - + + - ]: 191932 : std::vector<std::pair<TxIdx, TxIdx>> chunk_deps(m_tx_data.size(), {0, 0});
1284 : : /** The set of all chunk representatives. */
1285 : 191932 : SetType chunk_reps;
1286 : : /** A heap with all transactions within the current chunk that can be included, sorted by
1287 : : * tx feerate (high to low), tx size (small to large), and fallback order. */
1288 : 191932 : std::vector<TxIdx> ready_tx;
1289 : : // Populate chunk_deps[c] with the number of {out-of-chunk dependencies, dependencies} the
1290 : : // child has.
1291 [ + + + + ]: 5351024 : for (TxIdx chl_idx : m_transaction_idxs) {
1292 [ + + ]: 5082960 : const auto& chl_data = m_tx_data[chl_idx];
1293 [ + + ]: 5082960 : chunk_deps[chl_idx].second = chl_data.parents.Count();
1294 [ + + ]: 5082960 : auto chl_chunk_rep = chl_data.chunk_rep;
1295 : 5082960 : chunk_reps.Set(chl_chunk_rep);
1296 [ + + + + ]: 21623416 : for (auto par_idx : chl_data.parents) {
1297 : 15043838 : auto par_chunk_rep = m_tx_data[par_idx].chunk_rep;
1298 : 15043838 : chunk_deps[chl_chunk_rep].first += (par_chunk_rep != chl_chunk_rep);
1299 : : }
1300 : : }
1301 : : /** Function to compute the highest element of a chunk, by fallback_order. */
1302 : 1986141 : auto max_fallback_fn = [&](TxIdx chunk_rep) noexcept {
1303 [ + - ]: 1794209 : auto& chunk = m_tx_data[chunk_rep].chunk_setinfo.transactions;
[ + - + - ]
1304 : 1794209 : auto it = chunk.begin();
1305 : 1794209 : DepGraphIndex ret = *it;
1306 : 1794209 : ++it;
1307 [ + + ][ + + : 5082960 : while (it != chunk.end()) {
+ + + + +
+ + + ]
1308 [ + + ][ + - : 6561351 : if (fallback_order(*it, ret) > 0) ret = *it;
+ - + - +
- + - + -
+ - + - +
- + - ]
1309 : 3288751 : ++it;
1310 : : }
1311 : 1794209 : return ret;
1312 : : };
1313 : : /** Comparison function for the transaction heap. Note that it is a max-heap, so
1314 : : * tx_cmp_fn(a, b) == true means "a appears after b in the linearization". */
1315 : 8786644 : auto tx_cmp_fn = [&](const auto& a, const auto& b) noexcept {
1316 : : // Bail out for identical transactions.
1317 [ + - ][ + - : 8594712 : if (a == b) return false;
+ - + - +
- + - ]
1318 : : // First sort by increasing transaction feerate.
1319 [ + + ][ + + : 8594712 : auto& a_feerate = m_depgraph.FeeRate(a);
+ + + + +
+ + + ]
1320 : 8594712 : auto& b_feerate = m_depgraph.FeeRate(b);
1321 [ + + ][ + + : 8594712 : auto feerate_cmp = FeeRateCompare(a_feerate, b_feerate);
+ + + + +
+ + + ]
1322 [ + + ][ + + : 8594712 : if (feerate_cmp != 0) return feerate_cmp < 0;
+ + + + +
+ + + ]
1323 : : // Then by decreasing transaction size.
1324 [ - + ][ + + : 3479283 : if (a_feerate.size != b_feerate.size) {
+ + + + +
+ + + ]
1325 : 3400 : return a_feerate.size > b_feerate.size;
1326 : : }
1327 : : // Tie-break by decreasing fallback_order.
1328 [ + + + - : 6916883 : auto fallback_cmp = fallback_order(a, b);
+ + + - +
+ + - + +
+ - + + +
- ]
1329 [ + - ][ + - : 3475883 : if (fallback_cmp != 0) return fallback_cmp > 0;
+ - + - +
- + - ]
1330 : : // This should not be hit, because fallback_order defines a strong ordering.
1331 : 0 : Assume(false);
1332 : 0 : return a < b;
1333 : : };
1334 : : // Construct a heap with all chunks that have no out-of-chunk dependencies.
1335 : : /** Comparison function for the chunk heap. Note that it is a max-heap, so
1336 : : * chunk_cmp_fn(a, b) == true means "a appears after b in the linearization". */
1337 : 5426709 : auto chunk_cmp_fn = [&](const auto& a, const auto& b) noexcept {
1338 : : // Bail out for identical chunks.
1339 [ + - ][ + - : 5234777 : if (a.first == b.first) return false;
+ - + - +
- + - ]
1340 : : // First sort by increasing chunk feerate.
1341 [ + + ][ + + : 5234777 : auto& chunk_feerate_a = m_tx_data[a.first].chunk_setinfo.feerate;
+ + + + +
+ + + ]
1342 : 5234777 : auto& chunk_feerate_b = m_tx_data[b.first].chunk_setinfo.feerate;
1343 [ + + ][ + + : 5234777 : auto feerate_cmp = FeeRateCompare(chunk_feerate_a, chunk_feerate_b);
+ + + + +
+ + + ]
1344 [ + + ][ + + : 5234777 : if (feerate_cmp != 0) return feerate_cmp < 0;
+ + + + +
+ + + ]
1345 : : // Then by decreasing chunk size.
1346 [ + + ][ + + : 1845384 : if (chunk_feerate_a.size != chunk_feerate_b.size) {
+ + + + +
+ + + ]
1347 : 69278 : return chunk_feerate_a.size > chunk_feerate_b.size;
1348 : : }
1349 : : // Tie-break by decreasing fallback_order.
1350 [ + - + - : 3508913 : auto fallback_cmp = fallback_order(a.second, b.second);
+ - + - +
- + - + -
+ - + - +
- ]
1351 [ + - ][ + - : 1776106 : if (fallback_cmp != 0) return fallback_cmp > 0;
+ - + - +
- + - ]
1352 : : // This should not be hit, because fallback_order defines a strong ordering.
1353 : 0 : Assume(false);
1354 : 0 : return a.second < b.second;
1355 : : };
1356 : : // Construct a heap with all chunks that have no out-of-chunk dependencies.
1357 [ + + + + ]: 2062273 : for (TxIdx chunk_rep : chunk_reps) {
1358 [ + + ]: 1794209 : if (chunk_deps[chunk_rep].first == 0) {
1359 : 461400 : ready_chunks.emplace_back(chunk_rep, max_fallback_fn(chunk_rep));
1360 : : }
1361 : : }
1362 : 191932 : std::make_heap(ready_chunks.begin(), ready_chunks.end(), chunk_cmp_fn);
1363 : : // Pop chunks off the heap.
1364 [ + + ]: 1986141 : while (!ready_chunks.empty()) {
1365 : 1794209 : auto [chunk_rep, _rnd] = ready_chunks.front();
1366 [ + - ]: 1794209 : std::pop_heap(ready_chunks.begin(), ready_chunks.end(), chunk_cmp_fn);
1367 : 1794209 : ready_chunks.pop_back();
1368 [ + - ]: 1794209 : Assume(m_tx_data[chunk_rep].chunk_rep == chunk_rep);
1369 : 1794209 : Assume(chunk_deps[chunk_rep].first == 0);
1370 [ + - ]: 1794209 : const auto& chunk_txn = m_tx_data[chunk_rep].chunk_setinfo.transactions;
1371 : : // Build heap of all includable transactions in chunk.
1372 : 1794209 : Assume(ready_tx.empty());
1373 [ + + + + ]: 7563978 : for (TxIdx tx_idx : chunk_txn) {
1374 [ + + ]: 5082960 : if (chunk_deps[tx_idx].second == 0) ready_tx.push_back(tx_idx);
1375 : : }
1376 : 1794209 : Assume(!ready_tx.empty());
1377 : 1794209 : std::make_heap(ready_tx.begin(), ready_tx.end(), tx_cmp_fn);
1378 : : // Pick transactions from the ready heap, append them to linearization, and decrement
1379 : : // dependency counts.
1380 [ + + ]: 6877169 : while (!ready_tx.empty()) {
1381 : : // Pop an element from the tx_ready heap.
1382 : 5082960 : auto tx_idx = ready_tx.front();
1383 : 5082960 : std::pop_heap(ready_tx.begin(), ready_tx.end(), tx_cmp_fn);
1384 : 5082960 : ready_tx.pop_back();
1385 : : // Append to linearization.
1386 : 5082960 : ret.push_back(tx_idx);
1387 : : // Decrement dependency counts.
1388 [ + + ]: 5082960 : auto& tx_data = m_tx_data[tx_idx];
1389 [ + + + + ]: 21112199 : for (TxIdx chl_idx : tx_data.children) {
1390 [ + + ]: 15043838 : auto& chl_data = m_tx_data[chl_idx];
1391 : : // Decrement tx dependency count.
1392 : 15043838 : Assume(chunk_deps[chl_idx].second > 0);
1393 [ + + + + ]: 15043838 : if (--chunk_deps[chl_idx].second == 0 && chunk_txn[chl_idx]) {
1394 : : // Child tx has no dependencies left, and is in this chunk. Add it to the tx heap.
1395 : 2676414 : ready_tx.push_back(chl_idx);
1396 : 2676414 : std::push_heap(ready_tx.begin(), ready_tx.end(), tx_cmp_fn);
1397 : : }
1398 : : // Decrement chunk dependency count if this is out-of-chunk dependency.
1399 [ + + ]: 15043838 : if (chl_data.chunk_rep != chunk_rep) {
1400 [ + + ]: 8151285 : Assume(chunk_deps[chl_data.chunk_rep].first > 0);
1401 [ + + ]: 8151285 : if (--chunk_deps[chl_data.chunk_rep].first == 0) {
1402 : : // Child chunk has no dependencies left. Add it to the chunk heap.
1403 : 1332809 : ready_chunks.emplace_back(chl_data.chunk_rep, max_fallback_fn(chl_data.chunk_rep));
1404 : 1332809 : std::push_heap(ready_chunks.begin(), ready_chunks.end(), chunk_cmp_fn);
1405 : : }
1406 : : }
1407 : : }
1408 : : }
1409 : : }
1410 [ - + ]: 191932 : Assume(ret.size() == m_transaction_idxs.Count());
1411 : 191932 : return ret;
1412 : 191932 : }
1413 : :
1414 : : /** Get the diagram for the current state, which must be topological. Test-only.
1415 : : *
1416 : : * The linearization produced by GetLinearization() is always at least as good (in the
1417 : : * CompareChunks() sense) as this diagram, but may be better.
1418 : : *
1419 : : * After an OptimizeStep(), the diagram will always be at least as good as before. Once
1420 : : * OptimizeStep() returns false, the diagram will be equivalent to that produced by
1421 : : * GetLinearization(), and optimal.
1422 : : *
1423 : : * After a MinimizeStep(), the diagram cannot change anymore (in the CompareChunks() sense),
1424 : : * but its number of segments can increase still. Once MinimizeStep() returns false, the number
1425 : : * of chunks of the produced linearization will match the number of segments in the diagram.
1426 : : */
1427 : : std::vector<FeeFrac> GetDiagram() const noexcept
1428 : : {
1429 : : std::vector<FeeFrac> ret;
1430 : : for (auto tx : m_transaction_idxs) {
1431 : : if (m_tx_data[tx].chunk_rep == tx) {
1432 : : ret.push_back(m_tx_data[tx].chunk_setinfo.feerate);
1433 : : }
1434 : : }
1435 : : std::sort(ret.begin(), ret.end(), std::greater{});
1436 : : return ret;
1437 : : }
1438 : :
1439 : : /** Determine how much work was performed so far. */
1440 : 5231340 : uint64_t GetCost() const noexcept { return m_cost; }
1441 : :
1442 : : /** Verify internal consistency of the data structure. */
1443 : : void SanityCheck(const DepGraph<SetType>& depgraph) const
1444 : : {
1445 : : //
1446 : : // Verify dependency parent/child information, and build list of (active) dependencies.
1447 : : //
1448 : : std::vector<std::pair<TxIdx, TxIdx>> expected_dependencies;
1449 : : std::vector<std::tuple<TxIdx, TxIdx, DepIdx>> all_dependencies;
1450 : : std::vector<std::tuple<TxIdx, TxIdx, DepIdx>> active_dependencies;
1451 : : for (auto parent_idx : depgraph.Positions()) {
1452 : : for (auto child_idx : depgraph.GetReducedChildren(parent_idx)) {
1453 : : expected_dependencies.emplace_back(parent_idx, child_idx);
1454 : : }
1455 : : }
1456 : : for (DepIdx dep_idx = 0; dep_idx < m_dep_data.size(); ++dep_idx) {
1457 : : const auto& dep_data = m_dep_data[dep_idx];
1458 : : all_dependencies.emplace_back(dep_data.parent, dep_data.child, dep_idx);
1459 : : // Also add to active_dependencies if it is active.
1460 : : if (m_dep_data[dep_idx].active) {
1461 : : active_dependencies.emplace_back(dep_data.parent, dep_data.child, dep_idx);
1462 : : }
1463 : : }
1464 : : std::sort(expected_dependencies.begin(), expected_dependencies.end());
1465 : : std::sort(all_dependencies.begin(), all_dependencies.end());
1466 : : assert(expected_dependencies.size() == all_dependencies.size());
1467 : : for (size_t i = 0; i < expected_dependencies.size(); ++i) {
1468 : : assert(expected_dependencies[i] ==
1469 : : std::make_pair(std::get<0>(all_dependencies[i]),
1470 : : std::get<1>(all_dependencies[i])));
1471 : : }
1472 : :
1473 : : //
1474 : : // Verify the chunks against the list of active dependencies
1475 : : //
1476 : : for (auto tx_idx: depgraph.Positions()) {
1477 : : // Only process chunks for now.
1478 : : if (m_tx_data[tx_idx].chunk_rep == tx_idx) {
1479 : : const auto& chunk_data = m_tx_data[tx_idx];
1480 : : // Verify that transactions in the chunk point back to it. This guarantees
1481 : : // that chunks are non-overlapping.
1482 : : for (auto chunk_tx : chunk_data.chunk_setinfo.transactions) {
1483 : : assert(m_tx_data[chunk_tx].chunk_rep == tx_idx);
1484 : : }
1485 : : // Verify the chunk's transaction set: it must contain the representative, and for
1486 : : // every active dependency, if it contains the parent or child, it must contain
1487 : : // both. It must have exactly N-1 active dependencies in it, guaranteeing it is
1488 : : // acyclic.
1489 : : SetType expected_chunk = SetType::Singleton(tx_idx);
1490 : : while (true) {
1491 : : auto old = expected_chunk;
1492 : : size_t active_dep_count{0};
1493 : : for (const auto& [par, chl, _dep] : active_dependencies) {
1494 : : if (expected_chunk[par] || expected_chunk[chl]) {
1495 : : expected_chunk.Set(par);
1496 : : expected_chunk.Set(chl);
1497 : : ++active_dep_count;
1498 : : }
1499 : : }
1500 : : if (old == expected_chunk) {
1501 : : assert(expected_chunk.Count() == active_dep_count + 1);
1502 : : break;
1503 : : }
1504 : : }
1505 : : assert(chunk_data.chunk_setinfo.transactions == expected_chunk);
1506 : : // Verify the chunk's feerate.
1507 : : assert(chunk_data.chunk_setinfo.feerate ==
1508 : : depgraph.FeeRate(chunk_data.chunk_setinfo.transactions));
1509 : : }
1510 : : }
1511 : :
1512 : : //
1513 : : // Verify other transaction data.
1514 : : //
1515 : : assert(m_transaction_idxs == depgraph.Positions());
1516 : : for (auto tx_idx : m_transaction_idxs) {
1517 : : const auto& tx_data = m_tx_data[tx_idx];
1518 : : // Verify it has a valid chunk representative, and that chunk includes this
1519 : : // transaction.
1520 : : assert(m_tx_data[tx_data.chunk_rep].chunk_rep == tx_data.chunk_rep);
1521 : : assert(m_tx_data[tx_data.chunk_rep].chunk_setinfo.transactions[tx_idx]);
1522 : : // Verify parents/children.
1523 : : assert(tx_data.parents == depgraph.GetReducedParents(tx_idx));
1524 : : assert(tx_data.children == depgraph.GetReducedChildren(tx_idx));
1525 : : // Verify list of child dependencies.
1526 : : std::vector<DepIdx> expected_child_deps;
1527 : : for (const auto& [par_idx, chl_idx, dep_idx] : all_dependencies) {
1528 : : if (tx_idx == par_idx) {
1529 : : assert(tx_data.children[chl_idx]);
1530 : : expected_child_deps.push_back(dep_idx);
1531 : : }
1532 : : }
1533 : : std::sort(expected_child_deps.begin(), expected_child_deps.end());
1534 : : auto child_deps_copy = tx_data.child_deps;
1535 : : std::sort(child_deps_copy.begin(), child_deps_copy.end());
1536 : : assert(expected_child_deps == child_deps_copy);
1537 : : }
1538 : :
1539 : : //
1540 : : // Verify active dependencies' top_setinfo.
1541 : : //
1542 : : for (const auto& [par_idx, chl_idx, dep_idx] : active_dependencies) {
1543 : : const auto& dep_data = m_dep_data[dep_idx];
1544 : : // Verify the top_info's transactions: it must contain the parent, and for every
1545 : : // active dependency, except dep_idx itself, if it contains the parent or child, it
1546 : : // must contain both.
1547 : : SetType expected_top = SetType::Singleton(par_idx);
1548 : : while (true) {
1549 : : auto old = expected_top;
1550 : : for (const auto& [par2_idx, chl2_idx, dep2_idx] : active_dependencies) {
1551 : : if (dep2_idx != dep_idx && (expected_top[par2_idx] || expected_top[chl2_idx])) {
1552 : : expected_top.Set(par2_idx);
1553 : : expected_top.Set(chl2_idx);
1554 : : }
1555 : : }
1556 : : if (old == expected_top) break;
1557 : : }
1558 : : assert(!expected_top[chl_idx]);
1559 : : assert(dep_data.top_setinfo.transactions == expected_top);
1560 : : // Verify the top_info's feerate.
1561 : : assert(dep_data.top_setinfo.feerate ==
1562 : : depgraph.FeeRate(dep_data.top_setinfo.transactions));
1563 : : }
1564 : :
1565 : : //
1566 : : // Verify m_suboptimal_chunks.
1567 : : //
1568 : : for (size_t i = 0; i < m_suboptimal_chunks.size(); ++i) {
1569 : : auto tx_idx = m_suboptimal_chunks[i];
1570 : : assert(m_transaction_idxs[tx_idx]);
1571 : : }
1572 : :
1573 : : //
1574 : : // Verify m_nonminimal_chunks.
1575 : : //
1576 : : SetType nonminimal_reps;
1577 : : for (size_t i = 0; i < m_nonminimal_chunks.size(); ++i) {
1578 : : auto [chunk_rep, pivot, flags] = m_nonminimal_chunks[i];
1579 : : assert(m_tx_data[chunk_rep].chunk_rep == chunk_rep);
1580 : : assert(m_tx_data[pivot].chunk_rep == chunk_rep);
1581 : : assert(!nonminimal_reps[chunk_rep]);
1582 : : nonminimal_reps.Set(chunk_rep);
1583 : : }
1584 : : assert(nonminimal_reps.IsSubsetOf(m_transaction_idxs));
1585 : : }
1586 : : };
1587 : :
1588 : : /** Find or improve a linearization for a cluster.
1589 : : *
1590 : : * @param[in] depgraph Dependency graph of the cluster to be linearized.
1591 : : * @param[in] max_iterations Upper bound on the amount of work that will be done.
1592 : : * @param[in] rng_seed A random number seed to control search order. This prevents peers
1593 : : * from predicting exactly which clusters would be hard for us to
1594 : : * linearize.
1595 : : * @param[in] fallback_order A comparator to order transactions, used to sort equal-feerate
1596 : : * chunks and transactions. See SpanningForestState::GetLinearization
1597 : : * for details.
1598 : : * @param[in] old_linearization An existing linearization for the cluster, or empty.
1599 : : * @param[in] is_topological (Only relevant if old_linearization is not empty) Whether
1600 : : * old_linearization is topologically valid.
1601 : : * @return A tuple of:
1602 : : * - The resulting linearization. It is guaranteed to be at least as
1603 : : * good (in the feerate diagram sense) as old_linearization.
1604 : : * - A boolean indicating whether the result is guaranteed to be
1605 : : * optimal with minimal chunks.
1606 : : * - How many optimization steps were actually performed.
1607 : : */
1608 : : template<typename SetType>
1609 : 191932 : std::tuple<std::vector<DepGraphIndex>, bool, uint64_t> Linearize(
1610 : : const DepGraph<SetType>& depgraph,
1611 : : uint64_t max_iterations,
1612 : : uint64_t rng_seed,
1613 : : const StrongComparator<DepGraphIndex> auto& fallback_order,
1614 : : std::span<const DepGraphIndex> old_linearization = {},
1615 : : bool is_topological = true) noexcept
1616 : : {
1617 : : /** Initialize a spanning forest data structure for this cluster. */
1618 [ + + ]: 191932 : SpanningForestState forest(depgraph, rng_seed);
1619 [ + + ]: 191932 : if (!old_linearization.empty()) {
1620 : 144656 : forest.LoadLinearization(old_linearization);
1621 [ + + ]: 144656 : if (!is_topological) forest.MakeTopological();
1622 : : } else {
1623 : 47276 : forest.MakeTopological();
1624 : : }
1625 : : // Make improvement steps to it until we hit the max_iterations limit, or an optimal result
1626 : : // is found.
1627 [ + + ]: 191932 : if (forest.GetCost() < max_iterations) {
1628 : 191848 : forest.StartOptimizing();
1629 : : do {
1630 [ + + ]: 2713955 : if (!forest.OptimizeStep()) break;
1631 [ + - ]: 2522107 : } while (forest.GetCost() < max_iterations);
1632 : : }
1633 : : // Make chunk minimization steps until we hit the max_iterations limit, or all chunks are
1634 : : // minimal.
1635 : 191932 : bool optimal = false;
1636 [ + + ]: 191932 : if (forest.GetCost() < max_iterations) {
1637 : 191848 : forest.StartMinimizing();
1638 : : do {
1639 [ + + ]: 2325179 : if (!forest.MinimizeStep()) {
1640 : : optimal = true;
1641 : : break;
1642 : : }
1643 [ + + ]: 2133437 : } while (forest.GetCost() < max_iterations);
1644 : : }
1645 : 191932 : return {forest.GetLinearization(fallback_order), optimal, forest.GetCost()};
1646 : 191932 : }
1647 : :
1648 : : /** Improve a given linearization.
1649 : : *
1650 : : * @param[in] depgraph Dependency graph of the cluster being linearized.
1651 : : * @param[in,out] linearization On input, an existing linearization for depgraph. On output, a
1652 : : * potentially better linearization for the same graph.
1653 : : *
1654 : : * Postlinearization guarantees:
1655 : : * - The resulting chunks are connected.
1656 : : * - If the input has a tree shape (either all transactions have at most one child, or all
1657 : : * transactions have at most one parent), the result is optimal.
1658 : : * - Given a linearization L1 and a leaf transaction T in it. Let L2 be L1 with T moved to the end,
1659 : : * optionally with its fee increased. Let L3 be the postlinearization of L2. L3 will be at least
1660 : : * as good as L1. This means that replacing transactions with same-size higher-fee transactions
1661 : : * will not worsen linearizations through a "drop conflicts, append new transactions,
1662 : : * postlinearize" process.
1663 : : */
1664 : : template<typename SetType>
1665 [ - + ]: 5732 : void PostLinearize(const DepGraph<SetType>& depgraph, std::span<DepGraphIndex> linearization)
1666 : : {
1667 : : // This algorithm performs a number of passes (currently 2); the even ones operate from back to
1668 : : // front, the odd ones from front to back. Each results in an equal-or-better linearization
1669 : : // than the one started from.
1670 : : // - One pass in either direction guarantees that the resulting chunks are connected.
1671 : : // - Each direction corresponds to one shape of tree being linearized optimally (forward passes
1672 : : // guarantee this for graphs where each transaction has at most one child; backward passes
1673 : : // guarantee this for graphs where each transaction has at most one parent).
1674 : : // - Starting with a backward pass guarantees the moved-tree property.
1675 : : //
1676 : : // During an odd (forward) pass, the high-level operation is:
1677 : : // - Start with an empty list of groups L=[].
1678 : : // - For every transaction i in the old linearization, from front to back:
1679 : : // - Append a new group C=[i], containing just i, to the back of L.
1680 : : // - While L has at least one group before C, and the group immediately before C has feerate
1681 : : // lower than C:
1682 : : // - If C depends on P:
1683 : : // - Merge P into C, making C the concatenation of P+C, continuing with the combined C.
1684 : : // - Otherwise:
1685 : : // - Swap P with C, continuing with the now-moved C.
1686 : : // - The output linearization is the concatenation of the groups in L.
1687 : : //
1688 : : // During even (backward) passes, i iterates from the back to the front of the existing
1689 : : // linearization, and new groups are prepended instead of appended to the list L. To enable
1690 : : // more code reuse, both passes append groups, but during even passes the meanings of
1691 : : // parent/child, and of high/low feerate are reversed, and the final concatenation is reversed
1692 : : // on output.
1693 : : //
1694 : : // In the implementation below, the groups are represented by singly-linked lists (pointing
1695 : : // from the back to the front), which are themselves organized in a singly-linked circular
1696 : : // list (each group pointing to its predecessor, with a special sentinel group at the front
1697 : : // that points back to the last group).
1698 : : //
1699 : : // Information about transaction t is stored in entries[t + 1], while the sentinel is in
1700 : : // entries[0].
1701 : :
1702 : : /** Index of the sentinel in the entries array below. */
1703 : : static constexpr DepGraphIndex SENTINEL{0};
1704 : : /** Indicator that a group has no previous transaction. */
1705 : : static constexpr DepGraphIndex NO_PREV_TX{0};
1706 : :
1707 : :
1708 : : /** Data structure per transaction entry. */
1709 : 85692 : struct TxEntry
1710 : : {
1711 : : /** The index of the previous transaction in this group; NO_PREV_TX if this is the first
1712 : : * entry of a group. */
1713 : : DepGraphIndex prev_tx;
1714 : :
1715 : : // The fields below are only used for transactions that are the last one in a group
1716 : : // (referred to as tail transactions below).
1717 : :
1718 : : /** Index of the first transaction in this group, possibly itself. */
1719 : : DepGraphIndex first_tx;
1720 : : /** Index of the last transaction in the previous group. The first group (the sentinel)
1721 : : * points back to the last group here, making it a singly-linked circular list. */
1722 : : DepGraphIndex prev_group;
1723 : : /** All transactions in the group. Empty for the sentinel. */
1724 : : SetType group;
1725 : : /** All dependencies of the group (descendants in even passes; ancestors in odd ones). */
1726 : : SetType deps;
1727 : : /** The combined fee/size of transactions in the group. Fee is negated in even passes. */
1728 : : FeeFrac feerate;
1729 : : };
1730 : :
1731 : : // As an example, consider the state corresponding to the linearization [1,0,3,2], with
1732 : : // groups [1,0,3] and [2], in an odd pass. The linked lists would be:
1733 : : //
1734 : : // +-----+
1735 : : // 0<-P-- | 0 S | ---\ Legend:
1736 : : // +-----+ |
1737 : : // ^ | - digit in box: entries index
1738 : : // /--------------F---------+ G | (note: one more than tx value)
1739 : : // v \ | | - S: sentinel group
1740 : : // +-----+ +-----+ +-----+ | (empty feerate)
1741 : : // 0<-P-- | 2 | <--P-- | 1 | <--P-- | 4 T | | - T: tail transaction, contains
1742 : : // +-----+ +-----+ +-----+ | fields beyond prev_tv.
1743 : : // ^ | - P: prev_tx reference
1744 : : // G G - F: first_tx reference
1745 : : // | | - G: prev_group reference
1746 : : // +-----+ |
1747 : : // 0<-P-- | 3 T | <--/
1748 : : // +-----+
1749 : : // ^ |
1750 : : // \-F-/
1751 : : //
1752 : : // During an even pass, the diagram above would correspond to linearization [2,3,0,1], with
1753 : : // groups [2] and [3,0,1].
1754 : :
1755 : 5732 : std::vector<TxEntry> entries(depgraph.PositionRange() + 1);
1756 : :
1757 : : // Perform two passes over the linearization.
1758 [ + + ]: 17196 : for (int pass = 0; pass < 2; ++pass) {
1759 : 11464 : int rev = !(pass & 1);
1760 : : // Construct a sentinel group, identifying the start of the list.
1761 : 11464 : entries[SENTINEL].prev_group = SENTINEL;
1762 : 11464 : Assume(entries[SENTINEL].feerate.IsEmpty());
1763 : :
1764 : : // Iterate over all elements in the existing linearization.
1765 [ + + ]: 171384 : for (DepGraphIndex i = 0; i < linearization.size(); ++i) {
1766 : : // Even passes are from back to front; odd passes from front to back.
1767 [ + + ]: 159920 : DepGraphIndex idx = linearization[rev ? linearization.size() - 1 - i : i];
1768 : : // Construct a new group containing just idx. In even passes, the meaning of
1769 : : // parent/child and high/low feerate are swapped.
1770 [ + + ]: 159920 : DepGraphIndex cur_group = idx + 1;
1771 [ + + ]: 159920 : entries[cur_group].group = SetType::Singleton(idx);
1772 [ + + + + ]: 159920 : entries[cur_group].deps = rev ? depgraph.Descendants(idx): depgraph.Ancestors(idx);
1773 : 159920 : entries[cur_group].feerate = depgraph.FeeRate(idx);
1774 [ + + ]: 159920 : if (rev) entries[cur_group].feerate.fee = -entries[cur_group].feerate.fee;
1775 : 159920 : entries[cur_group].prev_tx = NO_PREV_TX; // No previous transaction in group.
1776 : 159920 : entries[cur_group].first_tx = cur_group; // Transaction itself is first of group.
1777 : : // Insert the new group at the back of the groups linked list.
1778 : 159920 : entries[cur_group].prev_group = entries[SENTINEL].prev_group;
1779 : 159920 : entries[SENTINEL].prev_group = cur_group;
1780 : :
1781 : : // Start merge/swap cycle.
1782 : 159920 : DepGraphIndex next_group = SENTINEL; // We inserted at the end, so next group is sentinel.
1783 : 159920 : DepGraphIndex prev_group = entries[cur_group].prev_group;
1784 : : // Continue as long as the current group has higher feerate than the previous one.
1785 [ + + ]: 175096 : while (entries[cur_group].feerate >> entries[prev_group].feerate) {
1786 : : // prev_group/cur_group/next_group refer to (the last transactions of) 3
1787 : : // consecutive entries in groups list.
1788 [ + - ]: 15176 : Assume(cur_group == entries[next_group].prev_group);
1789 : 15176 : Assume(prev_group == entries[cur_group].prev_group);
1790 : : // The sentinel has empty feerate, which is neither higher or lower than other
1791 : : // feerates. Thus, the while loop we are in here guarantees that cur_group and
1792 : : // prev_group are not the sentinel.
1793 : 15176 : Assume(cur_group != SENTINEL);
1794 : 15176 : Assume(prev_group != SENTINEL);
1795 [ + - ]: 15176 : if (entries[cur_group].deps.Overlaps(entries[prev_group].group)) {
1796 : : // There is a dependency between cur_group and prev_group; merge prev_group
1797 : : // into cur_group. The group/deps/feerate fields of prev_group remain unchanged
1798 : : // but become unused.
1799 : 15176 : entries[cur_group].group |= entries[prev_group].group;
1800 : 15176 : entries[cur_group].deps |= entries[prev_group].deps;
1801 : 15176 : entries[cur_group].feerate += entries[prev_group].feerate;
1802 : : // Make the first of the current group point to the tail of the previous group.
1803 : 15176 : entries[entries[cur_group].first_tx].prev_tx = prev_group;
1804 : : // The first of the previous group becomes the first of the newly-merged group.
1805 : 15176 : entries[cur_group].first_tx = entries[prev_group].first_tx;
1806 : : // The previous group becomes whatever group was before the former one.
1807 : 15176 : prev_group = entries[prev_group].prev_group;
1808 : 15176 : entries[cur_group].prev_group = prev_group;
1809 : : } else {
1810 : : // There is no dependency between cur_group and prev_group; swap them.
1811 : 0 : DepGraphIndex preprev_group = entries[prev_group].prev_group;
1812 : : // If PP, P, C, N were the old preprev, prev, cur, next groups, then the new
1813 : : // layout becomes [PP, C, P, N]. Update prev_groups to reflect that order.
1814 : 0 : entries[next_group].prev_group = prev_group;
1815 : 0 : entries[prev_group].prev_group = cur_group;
1816 : 0 : entries[cur_group].prev_group = preprev_group;
1817 : : // The current group remains the same, but the groups before/after it have
1818 : : // changed.
1819 : 0 : next_group = prev_group;
1820 : 0 : prev_group = preprev_group;
1821 : : }
1822 : : }
1823 : : }
1824 : :
1825 : : // Convert the entries back to linearization (overwriting the existing one).
1826 : 11464 : DepGraphIndex cur_group = entries[0].prev_group;
1827 : 11464 : DepGraphIndex done = 0;
1828 [ + + ]: 156208 : while (cur_group != SENTINEL) {
1829 : 144744 : DepGraphIndex cur_tx = cur_group;
1830 : : // Traverse the transactions of cur_group (from back to front), and write them in the
1831 : : // same order during odd passes, and reversed (front to back) in even passes.
1832 [ + + ]: 144744 : if (rev) {
1833 : : do {
1834 [ + + ]: 79960 : *(linearization.begin() + (done++)) = cur_tx - 1;
1835 [ + + ]: 79960 : cur_tx = entries[cur_tx].prev_tx;
1836 [ + + ]: 79960 : } while (cur_tx != NO_PREV_TX);
1837 : : } else {
1838 : : do {
1839 [ + + ]: 79960 : *(linearization.end() - (++done)) = cur_tx - 1;
1840 [ + + ]: 79960 : cur_tx = entries[cur_tx].prev_tx;
1841 [ + + ]: 79960 : } while (cur_tx != NO_PREV_TX);
1842 : : }
1843 : 144744 : cur_group = entries[cur_group].prev_group;
1844 : : }
1845 : 11464 : Assume(done == linearization.size());
1846 : : }
1847 : 5732 : }
1848 : :
1849 : : } // namespace cluster_linearize
1850 : :
1851 : : #endif // BITCOIN_CLUSTER_LINEARIZE_H
|