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 : : #include <cluster_linearize.h>
6 : :
7 : : #include <random.h>
8 : : #include <serialize.h>
9 : : #include <streams.h>
10 : : #include <test/fuzz/FuzzedDataProvider.h>
11 : : #include <test/fuzz/fuzz.h>
12 : : #include <test/util/cluster_linearize.h>
13 : : #include <util/bitset.h>
14 : : #include <util/check.h>
15 : : #include <util/feefrac.h>
16 : :
17 : : #include <algorithm>
18 : : #include <cstdint>
19 : : #include <utility>
20 : : #include <vector>
21 : :
22 : : /*
23 : : * The tests in this file primarily cover the candidate finder classes and linearization algorithms.
24 : : *
25 : : * <----: An implementation (at the start of the line --) is tested in the test marked with *,
26 : : * possibly by comparison with other implementations (at the end of the line ->).
27 : : * <<---: The right side is implemented using the left side.
28 : : *
29 : : * +---------------------+ +-----------+
30 : : * | SpanningForestState | <<-------------------- | Linearize |
31 : : * +---------------------+ +-----------+
32 : : * | |
33 : : * | | ^^ PRODUCTION CODE
34 : : * | | ||
35 : : * ==============================================================================================
36 : : * | | ||
37 : : * |-clusterlin_sfl* | vv TEST CODE
38 : : * | |
39 : : * \------------------------------------\ |-clusterlin_linearize*
40 : : * | |
41 : : * v v
42 : : * +-----------------------+ +-----------------+
43 : : * | SimpleCandidateFinder | <<-------------------| SimpleLinearize |
44 : : * +-----------------------+ +-----------------+
45 : : * | |
46 : : * |-clusterlin_simple_finder* |-clusterlin_simple_linearize*
47 : : * v v
48 : : * +---------------------------+ +---------------------+
49 : : * | ExhaustiveCandidateFinder | | ExhaustiveLinearize |
50 : : * +---------------------------+ +---------------------+
51 : : *
52 : : * More tests are included for lower-level and related functions and classes:
53 : : * - DepGraph tests:
54 : : * - clusterlin_depgraph_sim
55 : : * - clusterlin_depgraph_serialization
56 : : * - clusterlin_components
57 : : * - ChunkLinearization and ChunkLinearizationInfo tests:
58 : : * - clusterlin_chunking
59 : : * - PostLinearize tests:
60 : : * - clusterlin_postlinearize
61 : : * - clusterlin_postlinearize_tree
62 : : * - clusterlin_postlinearize_moved_leaf
63 : : * - MakeConnected tests (a test-only function):
64 : : * - clusterlin_make_connected
65 : : */
66 : :
67 : : using namespace cluster_linearize;
68 : :
69 : : namespace {
70 : :
71 : : /** A simple finder class for candidate sets (topologically-valid subsets with high feerate), only
72 : : * used by SimpleLinearize below. */
73 : : template<typename SetType>
74 : : class SimpleCandidateFinder
75 : : {
76 : : /** Internal dependency graph. */
77 : : const DepGraph<SetType>& m_depgraph;
78 : : /** Which transaction are left to include. */
79 : : SetType m_todo;
80 : :
81 : : public:
82 : : /** Construct an SimpleCandidateFinder for a given graph. */
83 : 1342 : SimpleCandidateFinder(const DepGraph<SetType>& depgraph LIFETIMEBOUND) noexcept :
84 : 1342 : m_depgraph(depgraph), m_todo{depgraph.Positions()} {}
85 : :
86 : : /** Remove a set of transactions from the set of to-be-linearized ones. */
87 : 15582 : void MarkDone(SetType select) noexcept { m_todo -= select; }
88 : :
89 : : /** Determine whether unlinearized transactions remain. */
90 : 1480 : bool AllDone() const noexcept { return m_todo.None(); }
91 : :
92 : : /** Find a candidate set using at most max_iterations iterations, and the number of iterations
93 : : * actually performed. If that number is less than max_iterations, then the result is optimal.
94 : : *
95 : : * Always returns a connected set of transactions.
96 : : *
97 : : * Complexity: O(N * M), where M is the number of connected topological subsets of the cluster.
98 : : * That number is bounded by M <= 2^(N-1).
99 : : */
100 : 15582 : std::pair<SetInfo<SetType>, uint64_t> FindCandidateSet(uint64_t max_iterations) const noexcept
101 : : {
102 : 15582 : uint64_t iterations_left = max_iterations;
103 : : // Queue of work units. Each consists of:
104 : : // - inc: set of transactions definitely included
105 : : // - und: set of transactions that can be added to inc still
106 : 15582 : std::vector<std::pair<SetType, SetType>> queue;
107 : : // Initially we have just one queue element, with the entire graph in und.
108 : 15582 : queue.emplace_back(SetType{}, m_todo);
109 : : // Best solution so far. Initialize with the remaining ancestors of the first remaining
110 : : // transaction.
111 : 15582 : SetInfo best(m_depgraph, m_depgraph.Ancestors(m_todo.First()) & m_todo);
112 : : // Process the queue.
113 [ + + + + ]: 50432409 : while (!queue.empty() && iterations_left) {
114 : : // Pop top element of the queue.
115 : 50416827 : auto [inc, und] = queue.back();
116 : 50416827 : queue.pop_back();
117 : : // Look for a transaction to consider adding/removing.
118 : 50416827 : bool inc_none = inc.None();
119 [ + + ]: 85738617 : for (auto split : und) {
120 : : // If inc is empty, consider any split transaction. Otherwise only consider
121 : : // transactions that share ancestry with inc so far (which means only connected
122 : : // sets will be considered).
123 [ + + + + ]: 60523895 : if (inc_none || inc.Overlaps(m_depgraph.Ancestors(split))) {
124 : 25202105 : --iterations_left;
125 : : // Add a queue entry with split included.
126 : 25202105 : SetInfo new_inc(m_depgraph, inc | (m_todo & m_depgraph.Ancestors(split)));
127 : 25202105 : queue.emplace_back(new_inc.transactions, und - new_inc.transactions);
128 : : // Add a queue entry with split excluded.
129 [ + + ]: 50404210 : queue.emplace_back(inc, und - m_depgraph.Descendants(split));
130 : : // Update statistics to account for the candidate new_inc.
131 [ + + ]: 25202105 : if (ByRatioNegSize{new_inc.feerate} > ByRatioNegSize{best.feerate}) best = new_inc;
132 : : break;
133 : : }
134 : : }
135 : : }
136 : 15582 : return {std::move(best), max_iterations - iterations_left};
137 : 15582 : }
138 : : };
139 : :
140 : : /** A very simple finder class for optimal candidate sets, which tries every subset.
141 : : *
142 : : * It is even simpler than SimpleCandidateFinder, and exists just to help test the correctness of
143 : : * SimpleCandidateFinder, so that it can be used in SimpleLinearize, which is then used to test the
144 : : * correctness of Linearize.
145 : : */
146 : : template<typename SetType>
147 : : class ExhaustiveCandidateFinder
148 : : {
149 : : /** Internal dependency graph. */
150 : : const DepGraph<SetType>& m_depgraph;
151 : : /** Which transaction are left to include. */
152 : : SetType m_todo;
153 : :
154 : : public:
155 : : /** Construct an ExhaustiveCandidateFinder for a given graph. */
156 : 152 : ExhaustiveCandidateFinder(const DepGraph<SetType>& depgraph LIFETIMEBOUND) noexcept :
157 : 152 : m_depgraph(depgraph), m_todo{depgraph.Positions()} {}
158 : :
159 : : /** Remove a set of transactions from the set of to-be-linearized ones. */
160 : 1328 : void MarkDone(SetType select) noexcept { m_todo -= select; }
161 : :
162 : : /** Determine whether unlinearized transactions remain. */
163 : 1480 : bool AllDone() const noexcept { return m_todo.None(); }
164 : :
165 : : /** Find the optimal remaining candidate set.
166 : : *
167 : : * Complexity: O(N * 2^N).
168 : : */
169 : 844 : SetInfo<SetType> FindCandidateSet() const noexcept
170 : : {
171 : : // Best solution so far.
172 : 844 : SetInfo<SetType> best{m_todo, m_depgraph.FeeRate(m_todo)};
173 : : // The number of combinations to try.
174 : 844 : uint64_t limit = (uint64_t{1} << m_todo.Count()) - 1;
175 : : // Try the transitive closure of every non-empty subset of m_todo.
176 [ + + ]: 390130 : for (uint64_t x = 1; x < limit; ++x) {
177 : : // If bit number b is set in x, then the remaining ancestors of the b'th remaining
178 : : // transaction in m_todo are included.
179 : 389286 : SetType txn;
180 : 389286 : auto x_shifted{x};
181 [ + - + + ]: 5027986 : for (auto i : m_todo) {
182 [ + + ]: 4249414 : if (x_shifted & 1) txn |= m_depgraph.Ancestors(i);
183 : 4249414 : x_shifted >>= 1;
184 : : }
185 [ + + ]: 389286 : SetInfo cur(m_depgraph, txn & m_todo);
186 [ + + ]: 389286 : if (ByRatioNegSize{cur.feerate} > ByRatioNegSize{best.feerate}) best = cur;
187 : : }
188 : 844 : return best;
189 : : }
190 : : };
191 : :
192 : : /** A simple linearization algorithm.
193 : : *
194 : : * This matches Linearize() in interface and behavior, though with fewer optimizations, lacking
195 : : * the ability to pass in an existing linearization, and linearizing by simply finding the
196 : : * consecutive remaining highest-feerate topological subset using SimpleCandidateFinder.
197 : : */
198 : : template<typename SetType>
199 : 1190 : std::pair<std::vector<DepGraphIndex>, bool> SimpleLinearize(const DepGraph<SetType>& depgraph, uint64_t max_iterations)
200 : : {
201 : 1190 : std::vector<DepGraphIndex> linearization;
202 : 1190 : SimpleCandidateFinder finder(depgraph);
203 : 1190 : SetType todo = depgraph.Positions();
204 : 1190 : bool optimal = true;
205 [ + + ]: 15444 : while (todo.Any()) {
206 [ + + ]: 14254 : auto [candidate, iterations_done] = finder.FindCandidateSet(max_iterations);
207 [ + + ]: 14254 : if (iterations_done == max_iterations) optimal = false;
208 : 14254 : depgraph.AppendTopo(linearization, candidate.transactions);
209 : 14254 : todo -= candidate.transactions;
210 : 14254 : finder.MarkDone(candidate.transactions);
211 : 14254 : max_iterations -= iterations_done;
212 : : }
213 : 1190 : return {std::move(linearization), optimal};
214 : 1190 : }
215 : :
216 : : /** An even simpler linearization algorithm that tries all permutations.
217 : : *
218 : : * This roughly matches SimpleLinearize() (and Linearize) in interface and behavior, but always
219 : : * tries all topologically-valid transaction orderings, has no way to bound how much work it does,
220 : : * and always finds the optimal. With an O(n!) complexity, it should only be used for small
221 : : * clusters.
222 : : */
223 : : template<typename SetType>
224 : 111 : std::vector<DepGraphIndex> ExhaustiveLinearize(const DepGraph<SetType>& depgraph)
225 : : {
226 : : // The best linearization so far, and its chunking.
227 : 111 : std::vector<DepGraphIndex> linearization;
228 : 111 : std::vector<FeeFrac> chunking;
229 : :
230 [ + + ]: 111 : std::vector<DepGraphIndex> perm_linearization;
231 : : // Initialize with the lexicographically-first linearization.
232 [ + + + - : 750 : for (DepGraphIndex i : depgraph.Positions()) perm_linearization.push_back(i);
+ + ]
233 : : // Iterate over all valid permutations.
234 : : do {
235 : : /** What prefix of perm_linearization is topological. */
236 : 497748 : DepGraphIndex topo_length{0};
237 : 497748 : TestBitSet perm_done;
238 [ - + + + ]: 4320932 : while (topo_length < perm_linearization.size()) {
239 : 3864403 : auto i = perm_linearization[topo_length];
240 [ + + ]: 3864403 : perm_done.Set(i);
241 [ + + ]: 3864403 : if (!depgraph.Ancestors(i).IsSubsetOf(perm_done)) break;
242 : 3823184 : ++topo_length;
243 : : }
244 [ - + + + ]: 497748 : if (topo_length == perm_linearization.size()) {
245 : : // If all of perm_linearization is topological, check if it is perhaps our best
246 : : // linearization so far.
247 [ - + ]: 456529 : auto perm_chunking = ChunkLinearization(depgraph, perm_linearization);
248 [ - + + - ]: 456529 : auto cmp = CompareChunks(perm_chunking, chunking);
249 : : // If the diagram is better, or if it is equal but with more chunks (because we
250 : : // prefer minimal chunks), consider this better.
251 [ + + + + : 507200 : if (linearization.empty() || cmp > 0 || (cmp == 0 && perm_chunking.size() > chunking.size())) {
+ + - + +
+ ]
252 [ + - ]: 1101 : linearization = perm_linearization;
253 [ + - ]: 1101 : chunking = perm_chunking;
254 : : }
255 : 456529 : } else {
256 : : // Otherwise, fast forward to the last permutation with the same non-topological
257 : : // prefix.
258 : 41219 : auto first_non_topo = perm_linearization.begin() + topo_length;
259 [ - + ]: 41219 : assert(std::is_sorted(first_non_topo + 1, perm_linearization.end()));
260 : 41219 : std::reverse(first_non_topo + 1, perm_linearization.end());
261 : : }
262 [ + + ]: 497748 : } while(std::next_permutation(perm_linearization.begin(), perm_linearization.end()));
263 : :
264 : 111 : return linearization;
265 : 111 : }
266 : :
267 : :
268 : : /** Stitch connected components together in a DepGraph, guaranteeing its corresponding cluster is connected. */
269 : : template<typename BS>
270 : 840 : void MakeConnected(DepGraph<BS>& depgraph)
271 : : {
272 : 840 : auto todo = depgraph.Positions();
273 : 840 : auto comp = depgraph.FindConnectedComponent(todo);
274 : 840 : Assume(depgraph.IsConnected(comp));
275 : 840 : todo -= comp;
276 [ + + ]: 6855 : while (todo.Any()) {
277 : 6015 : auto nextcomp = depgraph.FindConnectedComponent(todo);
278 : 6015 : Assume(depgraph.IsConnected(nextcomp));
279 : 6015 : depgraph.AddDependencies(BS::Singleton(comp.Last()), nextcomp.First());
280 : 6015 : todo -= nextcomp;
281 : 6015 : comp = nextcomp;
282 : : }
283 : 840 : }
284 : :
285 : : /** Given a dependency graph, and a todo set, read a topological subset of todo from reader. */
286 : : template<typename SetType>
287 : 2625 : SetType ReadTopologicalSet(const DepGraph<SetType>& depgraph, const SetType& todo, SpanReader& reader, bool non_empty)
288 : : {
289 : : // Read a bitmask from the fuzzing input. Add 1 if non_empty, so the mask is definitely not
290 : : // zero in that case.
291 [ + + ]: 2625 : uint64_t mask{0};
292 : : try {
293 [ + + ]: 2625 : reader >> VARINT(mask);
294 [ - + ]: 1941 : } catch(const std::ios_base::failure&) {}
295 [ + + ]: 2625 : if (mask != uint64_t(-1)) mask += non_empty;
296 : :
297 : 2625 : SetType ret;
298 [ + - + + ]: 33499 : for (auto i : todo) {
299 [ + + ]: 28249 : if (!ret[i]) {
300 [ + + ]: 26911 : if (mask & 1) ret |= depgraph.Ancestors(i);
301 : 26911 : mask >>= 1;
302 : : }
303 : : }
304 : 2625 : ret &= todo;
305 : :
306 : : // While mask starts off non-zero if non_empty is true, it is still possible that all its low
307 : : // bits are 0, and ret ends up being empty. As a last resort, use the in-todo ancestry of the
308 : : // first todo position.
309 [ + - + + ]: 2625 : if (non_empty && ret.None()) {
310 : 177 : Assume(todo.Any());
311 : 177 : ret = depgraph.Ancestors(todo.First()) & todo;
312 : 177 : Assume(ret.Any());
313 : : }
314 : 2625 : return ret;
315 : : }
316 : :
317 : : /** Given a dependency graph, construct any valid linearization for it, reading from a SpanReader. */
318 : : template<typename BS>
319 : 7873 : std::vector<DepGraphIndex> ReadLinearization(const DepGraph<BS>& depgraph, SpanReader& reader, bool topological=true)
320 : : {
321 : 7873 : std::vector<DepGraphIndex> linearization;
322 : 7873 : TestBitSet todo = depgraph.Positions();
323 : : // In every iteration one transaction is appended to linearization.
324 [ + + ]: 187966 : while (todo.Any()) {
325 : : // Compute the set of transactions to select from.
326 : 172220 : TestBitSet potential_next;
327 [ + + ]: 172220 : if (topological) {
328 : : // Find all transactions with no not-yet-included ancestors.
329 [ + + ]: 2485244 : for (auto j : todo) {
330 [ + + ]: 3450660 : if ((depgraph.Ancestors(j) & todo) == TestBitSet::Singleton(j)) {
331 : 1133669 : potential_next.Set(j);
332 : : }
333 : : }
334 : : } else {
335 : : // Allow any element to be selected next, regardless of topology.
336 : 3967 : potential_next = todo;
337 : : }
338 : : // There must always be one (otherwise there is a cycle in the graph).
339 [ - + ]: 172220 : assert(potential_next.Any());
340 : : // Read a number from reader, and interpret it as index into potential_next.
341 [ + + ]: 172220 : uint64_t idx{0};
342 : : try {
343 [ + + + - ]: 344440 : reader >> VARINT(idx);
344 [ - + ]: 166493 : } catch (const std::ios_base::failure&) {}
345 : 172220 : idx %= potential_next.Count();
346 : : // Find out which transaction that corresponds to.
347 [ + - + - ]: 361893 : for (auto j : potential_next) {
348 [ + + ]: 189673 : if (idx == 0) {
349 : : // When found, add it to linearization and remove it from todo.
350 [ + - ]: 172220 : linearization.push_back(j);
351 [ - + ]: 172220 : assert(todo[j]);
352 : 172220 : todo.Reset(j);
353 : 172220 : break;
354 : : }
355 : 17453 : --idx;
356 : : }
357 : : }
358 : 7873 : return linearization;
359 : 0 : }
360 : :
361 : : /** Given a dependency graph, construct a tree-structured graph.
362 : : *
363 : : * Copies the nodes from the depgraph, but only keeps the first parent (even direction)
364 : : * or the first child (odd direction) for each transaction.
365 : : */
366 : : template<typename BS>
367 : 294 : DepGraph<BS> BuildTreeGraph(const DepGraph<BS>& depgraph, uint8_t direction)
368 : : {
369 : 294 : DepGraph<BS> depgraph_tree;
370 [ - + + + ]: 8146 : for (DepGraphIndex i = 0; i < depgraph.PositionRange(); ++i) {
371 [ + + ]: 7852 : if (depgraph.Positions()[i]) {
372 : 5697 : depgraph_tree.AddTransaction(depgraph.FeeRate(i));
373 : : } else {
374 : : // For holes, add a dummy transaction which is deleted below, so that non-hole
375 : : // transactions retain their position.
376 : 2155 : depgraph_tree.AddTransaction(FeeFrac{});
377 : : }
378 : : }
379 : 294 : depgraph_tree.RemoveTransactions(BS::Fill(depgraph.PositionRange()) - depgraph.Positions());
380 : :
381 [ + + ]: 294 : if (direction & 1) {
382 [ + + + + ]: 3756 : for (DepGraphIndex i : depgraph.Positions()) {
383 [ + + ]: 3427 : auto children = depgraph.GetReducedChildren(i);
384 [ + + ]: 3427 : if (children.Any()) {
385 : 2411 : depgraph_tree.AddDependencies(BS::Singleton(i), children.First());
386 : : }
387 : : }
388 : : } else {
389 [ + + + + ]: 2520 : for (DepGraphIndex i : depgraph.Positions()) {
390 [ + + ]: 2270 : auto parents = depgraph.GetReducedParents(i);
391 [ + + ]: 2270 : if (parents.Any()) {
392 : 1538 : depgraph_tree.AddDependencies(BS::Singleton(parents.First()), i);
393 : : }
394 : : }
395 : : }
396 : :
397 : 294 : return depgraph_tree;
398 : : }
399 : :
400 : : } // namespace
401 : :
402 [ + - ]: 761 : FUZZ_TARGET(clusterlin_depgraph_sim)
403 : : {
404 : : // Simulation test to verify the full behavior of DepGraph.
405 : :
406 : 285 : FuzzedDataProvider provider(buffer.data(), buffer.size());
407 : :
408 : : /** Real DepGraph being tested. */
409 : 285 : DepGraph<TestBitSet> real;
410 : : /** Simulated DepGraph (sim[i] is std::nullopt if position i does not exist; otherwise,
411 : : * sim[i]->first is its individual feerate, and sim[i]->second is its set of ancestors. */
412 : 285 : std::array<std::optional<std::pair<FeeFrac, TestBitSet>>, TestBitSet::Size()> sim;
413 : : /** The number of non-nullopt position in sim. */
414 : 285 : DepGraphIndex num_tx_sim{0};
415 : :
416 : : /** Read a valid index of a transaction from the provider. */
417 : 13049 : auto idx_fn = [&]() {
418 : 12764 : auto offset = provider.ConsumeIntegralInRange<DepGraphIndex>(0, num_tx_sim - 1);
419 [ + - ]: 83101 : for (DepGraphIndex i = 0; i < sim.size(); ++i) {
420 [ + + ]: 83101 : if (!sim[i].has_value()) continue;
421 [ + + ]: 70623 : if (offset == 0) return i;
422 : 57859 : --offset;
423 : : }
424 : 0 : AssertUnreachable();
425 : 285 : };
426 : :
427 : : /** Read a valid subset of the transactions from the provider. */
428 : 13049 : auto subset_fn = [&]() {
429 : 12764 : auto range = (uint64_t{1} << num_tx_sim) - 1;
430 : 12764 : const auto mask = provider.ConsumeIntegralInRange<uint64_t>(0, range);
431 : 12764 : auto mask_shifted = mask;
432 : 12764 : TestBitSet subset;
433 [ + + ]: 421212 : for (DepGraphIndex i = 0; i < sim.size(); ++i) {
434 [ + + ]: 408448 : if (!sim[i].has_value()) continue;
435 [ + + ]: 218336 : if (mask_shifted & 1) {
436 : 57434 : subset.Set(i);
437 : : }
438 : 218336 : mask_shifted >>= 1;
439 : : }
440 [ - + ]: 12764 : assert(mask_shifted == 0);
441 : 12764 : return subset;
442 : 285 : };
443 : :
444 : : /** Read any set of transactions from the provider (including unused positions). */
445 : 10700 : auto set_fn = [&]() {
446 : 10415 : auto range = (uint64_t{1} << sim.size()) - 1;
447 : 10415 : const auto mask = provider.ConsumeIntegralInRange<uint64_t>(0, range);
448 : 10415 : TestBitSet set;
449 [ + + ]: 343695 : for (DepGraphIndex i = 0; i < sim.size(); ++i) {
450 [ + + ]: 333280 : if ((mask >> i) & 1) {
451 : 120689 : set.Set(i);
452 : : }
453 : : }
454 : 10415 : return set;
455 : 285 : };
456 : :
457 : : /** Propagate ancestor information in sim. */
458 : 10985 : auto anc_update_fn = [&]() {
459 : 12460 : while (true) {
460 : 12460 : bool updates{false};
461 [ + + ]: 411180 : for (DepGraphIndex chl = 0; chl < sim.size(); ++chl) {
462 [ + + ]: 398720 : if (!sim[chl].has_value()) continue;
463 [ + - + + ]: 897706 : for (auto par : sim[chl]->second) {
464 [ + + ]: 532964 : if (!sim[chl]->second.IsSupersetOf(sim[par]->second)) {
465 : 7580 : sim[chl]->second |= sim[par]->second;
466 : 7580 : updates = true;
467 : : }
468 : : }
469 : : }
470 [ + + ]: 12460 : if (!updates) break;
471 : : }
472 : 10985 : };
473 : :
474 : : /** Compare the state of transaction i in the simulation with the real one. */
475 : 130094 : auto check_fn = [&](DepGraphIndex i) {
476 : : // Compare used positions.
477 [ - + ]: 129809 : assert(real.Positions()[i] == sim[i].has_value());
478 [ + + ]: 129809 : if (sim[i].has_value()) {
479 : : // Compare feerate.
480 [ + - ]: 27390 : assert(real.FeeRate(i) == sim[i]->first);
481 : : // Compare ancestors (note that SanityCheck verifies correspondence between ancestors
482 : : // and descendants, so we can restrict ourselves to ancestors here).
483 [ - + ]: 27390 : assert(real.Ancestors(i) == sim[i]->second);
484 : : }
485 : 130094 : };
486 : :
487 : 285 : auto last_compaction_pos{real.PositionRange()};
488 : :
489 [ + + + + ]: 61900 : LIMITED_WHILE (provider.remaining_bytes() > 0, 1000) {
490 : 61615 : int command = provider.ConsumeIntegral<uint8_t>() % 4;
491 : 63770 : while (true) {
492 : : // Iterate decreasing command until an applicable branch is found.
493 [ + + + + ]: 63770 : if (num_tx_sim < TestBitSet::Size() && command-- == 0) {
494 : : // AddTransaction.
495 : 27390 : auto fee = provider.ConsumeIntegralInRange<int64_t>(-0x8000000000000, 0x7ffffffffffff);
496 : 27390 : auto size = provider.ConsumeIntegralInRange<int32_t>(1, 0x3fffff);
497 : 27390 : FeeFrac feerate{fee, size};
498 : : // Apply to DepGraph.
499 : 27390 : auto idx = real.AddTransaction(feerate);
500 : : // Verify that the returned index is correct.
501 [ - + ]: 27390 : assert(!sim[idx].has_value());
502 [ + - ]: 396442 : for (DepGraphIndex i = 0; i < TestBitSet::Size(); ++i) {
503 [ + + ]: 396442 : if (!sim[i].has_value()) {
504 [ - + ]: 27390 : assert(idx == i);
505 : : break;
506 : : }
507 : : }
508 : : // Update sim.
509 [ - + ]: 27390 : sim[idx] = {feerate, TestBitSet::Singleton(idx)};
510 : 27390 : ++num_tx_sim;
511 : 27390 : break;
512 [ + + + + ]: 36380 : } else if (num_tx_sim > 0 && command-- == 0) {
513 : : // AddDependencies.
514 [ + - ]: 12764 : DepGraphIndex child = idx_fn();
515 : 12764 : auto parents = subset_fn();
516 : : // Apply to DepGraph.
517 : 12764 : real.AddDependencies(parents, child);
518 : : // Apply to sim.
519 : 12764 : sim[child]->second |= parents;
520 : 12764 : break;
521 [ + + + + ]: 23616 : } else if (num_tx_sim > 0 && command-- == 0) {
522 : : // Remove transactions.
523 : 10415 : auto del = set_fn();
524 : : // Propagate all ancestry information before deleting anything in the simulation (as
525 : : // intermediary transactions may be deleted which impact connectivity).
526 : 10415 : anc_update_fn();
527 : : // Compare the state of the transactions being deleted.
528 [ + + + + ]: 140619 : for (auto i : del) check_fn(i);
529 : : // Apply to DepGraph.
530 : 10415 : real.RemoveTransactions(del);
531 : : // Apply to sim.
532 [ + + ]: 343695 : for (DepGraphIndex i = 0; i < sim.size(); ++i) {
533 [ + + ]: 333280 : if (sim[i].has_value()) {
534 [ + + ]: 133455 : if (del[i]) {
535 : 22665 : --num_tx_sim;
536 [ + - ]: 355945 : sim[i] = std::nullopt;
537 : : } else {
538 : 110790 : sim[i]->second -= del;
539 : : }
540 : : }
541 : : }
542 : : break;
543 [ + + ]: 13201 : } else if (command-- == 0) {
544 : : // Compact.
545 [ - + ]: 11046 : const size_t mem_before{real.DynamicMemoryUsage()};
546 : 11046 : real.Compact();
547 [ - + ]: 11046 : const size_t mem_after{real.DynamicMemoryUsage()};
548 [ - + + + : 11046 : assert(real.PositionRange() < last_compaction_pos ? mem_after < mem_before : mem_after <= mem_before);
- + ]
549 : : last_compaction_pos = real.PositionRange();
550 : : break;
551 : : }
552 : : }
553 : : }
554 : :
555 : : // Compare the real obtained depgraph against the simulation.
556 : 285 : anc_update_fn();
557 [ + + ]: 9405 : for (DepGraphIndex i = 0; i < sim.size(); ++i) check_fn(i);
558 [ - + ]: 285 : assert(real.TxCount() == num_tx_sim);
559 : : // Sanity check the result (which includes round-tripping serialization, if applicable).
560 [ + - ]: 285 : SanityCheck(real);
561 : 285 : }
562 : :
563 [ + - ]: 662 : FUZZ_TARGET(clusterlin_depgraph_serialization)
564 : : {
565 : : // Verify that any deserialized depgraph is acyclic and roundtrips to an identical depgraph.
566 : :
567 : : // Construct a graph by deserializing.
568 : 186 : SpanReader reader(buffer);
569 : 186 : DepGraph<TestBitSet> depgraph;
570 : 186 : DepGraphIndex par_code{0}, chl_code{0};
571 : 186 : try {
572 [ + - + + : 186 : reader >> Using<DepGraphFormatter>(depgraph) >> VARINT(par_code) >> VARINT(chl_code);
+ + ]
573 [ - + ]: 162 : } catch (const std::ios_base::failure&) {}
574 [ + - ]: 186 : SanityCheck(depgraph);
575 : :
576 : : // Verify the graph is a DAG.
577 [ - + ]: 186 : assert(depgraph.IsAcyclic());
578 : :
579 : : // Introduce a cycle, and then test that IsAcyclic returns false.
580 [ + + ]: 186 : if (depgraph.TxCount() < 2) return;
581 : 171 : DepGraphIndex par(0), chl(0);
582 : : // Pick any transaction of depgraph as parent.
583 [ + - ]: 171 : par_code %= depgraph.TxCount();
584 [ + - + - ]: 657 : for (auto i : depgraph.Positions()) {
585 [ + + ]: 486 : if (par_code == 0) {
586 : : par = i;
587 : : break;
588 : : }
589 : 315 : --par_code;
590 : : }
591 : : // Pick any ancestor of par (excluding itself) as child, if any.
592 [ + + ]: 171 : auto ancestors = depgraph.Ancestors(par) - TestBitSet::Singleton(par);
593 [ + + ]: 171 : if (ancestors.None()) return;
594 : 82 : chl_code %= ancestors.Count();
595 [ + - ]: 167 : for (auto i : ancestors) {
596 [ + + ]: 167 : if (chl_code == 0) {
597 : : chl = i;
598 : : break;
599 : : }
600 : 85 : --chl_code;
601 : : }
602 : : // Add the cycle-introducing dependency.
603 : 82 : depgraph.AddDependencies(TestBitSet::Singleton(par), chl);
604 : : // Check that we now detect a cycle.
605 [ - + ]: 82 : assert(!depgraph.IsAcyclic());
606 : 186 : }
607 : :
608 [ + - ]: 573 : FUZZ_TARGET(clusterlin_components)
609 : : {
610 : : // Verify the behavior of DepGraphs's FindConnectedComponent and IsConnected functions.
611 : :
612 : : // Construct a depgraph.
613 : 97 : SpanReader reader(buffer);
614 : 97 : DepGraph<TestBitSet> depgraph;
615 : 97 : try {
616 [ + - ]: 97 : reader >> Using<DepGraphFormatter>(depgraph);
617 [ - - ]: 0 : } catch (const std::ios_base::failure&) {}
618 : :
619 : 97 : TestBitSet todo = depgraph.Positions();
620 [ + + ]: 1144 : while (todo.Any()) {
621 : : // Pick a transaction in todo, or nothing.
622 : 1047 : std::optional<DepGraphIndex> picked;
623 : 1047 : {
624 : 1047 : uint64_t picked_num{0};
625 : 1047 : try {
626 [ + + ]: 1047 : reader >> VARINT(picked_num);
627 [ - + ]: 681 : } catch (const std::ios_base::failure&) {}
628 [ + + + + ]: 1047 : if (picked_num < todo.Size() && todo[picked_num]) {
629 : 189 : picked = picked_num;
630 : : }
631 : : }
632 : :
633 : : // Find a connected component inside todo, including picked if any.
634 [ + + ]: 1047 : auto component = picked ? depgraph.GetConnectedComponent(todo, *picked)
635 : 858 : : depgraph.FindConnectedComponent(todo);
636 : :
637 : : // The component must be a subset of todo and non-empty.
638 [ - + ]: 1047 : assert(component.IsSubsetOf(todo));
639 [ - + ]: 1047 : assert(component.Any());
640 : :
641 : : // If picked was provided, the component must include it.
642 [ + + - + ]: 1047 : if (picked) assert(component[*picked]);
643 : :
644 : : // If todo is the entire graph, and the entire graph is connected, then the component must
645 : : // be the entire graph.
646 [ + + ]: 1047 : if (todo == depgraph.Positions()) {
647 [ + + - + ]: 155 : assert((component == todo) == depgraph.IsConnected());
648 : : }
649 : :
650 : : // If subset is connected, then component must match subset.
651 [ + + - + ]: 1839 : assert((component == todo) == depgraph.IsConnected(todo));
652 : :
653 : : // The component cannot have any ancestors or descendants outside of component but in todo.
654 [ + - + + ]: 7358 : for (auto i : component) {
655 [ - + ]: 5264 : assert((depgraph.Ancestors(i) & todo).IsSubsetOf(component));
656 [ - + ]: 5264 : assert((depgraph.Descendants(i) & todo).IsSubsetOf(component));
657 : : }
658 : :
659 : : // Starting from any component element, we must be able to reach every element.
660 [ + - + + ]: 7358 : for (auto i : component) {
661 : : // Start with just i as reachable.
662 : 5264 : TestBitSet reachable = TestBitSet::Singleton(i);
663 : : // Add in-todo descendants and ancestors to reachable until it does not change anymore.
664 : 33580 : while (true) {
665 : 19422 : TestBitSet new_reachable = reachable;
666 [ + - + + ]: 224683 : for (auto j : new_reachable) {
667 : 185839 : new_reachable |= depgraph.Ancestors(j) & todo;
668 : 185839 : new_reachable |= depgraph.Descendants(j) & todo;
669 : : }
670 [ + + ]: 19422 : if (new_reachable == reachable) break;
671 : 14158 : reachable = new_reachable;
672 : 14158 : }
673 : : // Verify that the result is the entire component.
674 [ - + ]: 5264 : assert(component == reachable);
675 : : }
676 : :
677 : : // Construct an arbitrary subset of todo.
678 : 1047 : uint64_t subset_bits{0};
679 : 1047 : try {
680 [ + + ]: 1047 : reader >> VARINT(subset_bits);
681 [ - + ]: 697 : } catch (const std::ios_base::failure&) {}
682 : 1047 : TestBitSet subset;
683 [ + - + + ]: 24942 : for (DepGraphIndex i : depgraph.Positions()) {
684 [ + + ]: 22848 : if (todo[i]) {
685 [ + + ]: 11934 : if (subset_bits & 1) subset.Set(i);
686 : 11934 : subset_bits >>= 1;
687 : : }
688 : : }
689 : : // Which must be non-empty.
690 [ + + ]: 1047 : if (subset.None()) subset = TestBitSet::Singleton(todo.First());
691 : : // Remove it from todo.
692 : 1047 : todo -= subset;
693 : : }
694 : :
695 : : // No components can be found in an empty subset.
696 [ - + ]: 97 : assert(depgraph.FindConnectedComponent(todo).None());
697 : 97 : }
698 : :
699 [ + - ]: 659 : FUZZ_TARGET(clusterlin_make_connected)
700 : : {
701 : : // Verify that MakeConnected makes graphs connected.
702 : :
703 : 183 : SpanReader reader(buffer);
704 : 183 : DepGraph<TestBitSet> depgraph;
705 : 183 : try {
706 [ + - ]: 183 : reader >> Using<DepGraphFormatter>(depgraph);
707 [ - - ]: 0 : } catch (const std::ios_base::failure&) {}
708 [ + - ]: 183 : MakeConnected(depgraph);
709 [ + - ]: 183 : SanityCheck(depgraph);
710 [ - + ]: 183 : assert(depgraph.IsConnected());
711 : 183 : }
712 : :
713 [ + - ]: 584 : FUZZ_TARGET(clusterlin_chunking)
714 : : {
715 : : // Verify the correctness of the ChunkLinearization function.
716 : :
717 : : // Construct a graph by deserializing.
718 : 108 : SpanReader reader(buffer);
719 : 108 : DepGraph<TestBitSet> depgraph;
720 : 108 : try {
721 [ + - ]: 108 : reader >> Using<DepGraphFormatter>(depgraph);
722 [ - - ]: 0 : } catch (const std::ios_base::failure&) {}
723 : :
724 : : // Read a valid linearization for depgraph.
725 [ + - ]: 108 : auto linearization = ReadLinearization(depgraph, reader);
726 : :
727 : : // Invoke the chunking functions.
728 [ - + ]: 108 : auto chunking = ChunkLinearization(depgraph, linearization);
729 [ - + ]: 108 : auto chunking_info = ChunkLinearizationInfo(depgraph, linearization);
730 : :
731 : : // Verify consistency between the two functions.
732 [ - + - + : 108 : assert(chunking.size() == chunking_info.size());
- + ]
733 [ - + + + ]: 557 : for (size_t i = 0; i < chunking.size(); ++i) {
734 [ + - ]: 449 : assert(chunking[i] == chunking_info[i].feerate);
735 [ + - ]: 898 : assert(SetInfo(depgraph, chunking_info[i].transactions) == chunking_info[i]);
736 : : }
737 : :
738 : : // Verify that chunk feerates are monotonically non-increasing.
739 [ + + ]: 456 : for (size_t i = 1; i < chunking.size(); ++i) {
740 [ - + ]: 348 : assert(ByRatio{chunking[i]} <= ByRatio{chunking[i - 1]});
741 : : }
742 : :
743 : : // Naively recompute the chunks (each is the highest-feerate prefix of what remains).
744 : 108 : auto todo = depgraph.Positions();
745 [ + + ]: 557 : for (const auto& [chunk_set, chunk_feerate] : chunking_info) {
746 [ - + ]: 449 : assert(todo.Any());
747 : 449 : SetInfo<TestBitSet> accumulator, best;
748 [ + + ]: 9938 : for (DepGraphIndex idx : linearization) {
749 [ + + ]: 9489 : if (todo[idx]) {
750 : 5259 : accumulator.Set(depgraph, idx);
751 [ + + + + ]: 5259 : if (best.feerate.IsEmpty() || ByRatio{accumulator.feerate} > ByRatio{best.feerate}) {
752 : 983 : best = accumulator;
753 : : }
754 : : }
755 : : }
756 [ + - ]: 449 : assert(chunk_feerate == best.feerate);
757 [ - + ]: 449 : assert(chunk_set == best.transactions);
758 [ - + ]: 449 : assert(best.transactions.IsSubsetOf(todo));
759 : 449 : todo -= best.transactions;
760 : : }
761 [ - + ]: 108 : assert(todo.None());
762 : 108 : }
763 : :
764 : : static constexpr auto MAX_SIMPLE_ITERATIONS = 300000;
765 : :
766 [ + - ]: 628 : FUZZ_TARGET(clusterlin_simple_finder)
767 : : {
768 : : // Verify that SimpleCandidateFinder works as expected by sanity checking the results
769 : : // and comparing them (if claimed to be optimal) against the sets found by
770 : : // ExhaustiveCandidateFinder.
771 : : //
772 : : // Note that SimpleCandidateFinder is only used in tests; the purpose of this fuzz test is to
773 : : // establish confidence in SimpleCandidateFinder, so that it can be used in SimpleLinearize,
774 : : // which is then used to test Linearize below.
775 : :
776 : : // Retrieve a depgraph from the fuzz input.
777 : 152 : SpanReader reader(buffer);
778 : 152 : DepGraph<TestBitSet> depgraph;
779 : 152 : try {
780 [ + - ]: 152 : reader >> Using<DepGraphFormatter>(depgraph);
781 [ - - ]: 0 : } catch (const std::ios_base::failure&) {}
782 : :
783 : : // Instantiate the SimpleCandidateFinder to be tested, and the ExhaustiveCandidateFinder it is
784 : : // being tested against.
785 : 152 : SimpleCandidateFinder smp_finder(depgraph);
786 : 152 : ExhaustiveCandidateFinder exh_finder(depgraph);
787 : :
788 : 152 : auto todo = depgraph.Positions();
789 [ + + ]: 1480 : while (todo.Any()) {
790 [ - + ]: 1328 : assert(!smp_finder.AllDone());
791 [ - + ]: 1328 : assert(!exh_finder.AllDone());
792 : :
793 : : // Call SimpleCandidateFinder.
794 [ - + ]: 1328 : auto [found, iterations_done] = smp_finder.FindCandidateSet(MAX_SIMPLE_ITERATIONS);
795 : 1328 : bool optimal = (iterations_done != MAX_SIMPLE_ITERATIONS);
796 : :
797 : : // Sanity check the result.
798 [ - + ]: 1328 : assert(iterations_done <= MAX_SIMPLE_ITERATIONS);
799 [ - + ]: 1328 : assert(found.transactions.Any());
800 [ - + ]: 1328 : assert(found.transactions.IsSubsetOf(todo));
801 [ + - ]: 1328 : assert(depgraph.FeeRate(found.transactions) == found.feerate);
802 : : // Check that it is topologically valid.
803 [ + - + + ]: 5846 : for (auto i : found.transactions) {
804 [ - + ]: 3190 : assert(found.transactions.IsSupersetOf(depgraph.Ancestors(i) & todo));
805 : : }
806 : :
807 : : // At most 2^(N-1) iterations can be required: the number of non-empty connected subsets a
808 : : // graph with N transactions can have. If MAX_SIMPLE_ITERATIONS exceeds this number, the
809 : : // result is necessarily optimal.
810 [ - + ]: 1328 : assert(iterations_done <= (uint64_t{1} << (todo.Count() - 1)));
811 [ + + - + ]: 1328 : if (MAX_SIMPLE_ITERATIONS > (uint64_t{1} << (todo.Count() - 1))) assert(optimal);
812 : :
813 : : // SimpleCandidateFinder only finds connected sets.
814 [ - + ]: 1328 : assert(depgraph.IsConnected(found.transactions));
815 : :
816 : : // Perform further quality checks only if SimpleCandidateFinder claims an optimal result.
817 [ + + ]: 1328 : if (optimal) {
818 [ + + ]: 1297 : if (todo.Count() <= 12) {
819 : : // Compare with ExhaustiveCandidateFinder. This quickly gets computationally
820 : : // expensive for large clusters (O(2^n)), so only do it for sufficiently small ones.
821 : 844 : auto exhaustive = exh_finder.FindCandidateSet();
822 [ + - ]: 844 : assert(exhaustive.feerate == found.feerate);
823 : : }
824 : :
825 : : // Compare with a non-empty topological set read from the fuzz input (comparing with an
826 : : // empty set is not interesting).
827 [ + - ]: 1297 : auto read_topo = ReadTopologicalSet(depgraph, todo, reader, /*non_empty=*/true);
828 [ - + ]: 1297 : assert(ByRatioNegSize{found.feerate} >= ByRatioNegSize{depgraph.FeeRate(read_topo)});
829 : : }
830 : :
831 : : // Find a non-empty topologically valid subset of transactions to remove from the graph.
832 : : // Using an empty set would mean the next iteration is identical to the current one, and
833 : : // could cause an infinite loop.
834 [ + - ]: 1328 : auto del_set = ReadTopologicalSet(depgraph, todo, reader, /*non_empty=*/true);
835 : 1328 : todo -= del_set;
836 : 1328 : smp_finder.MarkDone(del_set);
837 : 1328 : exh_finder.MarkDone(del_set);
838 : : }
839 : :
840 [ - + ]: 152 : assert(smp_finder.AllDone());
841 [ - + ]: 152 : assert(exh_finder.AllDone());
842 : 152 : }
843 : :
844 [ + - ]: 722 : FUZZ_TARGET(clusterlin_simple_linearize)
845 : : {
846 : : // Verify the behavior of SimpleLinearize(). Note that SimpleLinearize is only used in tests;
847 : : // the purpose of this fuzz test is to establish confidence in SimpleLinearize, so that it can
848 : : // be used to test the real Linearize function in the fuzz test below.
849 : :
850 : : // Retrieve an iteration count and a depgraph from the fuzz input.
851 : 246 : SpanReader reader(buffer);
852 : 246 : uint64_t iter_count{0};
853 : 246 : DepGraph<TestBitSet> depgraph;
854 : 246 : try {
855 [ + + + - ]: 246 : reader >> VARINT(iter_count) >> Using<DepGraphFormatter>(depgraph);
856 [ - + ]: 4 : } catch (const std::ios_base::failure&) {}
857 : 246 : iter_count %= MAX_SIMPLE_ITERATIONS;
858 : :
859 : : // Invoke SimpleLinearize().
860 [ - + ]: 246 : auto [linearization, optimal] = SimpleLinearize(depgraph, iter_count);
861 [ - + ]: 246 : SanityCheck(depgraph, linearization);
862 [ - + ]: 246 : auto simple_chunking = ChunkLinearization(depgraph, linearization);
863 : :
864 : : // If the iteration count is sufficiently high, an optimal linearization must be found.
865 : : // SimpleLinearize on k transactions can take up to 2^(k-1) iterations (one per non-empty
866 : : // connected topologically valid subset), which sums over k=1..n to (2^n)-1.
867 [ + - ]: 246 : const uint64_t n = depgraph.TxCount();
868 [ + - + + ]: 246 : if (n <= 63 && (iter_count >> n)) {
869 [ - + ]: 67 : assert(optimal);
870 : : }
871 : :
872 : : // If SimpleLinearize claims optimal result, and the cluster is sufficiently small (there are
873 : : // n! linearizations), test that the result is as good as every valid linearization.
874 [ + + + + ]: 246 : if (optimal && depgraph.TxCount() <= 8) {
875 [ + - ]: 111 : auto exh_linearization = ExhaustiveLinearize(depgraph);
876 [ - + ]: 111 : auto exh_chunking = ChunkLinearization(depgraph, exh_linearization);
877 [ - + - + : 111 : auto cmp = CompareChunks(simple_chunking, exh_chunking);
+ - ]
878 [ - + ]: 111 : assert(cmp == 0);
879 [ - + - + : 111 : assert(simple_chunking.size() == exh_chunking.size());
- + ]
880 : 111 : }
881 : :
882 [ + + ]: 246 : if (optimal) {
883 : : // Compare with a linearization read from the fuzz input.
884 [ + - ]: 197 : auto read = ReadLinearization(depgraph, reader);
885 [ - + ]: 197 : auto read_chunking = ChunkLinearization(depgraph, read);
886 [ - + - + : 197 : auto cmp = CompareChunks(simple_chunking, read_chunking);
+ - ]
887 [ - + ]: 197 : assert(cmp >= 0);
888 : 197 : }
889 : 246 : }
890 : :
891 [ + - ]: 1088 : FUZZ_TARGET(clusterlin_sfl)
892 : : {
893 : : // Verify the individual steps of the SFL algorithm.
894 : :
895 : 612 : SpanReader reader(buffer);
896 : 612 : DepGraph<TestBitSet> depgraph;
897 : 612 : uint8_t flags{1};
898 : 612 : uint64_t rng_seed{0};
899 : 612 : try {
900 [ + - + + : 612 : reader >> rng_seed >> flags >> Using<DepGraphFormatter>(depgraph);
+ - ]
901 [ - + ]: 2 : } catch (const std::ios_base::failure&) {}
902 [ + + ]: 612 : if (depgraph.TxCount() <= 1) return;
903 : 599 : InsecureRandomContext rng(rng_seed);
904 : : /** Whether to make the depgraph connected. */
905 : 599 : const bool make_connected = flags & 1;
906 : : /** Whether to load some input linearization into the state. */
907 : 599 : const bool load_linearization = flags & 2;
908 : : /** Whether that input linearization is topological. */
909 [ + + + + ]: 599 : const bool load_topological = load_linearization && (flags & 4);
910 : :
911 : : // Initialize SFL state.
912 [ + + + - ]: 599 : if (make_connected) MakeConnected(depgraph);
913 : 599 : SpanningForestState sfl(depgraph, rng.rand64());
914 : :
915 : : // Function to test the state.
916 : 599 : std::vector<FeeFrac> last_diagram;
917 : 599 : bool was_optimal{false};
918 : 26139 : auto test_fn = [&](bool is_optimal = false, bool is_minimal = false) {
919 [ + + ]: 25540 : if (rng.randbits(4) == 0) {
920 : : // Perform sanity checks from time to time (too computationally expensive to do after
921 : : // every step).
922 : 2436 : sfl.SanityCheck();
923 : : }
924 : 25540 : auto diagram = sfl.GetDiagram();
925 [ + + ]: 25540 : if (rng.randbits(4) == 0) {
926 : : // Verify that the diagram of GetLinearization() is at least as good as GetDiagram(),
927 : : // from time to time.
928 : 2433 : auto lin = sfl.GetLinearization(IndexTxOrder{});
929 [ - + ]: 2433 : auto lin_diagram = ChunkLinearization(depgraph, lin);
930 [ - + - + : 2433 : auto cmp_lin = CompareChunks(lin_diagram, diagram);
+ - ]
931 [ - + ]: 2433 : assert(cmp_lin >= 0);
932 : : // If we're in an allegedly optimal state, they must match.
933 [ + + - + ]: 2433 : if (is_optimal) assert(cmp_lin == 0);
934 : : // If we're in an allegedly minimal state, they must also have the same number of
935 : : // segments.
936 [ + + - + : 2433 : if (is_minimal) assert(diagram.size() == lin_diagram.size());
- + - + ]
937 : 2433 : }
938 : : // Verify that subsequent calls to GetDiagram() never get worse/incomparable.
939 [ + + ]: 25540 : if (!last_diagram.empty()) {
940 [ - + - + : 25059 : auto cmp = CompareChunks(diagram, last_diagram);
+ - ]
941 [ - + ]: 25059 : assert(cmp >= 0);
942 : : // If the last diagram was already optimal, the new one cannot be better.
943 [ + + - + ]: 25059 : if (was_optimal) assert(cmp == 0);
944 : : // Also, if the diagram was already optimal, the number of segments can only increase.
945 [ + + - + : 25059 : if (was_optimal) assert(diagram.size() >= last_diagram.size());
- + - + ]
946 : : }
947 : 25540 : last_diagram = std::move(diagram);
948 : 25540 : was_optimal = is_optimal;
949 : 26139 : };
950 : :
951 [ + + ]: 599 : if (load_linearization) {
952 [ + - ]: 252 : auto input_lin = ReadLinearization(depgraph, reader, load_topological);
953 [ - + ]: 252 : sfl.LoadLinearization(input_lin);
954 [ + + ]: 252 : if (load_topological) {
955 : : // The diagram of the loaded linearization forms an initial lower bound on future
956 : : // diagrams.
957 [ - + ]: 118 : last_diagram = ChunkLinearization(depgraph, input_lin);
958 : : } else {
959 : : // The input linearization may have been non-topological, so invoke MakeTopological to
960 : : // fix it still.
961 : 134 : sfl.MakeTopological();
962 : : }
963 : 252 : } else {
964 : : // Invoke MakeTopological to create an initial from-scratch topological state.
965 : 347 : sfl.MakeTopological();
966 : : }
967 : :
968 : : // Loop until optimal.
969 [ + - ]: 599 : test_fn();
970 : 599 : sfl.StartOptimizing();
971 : 9600 : while (true) {
972 [ + - ]: 9600 : test_fn();
973 [ + + ]: 9600 : if (!sfl.OptimizeStep()) break;
974 : : }
975 : :
976 : : // Loop until minimal.
977 [ + - ]: 599 : test_fn(/*is_optimal=*/true);
978 : 599 : sfl.StartMinimizing();
979 : 14143 : while (true) {
980 [ + - ]: 14143 : test_fn(/*is_optimal=*/true);
981 [ + + ]: 14143 : if (!sfl.MinimizeStep()) break;
982 : : }
983 [ + - ]: 599 : test_fn(/*is_optimal=*/true, /*is_minimal=*/true);
984 : :
985 : : // Verify that optimality is reached within an expected amount of work. This protects against
986 : : // hypothetical bugs that hugely increase the amount of work needed to reach optimality.
987 [ - + ]: 599 : assert(sfl.GetCost() <= MaxOptimalLinearizationCost(depgraph.TxCount()));
988 : :
989 : : // The result must be as good as SimpleLinearize.
990 [ - + ]: 599 : auto [simple_linearization, simple_optimal] = SimpleLinearize(depgraph, MAX_SIMPLE_ITERATIONS / 10);
991 [ - + ]: 599 : auto simple_diagram = ChunkLinearization(depgraph, simple_linearization);
992 [ - + - + : 599 : auto simple_cmp = CompareChunks(last_diagram, simple_diagram);
+ - ]
993 [ - + ]: 599 : assert(simple_cmp >= 0);
994 [ + + - + ]: 599 : if (simple_optimal) assert(simple_cmp == 0);
995 : : // If the diagram matches, we must also have at least as many segments (because the SFL state
996 : : // and its produced diagram are minimal);
997 [ + + - + : 599 : if (simple_cmp == 0) assert(last_diagram.size() >= simple_diagram.size());
- + + - ]
998 : :
999 : : // We can compare with any arbitrary linearization, and the diagram must be at least as good as
1000 : : // each.
1001 [ + + ]: 6589 : for (int i = 0; i < 10; ++i) {
1002 [ + - ]: 5990 : auto read_lin = ReadLinearization(depgraph, reader);
1003 [ - + ]: 5990 : auto read_diagram = ChunkLinearization(depgraph, read_lin);
1004 [ - + - + : 5990 : auto cmp = CompareChunks(last_diagram, read_diagram);
+ - ]
1005 [ - + ]: 5990 : assert(cmp >= 0);
1006 [ + + - + : 5990 : if (cmp == 0) assert(last_diagram.size() >= read_diagram.size());
- + - + ]
1007 : 5990 : }
1008 : 612 : }
1009 : :
1010 [ + - ]: 934 : FUZZ_TARGET(clusterlin_linearize)
1011 : : {
1012 : : // Verify the behavior of Linearize().
1013 : :
1014 : : // Retrieve an RNG seed, a maximum amount of work, a depgraph, and whether to make it connected
1015 : : // from the fuzz input.
1016 : 458 : SpanReader reader(buffer);
1017 : 458 : DepGraph<TestBitSet> depgraph;
1018 : 458 : uint64_t rng_seed{0};
1019 : 458 : uint64_t max_cost{0};
1020 : 458 : uint8_t flags{7};
1021 : 458 : try {
1022 [ + + + - : 458 : reader >> VARINT(max_cost) >> Using<DepGraphFormatter>(depgraph) >> rng_seed >> flags;
+ + + + ]
1023 [ - + ]: 264 : } catch (const std::ios_base::failure&) {}
1024 [ + + ]: 458 : if (depgraph.TxCount() <= 1) return;
1025 : 445 : bool make_connected = flags & 1;
1026 : : // The following 3 booleans have 4 combinations:
1027 : : // - (flags & 6) == 0: do not provide input linearization.
1028 : : // - (flags & 6) == 2: provide potentially non-topological input.
1029 : : // - (flags & 6) == 4: provide topological input linearization, but do not claim it is
1030 : : // topological.
1031 : : // - (flags & 6) == 6: provide topological input linearization, and claim it is topological.
1032 : 445 : bool provide_input = flags & 6;
1033 : 445 : bool provide_topological_input = flags & 4;
1034 : 445 : bool claim_topological_input = (flags & 6) == 6;
1035 : : // The most complicated graphs are connected ones (other ones just split up). Optionally force
1036 : : // the graph to be connected.
1037 [ + + + - ]: 445 : if (make_connected) MakeConnected(depgraph);
1038 : :
1039 : : // Optionally construct an old linearization for it.
1040 : 445 : std::vector<DepGraphIndex> old_linearization;
1041 [ + + ]: 445 : if (provide_input) {
1042 [ + - ]: 708 : old_linearization = ReadLinearization(depgraph, reader, /*topological=*/provide_topological_input);
1043 [ + + - + ]: 354 : if (provide_topological_input) SanityCheck(depgraph, old_linearization);
1044 : : }
1045 : :
1046 : : // Invoke Linearize().
1047 : 445 : max_cost &= 0x3fffff;
1048 [ - + ]: 445 : auto [linearization, optimal, cost] = Linearize(
1049 : : /*depgraph=*/depgraph,
1050 : : /*max_cost=*/max_cost,
1051 : : /*rng_seed=*/rng_seed,
1052 : : /*fallback_order=*/IndexTxOrder{},
1053 : 445 : /*old_linearization=*/old_linearization,
1054 [ - + - + ]: 445 : /*is_topological=*/claim_topological_input);
1055 [ - + ]: 445 : SanityCheck(depgraph, linearization);
1056 [ - + ]: 445 : auto chunking = ChunkLinearization(depgraph, linearization);
1057 : :
1058 : : // Linearization must always be as good as the old one, if provided and topological (even when
1059 : : // not claimed to be topological).
1060 [ + + ]: 445 : if (provide_topological_input) {
1061 [ - + ]: 305 : auto old_chunking = ChunkLinearization(depgraph, old_linearization);
1062 [ - + - + : 305 : auto cmp = CompareChunks(chunking, old_chunking);
+ - ]
1063 [ - + ]: 305 : assert(cmp >= 0);
1064 : 305 : }
1065 : :
1066 : : // If the maximum amount of work is sufficiently high, an optimal linearization must be found.
1067 [ + + ]: 445 : if (max_cost > MaxOptimalLinearizationCost(depgraph.TxCount())) {
1068 [ - + ]: 145 : assert(optimal);
1069 : : }
1070 : :
1071 : : // If Linearize claims optimal result, run quality tests.
1072 [ + + ]: 445 : if (optimal) {
1073 : : // It must be as good as SimpleLinearize.
1074 [ - + ]: 345 : auto [simple_linearization, simple_optimal] = SimpleLinearize(depgraph, MAX_SIMPLE_ITERATIONS);
1075 [ - + ]: 345 : SanityCheck(depgraph, simple_linearization);
1076 [ - + ]: 345 : auto simple_chunking = ChunkLinearization(depgraph, simple_linearization);
1077 [ - + - + : 345 : auto cmp = CompareChunks(chunking, simple_chunking);
+ - ]
1078 [ - + ]: 345 : assert(cmp >= 0);
1079 : : // If SimpleLinearize finds the optimal result too, they must be equal (if not,
1080 : : // SimpleLinearize is broken).
1081 [ + + - + ]: 345 : if (simple_optimal) assert(cmp == 0);
1082 : :
1083 : : // If simple_chunking is diagram-optimal, it cannot have more chunks than chunking (as
1084 : : // chunking is claimed to be optimal, which implies minimal chunks).
1085 [ + + - + : 345 : if (cmp == 0) assert(chunking.size() >= simple_chunking.size());
- + - + ]
1086 : :
1087 : : // Compare with a linearization read from the fuzz input.
1088 [ + - ]: 345 : auto read = ReadLinearization(depgraph, reader);
1089 [ - + ]: 345 : auto read_chunking = ChunkLinearization(depgraph, read);
1090 [ - + - + : 345 : auto cmp_read = CompareChunks(chunking, read_chunking);
+ - ]
1091 [ - + ]: 345 : assert(cmp_read >= 0);
1092 : :
1093 : : // Verify that within every chunk, the transactions are in a valid order. For any pair of
1094 : : // transactions, it should not be possible to swap them; either due to a missing
1095 : : // dependency, or because the order would be inconsistent with decreasing feerate,
1096 : : // increasing size, and fallback order (just DepGraphIndex value here).
1097 [ - + ]: 345 : auto chunking_info = ChunkLinearizationInfo(depgraph, linearization);
1098 : : /** The set of all transactions (strictly) before tx1 (see below), or (strictly) before
1099 : : * chunk1 (see even further below). */
1100 : 345 : TestBitSet done;
1101 : 345 : unsigned pos{0};
1102 [ + + ]: 4235 : for (const auto& chunk : chunking_info) {
1103 : 3890 : auto chunk_start = pos;
1104 : 3890 : auto chunk_end = pos + chunk.transactions.Count() - 1;
1105 : : // Go over all pairs of transactions. done is the set of transactions seen before pos1.
1106 [ + + ]: 12418 : for (unsigned pos1 = chunk_start; pos1 <= chunk_end; ++pos1) {
1107 : 8528 : auto tx1 = linearization[pos1];
1108 [ + + ]: 55144 : for (unsigned pos2 = pos1 + 1; pos2 <= chunk_end; ++pos2) {
1109 [ + + ]: 46616 : auto tx2 = linearization[pos2];
1110 : : // Check whether tx2 only depends on transactions that precede tx1.
1111 [ + + ]: 46616 : if ((depgraph.Ancestors(tx2) - done).Count() == 1) {
1112 : : // tx2 could take position pos1.
1113 : : // Verify that individual transaction feerate is decreasing (tie-breaking by
1114 : : // size).
1115 [ - + ]: 15716 : assert(ByRatioNegSize{depgraph.FeeRate(tx1)} >= ByRatioNegSize{depgraph.FeeRate(tx2)});
1116 : : // If feerate and size are equal, compare by DepGraphIndex.
1117 [ + + ]: 52759 : if (depgraph.FeeRate(tx1) == depgraph.FeeRate(tx2)) {
1118 [ - + ]: 4465 : assert(tx1 < tx2);
1119 : : }
1120 : : }
1121 : : }
1122 : 8528 : done.Set(tx1);
1123 : : }
1124 : 3890 : pos += chunk.transactions.Count();
1125 : : }
1126 : :
1127 : : // Verify that chunks themselves are in a valid order. For any pair of chunks, it should
1128 : : // not be possible to swap them; either due to a missing dependency, or because the order
1129 : : // would be inconsistent with decreasing chunk feerate, increasing chunk size, and order
1130 : : // of maximum fallback-ordered element (just maximum DepGraphIndex element here).
1131 : 345 : done = {};
1132 : : // Go over all pairs of chunks. done is the set of transactions seen before chunk_num1.
1133 [ - + + + ]: 4235 : for (unsigned chunk_num1 = 0; chunk_num1 < chunking_info.size(); ++chunk_num1) {
1134 : 3890 : const auto& chunk1 = chunking_info[chunk_num1];
1135 [ - + + + ]: 44519 : for (unsigned chunk_num2 = chunk_num1 + 1; chunk_num2 < chunking_info.size(); ++chunk_num2) {
1136 [ + - ]: 40629 : const auto& chunk2 = chunking_info[chunk_num2];
1137 : 40629 : TestBitSet chunk2_ancestors;
1138 [ + - + + ]: 132247 : for (auto tx : chunk2.transactions) chunk2_ancestors |= depgraph.Ancestors(tx);
1139 : : // Check whether chunk2 only depends on transactions that precede chunk1.
1140 [ + + ]: 40629 : if ((chunk2_ancestors - done).IsSubsetOf(chunk2.transactions)) {
1141 : : // chunk2 could take position chunk_num1.
1142 : : // Verify that chunk feerate is decreasing (tie-breaking by size).
1143 [ - + ]: 22242 : assert(ByRatioNegSize{chunk1.feerate} >= ByRatioNegSize{chunk2.feerate});
1144 : : // If feerate and size are equal, compare by maximum DepGraphIndex element.
1145 [ + + ]: 51849 : if (chunk1.feerate == chunk2.feerate) {
1146 [ - + ]: 9547 : assert(chunk1.transactions.Last() < chunk2.transactions.Last());
1147 : : }
1148 : : }
1149 : : }
1150 : 3890 : done |= chunk1.transactions;
1151 : : }
1152 : :
1153 : : // Redo from scratch with a different rng_seed. The resulting linearization should be
1154 : : // deterministic, if both are optimal.
1155 [ - + ]: 345 : auto [linearization2, optimal2, cost2] = Linearize(depgraph, MaxOptimalLinearizationCost(depgraph.TxCount()) + 1, rng_seed ^ 0x1337, IndexTxOrder{});
1156 [ - + ]: 345 : assert(optimal2);
1157 [ - + ]: 345 : assert(linearization2 == linearization);
1158 : 345 : }
1159 : 458 : }
1160 : :
1161 [ + - ]: 585 : FUZZ_TARGET(clusterlin_postlinearize)
1162 : : {
1163 : : // Verify expected properties of PostLinearize() on arbitrary linearizations.
1164 : :
1165 : : // Retrieve a depgraph from the fuzz input.
1166 : 109 : SpanReader reader(buffer);
1167 : 109 : DepGraph<TestBitSet> depgraph;
1168 : 109 : try {
1169 [ + - ]: 109 : reader >> Using<DepGraphFormatter>(depgraph);
1170 [ - - ]: 0 : } catch (const std::ios_base::failure&) {}
1171 : :
1172 : : // Retrieve a linearization from the fuzz input.
1173 : 109 : std::vector<DepGraphIndex> linearization;
1174 [ + - ]: 218 : linearization = ReadLinearization(depgraph, reader);
1175 [ - + ]: 109 : SanityCheck(depgraph, linearization);
1176 : :
1177 : : // Produce a post-processed version.
1178 [ + - ]: 109 : auto post_linearization = linearization;
1179 [ - + + - ]: 109 : PostLinearize(depgraph, post_linearization);
1180 [ - + ]: 109 : SanityCheck(depgraph, post_linearization);
1181 : :
1182 : : // Compare diagrams: post-linearization cannot worsen anywhere.
1183 [ - + ]: 109 : auto chunking = ChunkLinearization(depgraph, linearization);
1184 [ - + ]: 109 : auto post_chunking = ChunkLinearization(depgraph, post_linearization);
1185 [ - + - + : 109 : auto cmp = CompareChunks(post_chunking, chunking);
+ - ]
1186 [ - + ]: 109 : assert(cmp >= 0);
1187 : :
1188 : : // Run again, things can keep improving (and never get worse)
1189 [ + - ]: 109 : auto post_post_linearization = post_linearization;
1190 [ - + + - ]: 109 : PostLinearize(depgraph, post_post_linearization);
1191 [ - + ]: 109 : SanityCheck(depgraph, post_post_linearization);
1192 [ - + ]: 109 : auto post_post_chunking = ChunkLinearization(depgraph, post_post_linearization);
1193 [ - + - + : 109 : cmp = CompareChunks(post_post_chunking, post_chunking);
+ - ]
1194 [ - + ]: 109 : assert(cmp >= 0);
1195 : :
1196 : : // The chunks that come out of postlinearizing are always connected.
1197 [ - + ]: 109 : auto linchunking = ChunkLinearizationInfo(depgraph, post_linearization);
1198 [ + + ]: 961 : for (const auto& [chunk_set, _chunk_feerate] : linchunking) {
1199 [ - + ]: 852 : assert(depgraph.IsConnected(chunk_set));
1200 : : }
1201 : 109 : }
1202 : :
1203 [ + - ]: 770 : FUZZ_TARGET(clusterlin_postlinearize_tree)
1204 : : {
1205 : : // Verify expected properties of PostLinearize() on linearizations of graphs that form either
1206 : : // an upright or reverse tree structure.
1207 : :
1208 : : // Construct a direction, RNG seed, and an arbitrary graph from the fuzz input.
1209 : 294 : SpanReader reader(buffer);
1210 : 294 : uint64_t rng_seed{0};
1211 : 294 : DepGraph<TestBitSet> depgraph_gen;
1212 : 294 : uint8_t direction{0};
1213 : 294 : try {
1214 [ + - + + : 294 : reader >> direction >> rng_seed >> Using<DepGraphFormatter>(depgraph_gen);
+ - ]
1215 [ - + ]: 2 : } catch (const std::ios_base::failure&) {}
1216 : :
1217 : 294 : auto depgraph_tree = BuildTreeGraph(depgraph_gen, direction);
1218 : :
1219 : : // Retrieve a linearization from the fuzz input.
1220 : 294 : std::vector<DepGraphIndex> linearization;
1221 [ + - ]: 588 : linearization = ReadLinearization(depgraph_tree, reader);
1222 [ - + ]: 294 : SanityCheck(depgraph_tree, linearization);
1223 : :
1224 : : // Produce a postlinearized version.
1225 [ + - ]: 294 : auto post_linearization = linearization;
1226 [ - + + - ]: 294 : PostLinearize(depgraph_tree, post_linearization);
1227 [ - + ]: 294 : SanityCheck(depgraph_tree, post_linearization);
1228 : :
1229 : : // Compare diagrams.
1230 [ - + ]: 294 : auto chunking = ChunkLinearization(depgraph_tree, linearization);
1231 [ - + ]: 294 : auto post_chunking = ChunkLinearization(depgraph_tree, post_linearization);
1232 [ - + - + : 294 : auto cmp = CompareChunks(post_chunking, chunking);
+ - ]
1233 [ - + ]: 294 : assert(cmp >= 0);
1234 : :
1235 : : // Verify that post-linearizing again does not change the diagram. The result must be identical
1236 : : // as post_linearization ought to be optimal already with a tree-structured graph.
1237 [ + - ]: 294 : auto post_post_linearization = post_linearization;
1238 [ - + + - ]: 294 : PostLinearize(depgraph_tree, post_post_linearization);
1239 [ - + ]: 294 : SanityCheck(depgraph_tree, post_post_linearization);
1240 [ - + ]: 294 : auto post_post_chunking = ChunkLinearization(depgraph_tree, post_post_linearization);
1241 [ - + - + : 294 : auto cmp_post = CompareChunks(post_post_chunking, post_chunking);
+ - ]
1242 [ - + ]: 294 : assert(cmp_post == 0);
1243 : :
1244 : : // Try to find an even better linearization directly. This must not change the diagram for the
1245 : : // same reason.
1246 [ - + - + ]: 294 : auto [opt_linearization, _optimal, _cost] = Linearize(depgraph_tree, 1000000, rng_seed, IndexTxOrder{}, post_linearization);
1247 [ - + ]: 294 : auto opt_chunking = ChunkLinearization(depgraph_tree, opt_linearization);
1248 [ - + - + : 294 : auto cmp_opt = CompareChunks(opt_chunking, post_chunking);
+ - ]
1249 [ - + ]: 294 : assert(cmp_opt == 0);
1250 : 294 : }
1251 : :
1252 [ + - ]: 598 : FUZZ_TARGET(clusterlin_postlinearize_moved_leaf)
1253 : : {
1254 : : // Verify that taking an existing linearization, and moving a leaf to the back, potentially
1255 : : // increasing its fee, and then post-linearizing, results in something as good as the
1256 : : // original. This guarantees that in an RBF that replaces a transaction with one of the same
1257 : : // size but higher fee, applying the "remove conflicts, append new transaction, postlinearize"
1258 : : // process will never worsen linearization quality.
1259 : :
1260 : : // Construct an arbitrary graph and a fee from the fuzz input.
1261 : 122 : SpanReader reader(buffer);
1262 : 122 : DepGraph<TestBitSet> depgraph;
1263 : 122 : int32_t fee_inc{0};
1264 : 122 : try {
1265 : 122 : uint64_t fee_inc_code;
1266 [ + - + + ]: 122 : reader >> Using<DepGraphFormatter>(depgraph) >> VARINT(fee_inc_code);
1267 : 42 : fee_inc = fee_inc_code & 0x3ffff;
1268 [ - + ]: 80 : } catch (const std::ios_base::failure&) {}
1269 [ + + ]: 122 : if (depgraph.TxCount() == 0) return;
1270 : :
1271 : : // Retrieve two linearizations from the fuzz input.
1272 [ + - ]: 112 : auto lin = ReadLinearization(depgraph, reader);
1273 [ + - ]: 112 : auto lin_leaf = ReadLinearization(depgraph, reader);
1274 : :
1275 : : // Construct a linearization identical to lin, but with the tail end of lin_leaf moved to the
1276 : : // back.
1277 : 112 : std::vector<DepGraphIndex> lin_moved;
1278 [ + + ]: 1389 : for (auto i : lin) {
1279 [ + + + - ]: 1277 : if (i != lin_leaf.back()) lin_moved.push_back(i);
1280 : : }
1281 [ + - ]: 112 : lin_moved.push_back(lin_leaf.back());
1282 : :
1283 : : // Postlinearize lin_moved.
1284 [ - + + - ]: 112 : PostLinearize(depgraph, lin_moved);
1285 [ - + ]: 112 : SanityCheck(depgraph, lin_moved);
1286 : :
1287 : : // Compare diagrams (applying the fee delta after computing the old one).
1288 [ - + ]: 112 : auto old_chunking = ChunkLinearization(depgraph, lin);
1289 [ - + ]: 112 : depgraph.FeeRate(lin_leaf.back()).fee += fee_inc;
1290 [ - + ]: 112 : auto new_chunking = ChunkLinearization(depgraph, lin_moved);
1291 [ - + - + : 112 : auto cmp = CompareChunks(new_chunking, old_chunking);
+ - ]
1292 [ - + ]: 112 : assert(cmp >= 0);
1293 : 122 : }
|