/root/bitcoin/src/cluster_linearize.h
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright (c) The Bitcoin Core developers |
2 | | // Distributed under the MIT software license, see the accompanying |
3 | | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
4 | | |
5 | | #ifndef BITCOIN_CLUSTER_LINEARIZE_H |
6 | | #define BITCOIN_CLUSTER_LINEARIZE_H |
7 | | |
8 | | #include <algorithm> |
9 | | #include <numeric> |
10 | | #include <optional> |
11 | | #include <stdint.h> |
12 | | #include <vector> |
13 | | #include <utility> |
14 | | |
15 | | #include <random.h> |
16 | | #include <span.h> |
17 | | #include <util/feefrac.h> |
18 | | #include <util/vecdeque.h> |
19 | | |
20 | | namespace cluster_linearize { |
21 | | |
22 | | /** Data type to represent cluster input. |
23 | | * |
24 | | * cluster[i].first is tx_i's fee and size. |
25 | | * cluster[i].second[j] is true iff tx_i spends one or more of tx_j's outputs. |
26 | | */ |
27 | | template<typename SetType> |
28 | | using Cluster = std::vector<std::pair<FeeFrac, SetType>>; |
29 | | |
30 | | /** Data type to represent transaction indices in clusters. */ |
31 | | using ClusterIndex = uint32_t; |
32 | | |
33 | | /** Data structure that holds a transaction graph's preprocessed data (fee, size, ancestors, |
34 | | * descendants). */ |
35 | | template<typename SetType> |
36 | | class DepGraph |
37 | | { |
38 | | /** Information about a single transaction. */ |
39 | | struct Entry |
40 | | { |
41 | | /** Fee and size of transaction itself. */ |
42 | | FeeFrac feerate; |
43 | | /** All ancestors of the transaction (including itself). */ |
44 | | SetType ancestors; |
45 | | /** All descendants of the transaction (including itself). */ |
46 | | SetType descendants; |
47 | | |
48 | | /** Equality operator (primarily for for testing purposes). */ |
49 | 0 | friend bool operator==(const Entry&, const Entry&) noexcept = default; |
50 | | |
51 | | /** Construct an empty entry. */ |
52 | 0 | Entry() noexcept = default; |
53 | | /** Construct an entry with a given feerate, ancestor set, descendant set. */ |
54 | 0 | Entry(const FeeFrac& f, const SetType& a, const SetType& d) noexcept : feerate(f), ancestors(a), descendants(d) {} |
55 | | }; |
56 | | |
57 | | /** Data for each transaction, in the same order as the Cluster it was constructed from. */ |
58 | | std::vector<Entry> entries; |
59 | | |
60 | | public: |
61 | | /** Equality operator (primarily for testing purposes). */ |
62 | 0 | friend bool operator==(const DepGraph&, const DepGraph&) noexcept = default; |
63 | | |
64 | | // Default constructors. |
65 | 0 | DepGraph() noexcept = default; |
66 | | DepGraph(const DepGraph&) noexcept = default; |
67 | | DepGraph(DepGraph&&) noexcept = default; |
68 | | DepGraph& operator=(const DepGraph&) noexcept = default; |
69 | 0 | DepGraph& operator=(DepGraph&&) noexcept = default; |
70 | | |
71 | | /** Construct a DepGraph object for ntx transactions, with no dependencies. |
72 | | * |
73 | | * Complexity: O(N) where N=ntx. |
74 | | **/ |
75 | | explicit DepGraph(ClusterIndex ntx) noexcept |
76 | | { |
77 | | Assume(ntx <= SetType::Size()); |
78 | | entries.resize(ntx); |
79 | | for (ClusterIndex i = 0; i < ntx; ++i) { |
80 | | entries[i].ancestors = SetType::Singleton(i); |
81 | | entries[i].descendants = SetType::Singleton(i); |
82 | | } |
83 | | } |
84 | | |
85 | | /** Construct a DepGraph object given a cluster. |
86 | | * |
87 | | * Complexity: O(N^2) where N=cluster.size(). |
88 | | */ |
89 | 0 | explicit DepGraph(const Cluster<SetType>& cluster) noexcept : entries(cluster.size()) |
90 | 0 | { |
91 | 0 | for (ClusterIndex i = 0; i < cluster.size(); ++i) { |
92 | | // Fill in fee and size. |
93 | 0 | entries[i].feerate = cluster[i].first; |
94 | | // Fill in direct parents as ancestors. |
95 | 0 | entries[i].ancestors = cluster[i].second; |
96 | | // Make sure transactions are ancestors of themselves. |
97 | 0 | entries[i].ancestors.Set(i); |
98 | 0 | } |
99 | | |
100 | | // Propagate ancestor information. |
101 | 0 | for (ClusterIndex i = 0; i < entries.size(); ++i) { |
102 | | // At this point, entries[a].ancestors[b] is true iff b is an ancestor of a and there |
103 | | // is a path from a to b through the subgraph consisting of {a, b} union |
104 | | // {0, 1, ..., (i-1)}. |
105 | 0 | SetType to_merge = entries[i].ancestors; |
106 | 0 | for (ClusterIndex j = 0; j < entries.size(); ++j) { |
107 | 0 | if (entries[j].ancestors[i]) { |
108 | 0 | entries[j].ancestors |= to_merge; |
109 | 0 | } |
110 | 0 | } |
111 | 0 | } |
112 | | |
113 | | // Fill in descendant information by transposing the ancestor information. |
114 | 0 | for (ClusterIndex i = 0; i < entries.size(); ++i) { |
115 | 0 | for (auto j : entries[i].ancestors) { |
116 | 0 | entries[j].descendants.Set(i); |
117 | 0 | } |
118 | 0 | } |
119 | 0 | } |
120 | | |
121 | | /** Construct a DepGraph object given another DepGraph and a mapping from old to new. |
122 | | * |
123 | | * Complexity: O(N^2) where N=depgraph.TxCount(). |
124 | | */ |
125 | 0 | DepGraph(const DepGraph<SetType>& depgraph, Span<const ClusterIndex> mapping) noexcept : entries(depgraph.TxCount()) |
126 | 0 | { |
127 | 0 | Assert(mapping.size() == depgraph.TxCount()); |
128 | | // Fill in fee, size, ancestors. |
129 | 0 | for (ClusterIndex i = 0; i < depgraph.TxCount(); ++i) { |
130 | 0 | const auto& input = depgraph.entries[i]; |
131 | 0 | auto& output = entries[mapping[i]]; |
132 | 0 | output.feerate = input.feerate; |
133 | 0 | for (auto j : input.ancestors) output.ancestors.Set(mapping[j]); |
134 | 0 | } |
135 | | // Fill in descendant information. |
136 | 0 | for (ClusterIndex i = 0; i < entries.size(); ++i) { |
137 | 0 | for (auto j : entries[i].ancestors) { |
138 | 0 | entries[j].descendants.Set(i); |
139 | 0 | } |
140 | 0 | } |
141 | 0 | } |
142 | | |
143 | | /** Get the number of transactions in the graph. Complexity: O(1). */ |
144 | 0 | auto TxCount() const noexcept { return entries.size(); } |
145 | | /** Get the feerate of a given transaction i. Complexity: O(1). */ |
146 | 0 | const FeeFrac& FeeRate(ClusterIndex i) const noexcept { return entries[i].feerate; } |
147 | | /** Get the mutable feerate of a given transaction i. Complexity: O(1). */ |
148 | 0 | FeeFrac& FeeRate(ClusterIndex i) noexcept { return entries[i].feerate; } |
149 | | /** Get the ancestors of a given transaction i. Complexity: O(1). */ |
150 | 0 | const SetType& Ancestors(ClusterIndex i) const noexcept { return entries[i].ancestors; } |
151 | | /** Get the descendants of a given transaction i. Complexity: O(1). */ |
152 | 0 | const SetType& Descendants(ClusterIndex i) const noexcept { return entries[i].descendants; } |
153 | | |
154 | | /** Add a new unconnected transaction to this transaction graph (at the end), and return its |
155 | | * ClusterIndex. |
156 | | * |
157 | | * Complexity: O(1) (amortized, due to resizing of backing vector). |
158 | | */ |
159 | | ClusterIndex AddTransaction(const FeeFrac& feefrac) noexcept |
160 | 0 | { |
161 | 0 | Assume(TxCount() < SetType::Size()); |
162 | 0 | ClusterIndex new_idx = TxCount(); |
163 | 0 | entries.emplace_back(feefrac, SetType::Singleton(new_idx), SetType::Singleton(new_idx)); |
164 | 0 | return new_idx; |
165 | 0 | } |
166 | | |
167 | | /** Modify this transaction graph, adding a dependency between a specified parent and child. |
168 | | * |
169 | | * Complexity: O(N) where N=TxCount(). |
170 | | **/ |
171 | | void AddDependency(ClusterIndex parent, ClusterIndex child) noexcept |
172 | 0 | { |
173 | | // Bail out if dependency is already implied. |
174 | 0 | if (entries[child].ancestors[parent]) return; |
175 | | // To each ancestor of the parent, add as descendants the descendants of the child. |
176 | 0 | const auto& chl_des = entries[child].descendants; |
177 | 0 | for (auto anc_of_par : Ancestors(parent)) { |
178 | 0 | entries[anc_of_par].descendants |= chl_des; |
179 | 0 | } |
180 | | // To each descendant of the child, add as ancestors the ancestors of the parent. |
181 | 0 | const auto& par_anc = entries[parent].ancestors; |
182 | 0 | for (auto dec_of_chl : Descendants(child)) { |
183 | 0 | entries[dec_of_chl].ancestors |= par_anc; |
184 | 0 | } |
185 | 0 | } |
186 | | |
187 | | /** Compute the aggregate feerate of a set of nodes in this graph. |
188 | | * |
189 | | * Complexity: O(N) where N=elems.Count(). |
190 | | **/ |
191 | | FeeFrac FeeRate(const SetType& elems) const noexcept |
192 | 0 | { |
193 | 0 | FeeFrac ret; |
194 | 0 | for (auto pos : elems) ret += entries[pos].feerate; |
195 | 0 | return ret; |
196 | 0 | } |
197 | | |
198 | | /** Find some connected component within the subset "todo" of this graph. |
199 | | * |
200 | | * Specifically, this finds the connected component which contains the first transaction of |
201 | | * todo (if any). |
202 | | * |
203 | | * Two transactions are considered connected if they are both in `todo`, and one is an ancestor |
204 | | * of the other in the entire graph (so not just within `todo`), or transitively there is a |
205 | | * path of transactions connecting them. This does mean that if `todo` contains a transaction |
206 | | * and a grandparent, but misses the parent, they will still be part of the same component. |
207 | | * |
208 | | * Complexity: O(ret.Count()). |
209 | | */ |
210 | | SetType FindConnectedComponent(const SetType& todo) const noexcept |
211 | 0 | { |
212 | 0 | if (todo.None()) return todo; |
213 | 0 | auto to_add = SetType::Singleton(todo.First()); |
214 | 0 | SetType ret; |
215 | 0 | do { |
216 | 0 | SetType old = ret; |
217 | 0 | for (auto add : to_add) { |
218 | 0 | ret |= Descendants(add); |
219 | 0 | ret |= Ancestors(add); |
220 | 0 | } |
221 | 0 | ret &= todo; |
222 | 0 | to_add = ret - old; |
223 | 0 | } while (to_add.Any()); |
224 | 0 | return ret; |
225 | 0 | } |
226 | | |
227 | | /** Determine if a subset is connected. |
228 | | * |
229 | | * Complexity: O(subset.Count()). |
230 | | */ |
231 | | bool IsConnected(const SetType& subset) const noexcept |
232 | 0 | { |
233 | 0 | return FindConnectedComponent(subset) == subset; |
234 | 0 | } |
235 | | |
236 | | /** Determine if this entire graph is connected. |
237 | | * |
238 | | * Complexity: O(TxCount()). |
239 | | */ |
240 | 0 | bool IsConnected() const noexcept { return IsConnected(SetType::Fill(TxCount())); } |
241 | | |
242 | | /** Append the entries of select to list in a topologically valid order. |
243 | | * |
244 | | * Complexity: O(select.Count() * log(select.Count())). |
245 | | */ |
246 | | void AppendTopo(std::vector<ClusterIndex>& list, const SetType& select) const noexcept |
247 | 0 | { |
248 | 0 | ClusterIndex old_len = list.size(); |
249 | 0 | for (auto i : select) list.push_back(i); |
250 | 0 | std::sort(list.begin() + old_len, list.end(), [&](ClusterIndex a, ClusterIndex b) noexcept { |
251 | 0 | const auto a_anc_count = entries[a].ancestors.Count(); |
252 | 0 | const auto b_anc_count = entries[b].ancestors.Count(); |
253 | 0 | if (a_anc_count != b_anc_count) return a_anc_count < b_anc_count; |
254 | 0 | return a < b; |
255 | 0 | }); |
256 | 0 | } |
257 | | }; |
258 | | |
259 | | /** A set of transactions together with their aggregate feerate. */ |
260 | | template<typename SetType> |
261 | | struct SetInfo |
262 | | { |
263 | | /** The transactions in the set. */ |
264 | | SetType transactions; |
265 | | /** Their combined fee and size. */ |
266 | | FeeFrac feerate; |
267 | | |
268 | | /** Construct a SetInfo for the empty set. */ |
269 | 0 | SetInfo() noexcept = default; |
270 | | |
271 | | /** Construct a SetInfo for a specified set and feerate. */ |
272 | 0 | SetInfo(const SetType& txn, const FeeFrac& fr) noexcept : transactions(txn), feerate(fr) {} |
273 | | |
274 | | /** Construct a SetInfo for a given transaction in a depgraph. */ |
275 | | explicit SetInfo(const DepGraph<SetType>& depgraph, ClusterIndex pos) noexcept : |
276 | 0 | transactions(SetType::Singleton(pos)), feerate(depgraph.FeeRate(pos)) {} |
277 | | |
278 | | /** Construct a SetInfo for a set of transactions in a depgraph. */ |
279 | | explicit SetInfo(const DepGraph<SetType>& depgraph, const SetType& txn) noexcept : |
280 | 0 | transactions(txn), feerate(depgraph.FeeRate(txn)) {} |
281 | | |
282 | | /** Add a transaction to this SetInfo (which must not yet be in it). */ |
283 | | void Set(const DepGraph<SetType>& depgraph, ClusterIndex pos) noexcept |
284 | 0 | { |
285 | 0 | Assume(!transactions[pos]); |
286 | 0 | transactions.Set(pos); |
287 | 0 | feerate += depgraph.FeeRate(pos); |
288 | 0 | } |
289 | | |
290 | | /** Add the transactions of other to this SetInfo (no overlap allowed). */ |
291 | | SetInfo& operator|=(const SetInfo& other) noexcept |
292 | 0 | { |
293 | 0 | Assume(!transactions.Overlaps(other.transactions)); |
294 | 0 | transactions |= other.transactions; |
295 | 0 | feerate += other.feerate; |
296 | 0 | return *this; |
297 | 0 | } |
298 | | |
299 | | /** Construct a new SetInfo equal to this, with more transactions added (which may overlap |
300 | | * with the existing transactions in the SetInfo). */ |
301 | | [[nodiscard]] SetInfo Add(const DepGraph<SetType>& depgraph, const SetType& txn) const noexcept |
302 | 0 | { |
303 | 0 | return {transactions | txn, feerate + depgraph.FeeRate(txn - transactions)}; |
304 | 0 | } |
305 | | |
306 | | /** Swap two SetInfo objects. */ |
307 | | friend void swap(SetInfo& a, SetInfo& b) noexcept |
308 | 0 | { |
309 | 0 | swap(a.transactions, b.transactions); |
310 | 0 | swap(a.feerate, b.feerate); |
311 | 0 | } |
312 | | |
313 | | /** Permit equality testing. */ |
314 | 0 | friend bool operator==(const SetInfo&, const SetInfo&) noexcept = default; |
315 | | }; |
316 | | |
317 | | /** Compute the feerates of the chunks of linearization. */ |
318 | | template<typename SetType> |
319 | | std::vector<FeeFrac> ChunkLinearization(const DepGraph<SetType>& depgraph, Span<const ClusterIndex> linearization) noexcept |
320 | 0 | { |
321 | 0 | std::vector<FeeFrac> ret; |
322 | 0 | for (ClusterIndex i : linearization) { |
323 | | /** The new chunk to be added, initially a singleton. */ |
324 | 0 | auto new_chunk = depgraph.FeeRate(i); |
325 | | // As long as the new chunk has a higher feerate than the last chunk so far, absorb it. |
326 | 0 | while (!ret.empty() && new_chunk >> ret.back()) { |
327 | 0 | new_chunk += ret.back(); |
328 | 0 | ret.pop_back(); |
329 | 0 | } |
330 | | // Actually move that new chunk into the chunking. |
331 | 0 | ret.push_back(std::move(new_chunk)); |
332 | 0 | } |
333 | 0 | return ret; |
334 | 0 | } |
335 | | |
336 | | /** Data structure encapsulating the chunking of a linearization, permitting removal of subsets. */ |
337 | | template<typename SetType> |
338 | | class LinearizationChunking |
339 | | { |
340 | | /** The depgraph this linearization is for. */ |
341 | | const DepGraph<SetType>& m_depgraph; |
342 | | |
343 | | /** The linearization we started from, possibly with removed prefix stripped. */ |
344 | | Span<const ClusterIndex> m_linearization; |
345 | | |
346 | | /** Chunk sets and their feerates, of what remains of the linearization. */ |
347 | | std::vector<SetInfo<SetType>> m_chunks; |
348 | | |
349 | | /** How large a prefix of m_chunks corresponds to removed transactions. */ |
350 | | ClusterIndex m_chunks_skip{0}; |
351 | | |
352 | | /** Which transactions remain in the linearization. */ |
353 | | SetType m_todo; |
354 | | |
355 | | /** Fill the m_chunks variable, and remove the done prefix of m_linearization. */ |
356 | | void BuildChunks() noexcept |
357 | 0 | { |
358 | | // Caller must clear m_chunks. |
359 | 0 | Assume(m_chunks.empty()); |
360 | | |
361 | | // Chop off the initial part of m_linearization that is already done. |
362 | 0 | while (!m_linearization.empty() && !m_todo[m_linearization.front()]) { |
363 | 0 | m_linearization = m_linearization.subspan(1); |
364 | 0 | } |
365 | | |
366 | | // Iterate over the remaining entries in m_linearization. This is effectively the same |
367 | | // algorithm as ChunkLinearization, but supports skipping parts of the linearization and |
368 | | // keeps track of the sets themselves instead of just their feerates. |
369 | 0 | for (auto idx : m_linearization) { |
370 | 0 | if (!m_todo[idx]) continue; |
371 | | // Start with an initial chunk containing just element idx. |
372 | 0 | SetInfo add(m_depgraph, idx); |
373 | | // Absorb existing final chunks into add while they have lower feerate. |
374 | 0 | while (!m_chunks.empty() && add.feerate >> m_chunks.back().feerate) { |
375 | 0 | add |= m_chunks.back(); |
376 | 0 | m_chunks.pop_back(); |
377 | 0 | } |
378 | | // Remember new chunk. |
379 | 0 | m_chunks.push_back(std::move(add)); |
380 | 0 | } |
381 | 0 | } |
382 | | |
383 | | public: |
384 | | /** Initialize a LinearizationSubset object for a given length of linearization. */ |
385 | | explicit LinearizationChunking(const DepGraph<SetType>& depgraph LIFETIMEBOUND, Span<const ClusterIndex> lin LIFETIMEBOUND) noexcept : |
386 | 0 | m_depgraph(depgraph), m_linearization(lin) |
387 | 0 | { |
388 | | // Mark everything in lin as todo still. |
389 | 0 | for (auto i : m_linearization) m_todo.Set(i); |
390 | | // Compute the initial chunking. |
391 | 0 | m_chunks.reserve(depgraph.TxCount()); |
392 | 0 | BuildChunks(); |
393 | 0 | } |
394 | | |
395 | | /** Determine how many chunks remain in the linearization. */ |
396 | 0 | ClusterIndex NumChunksLeft() const noexcept { return m_chunks.size() - m_chunks_skip; } |
397 | | |
398 | | /** Access a chunk. Chunk 0 is the highest-feerate prefix of what remains. */ |
399 | | const SetInfo<SetType>& GetChunk(ClusterIndex n) const noexcept |
400 | 0 | { |
401 | 0 | Assume(n + m_chunks_skip < m_chunks.size()); |
402 | 0 | return m_chunks[n + m_chunks_skip]; |
403 | 0 | } |
404 | | |
405 | | /** Remove some subset of transactions from the linearization. */ |
406 | | void MarkDone(SetType subset) noexcept |
407 | 0 | { |
408 | 0 | Assume(subset.Any()); |
409 | 0 | Assume(subset.IsSubsetOf(m_todo)); |
410 | 0 | m_todo -= subset; |
411 | 0 | if (GetChunk(0).transactions == subset) { |
412 | | // If the newly done transactions exactly match the first chunk of the remainder of |
413 | | // the linearization, we do not need to rechunk; just remember to skip one |
414 | | // additional chunk. |
415 | 0 | ++m_chunks_skip; |
416 | | // With subset marked done, some prefix of m_linearization will be done now. How long |
417 | | // that prefix is depends on how many done elements were interspersed with subset, |
418 | | // but at least as many transactions as there are in subset. |
419 | 0 | m_linearization = m_linearization.subspan(subset.Count()); |
420 | 0 | } else { |
421 | | // Otherwise rechunk what remains of m_linearization. |
422 | 0 | m_chunks.clear(); |
423 | 0 | m_chunks_skip = 0; |
424 | 0 | BuildChunks(); |
425 | 0 | } |
426 | 0 | } |
427 | | |
428 | | /** Find the shortest intersection between subset and the prefixes of remaining chunks |
429 | | * of the linearization that has a feerate not below subset's. |
430 | | * |
431 | | * This is a crucial operation in guaranteeing improvements to linearizations. If subset has |
432 | | * a feerate not below GetChunk(0)'s, then moving IntersectPrefixes(subset) to the front of |
433 | | * (what remains of) the linearization is guaranteed not to make it worse at any point. |
434 | | * |
435 | | * See https://delvingbitcoin.org/t/introduction-to-cluster-linearization/1032 for background. |
436 | | */ |
437 | | SetInfo<SetType> IntersectPrefixes(const SetInfo<SetType>& subset) const noexcept |
438 | 0 | { |
439 | 0 | Assume(subset.transactions.IsSubsetOf(m_todo)); |
440 | 0 | SetInfo<SetType> accumulator; |
441 | | // Iterate over all chunks of the remaining linearization. |
442 | 0 | for (ClusterIndex i = 0; i < NumChunksLeft(); ++i) { |
443 | | // Find what (if any) intersection the chunk has with subset. |
444 | 0 | const SetType to_add = GetChunk(i).transactions & subset.transactions; |
445 | 0 | if (to_add.Any()) { |
446 | | // If adding that to accumulator makes us hit all of subset, we are done as no |
447 | | // shorter intersection with higher/equal feerate exists. |
448 | 0 | accumulator.transactions |= to_add; |
449 | 0 | if (accumulator.transactions == subset.transactions) break; |
450 | | // Otherwise update the accumulator feerate. |
451 | 0 | accumulator.feerate += m_depgraph.FeeRate(to_add); |
452 | | // If that does result in something better, or something with the same feerate but |
453 | | // smaller, return that. Even if a longer, higher-feerate intersection exists, it |
454 | | // does not hurt to return the shorter one (the remainder of the longer intersection |
455 | | // will generally be found in the next call to Intersect, but even if not, it is not |
456 | | // required for the improvement guarantee this function makes). |
457 | 0 | if (!(accumulator.feerate << subset.feerate)) return accumulator; |
458 | 0 | } |
459 | 0 | } |
460 | 0 | return subset; |
461 | 0 | } |
462 | | }; |
463 | | |
464 | | /** Class encapsulating the state needed to find the best remaining ancestor set. |
465 | | * |
466 | | * It is initialized for an entire DepGraph, and parts of the graph can be dropped by calling |
467 | | * MarkDone. |
468 | | * |
469 | | * As long as any part of the graph remains, FindCandidateSet() can be called which will return a |
470 | | * SetInfo with the highest-feerate ancestor set that remains (an ancestor set is a single |
471 | | * transaction together with all its remaining ancestors). |
472 | | */ |
473 | | template<typename SetType> |
474 | | class AncestorCandidateFinder |
475 | | { |
476 | | /** Internal dependency graph. */ |
477 | | const DepGraph<SetType>& m_depgraph; |
478 | | /** Which transaction are left to include. */ |
479 | | SetType m_todo; |
480 | | /** Precomputed ancestor-set feerates (only kept up-to-date for indices in m_todo). */ |
481 | | std::vector<FeeFrac> m_ancestor_set_feerates; |
482 | | |
483 | | public: |
484 | | /** Construct an AncestorCandidateFinder for a given cluster. |
485 | | * |
486 | | * Complexity: O(N^2) where N=depgraph.TxCount(). |
487 | | */ |
488 | | AncestorCandidateFinder(const DepGraph<SetType>& depgraph LIFETIMEBOUND) noexcept : |
489 | 0 | m_depgraph(depgraph), |
490 | 0 | m_todo{SetType::Fill(depgraph.TxCount())}, |
491 | 0 | m_ancestor_set_feerates(depgraph.TxCount()) |
492 | 0 | { |
493 | | // Precompute ancestor-set feerates. |
494 | 0 | for (ClusterIndex i = 0; i < depgraph.TxCount(); ++i) { |
495 | | /** The remaining ancestors for transaction i. */ |
496 | 0 | SetType anc_to_add = m_depgraph.Ancestors(i); |
497 | 0 | FeeFrac anc_feerate; |
498 | | // Reuse accumulated feerate from first ancestor, if usable. |
499 | 0 | Assume(anc_to_add.Any()); |
500 | 0 | ClusterIndex first = anc_to_add.First(); |
501 | 0 | if (first < i) { |
502 | 0 | anc_feerate = m_ancestor_set_feerates[first]; |
503 | 0 | Assume(!anc_feerate.IsEmpty()); |
504 | 0 | anc_to_add -= m_depgraph.Ancestors(first); |
505 | 0 | } |
506 | | // Add in other ancestors (which necessarily include i itself). |
507 | 0 | Assume(anc_to_add[i]); |
508 | 0 | anc_feerate += m_depgraph.FeeRate(anc_to_add); |
509 | | // Store the result. |
510 | 0 | m_ancestor_set_feerates[i] = anc_feerate; |
511 | 0 | } |
512 | 0 | } |
513 | | |
514 | | /** Remove a set of transactions from the set of to-be-linearized ones. |
515 | | * |
516 | | * The same transaction may not be MarkDone()'d twice. |
517 | | * |
518 | | * Complexity: O(N*M) where N=depgraph.TxCount(), M=select.Count(). |
519 | | */ |
520 | | void MarkDone(SetType select) noexcept |
521 | 0 | { |
522 | 0 | Assume(select.Any()); |
523 | 0 | Assume(select.IsSubsetOf(m_todo)); |
524 | 0 | m_todo -= select; |
525 | 0 | for (auto i : select) { |
526 | 0 | auto feerate = m_depgraph.FeeRate(i); |
527 | 0 | for (auto j : m_depgraph.Descendants(i) & m_todo) { |
528 | 0 | m_ancestor_set_feerates[j] -= feerate; |
529 | 0 | } |
530 | 0 | } |
531 | 0 | } |
532 | | |
533 | | /** Check whether any unlinearized transactions remain. */ |
534 | | bool AllDone() const noexcept |
535 | 0 | { |
536 | 0 | return m_todo.None(); |
537 | 0 | } |
538 | | |
539 | | /** Count the number of remaining unlinearized transactions. */ |
540 | | ClusterIndex NumRemaining() const noexcept |
541 | 0 | { |
542 | 0 | return m_todo.Count(); |
543 | 0 | } |
544 | | |
545 | | /** Find the best (highest-feerate, smallest among those in case of a tie) ancestor set |
546 | | * among the remaining transactions. Requires !AllDone(). |
547 | | * |
548 | | * Complexity: O(N) where N=depgraph.TxCount(); |
549 | | */ |
550 | | SetInfo<SetType> FindCandidateSet() const noexcept |
551 | 0 | { |
552 | 0 | Assume(!AllDone()); |
553 | 0 | std::optional<ClusterIndex> best; |
554 | 0 | for (auto i : m_todo) { |
555 | 0 | if (best.has_value()) { |
556 | 0 | Assume(!m_ancestor_set_feerates[i].IsEmpty()); |
557 | 0 | if (!(m_ancestor_set_feerates[i] > m_ancestor_set_feerates[*best])) continue; |
558 | 0 | } |
559 | 0 | best = i; |
560 | 0 | } |
561 | 0 | Assume(best.has_value()); |
562 | 0 | return {m_depgraph.Ancestors(*best) & m_todo, m_ancestor_set_feerates[*best]}; |
563 | 0 | } |
564 | | }; |
565 | | |
566 | | /** Class encapsulating the state needed to perform search for good candidate sets. |
567 | | * |
568 | | * It is initialized for an entire DepGraph, and parts of the graph can be dropped by calling |
569 | | * MarkDone(). |
570 | | * |
571 | | * As long as any part of the graph remains, FindCandidateSet() can be called to perform a search |
572 | | * over the set of topologically-valid subsets of that remainder, with a limit on how many |
573 | | * combinations are tried. |
574 | | */ |
575 | | template<typename SetType> |
576 | | class SearchCandidateFinder |
577 | | { |
578 | | /** Internal RNG. */ |
579 | | InsecureRandomContext m_rng; |
580 | | /** m_sorted_to_original[i] is the original position that sorted transaction position i had. */ |
581 | | std::vector<ClusterIndex> m_sorted_to_original; |
582 | | /** m_original_to_sorted[i] is the sorted position original transaction position i has. */ |
583 | | std::vector<ClusterIndex> m_original_to_sorted; |
584 | | /** Internal dependency graph for the cluster (with transactions in decreasing individual |
585 | | * feerate order). */ |
586 | | DepGraph<SetType> m_sorted_depgraph; |
587 | | /** Which transactions are left to do (indices in m_sorted_depgraph's order). */ |
588 | | SetType m_todo; |
589 | | |
590 | | /** Given a set of transactions with sorted indices, get their original indices. */ |
591 | | SetType SortedToOriginal(const SetType& arg) const noexcept |
592 | 0 | { |
593 | 0 | SetType ret; |
594 | 0 | for (auto pos : arg) ret.Set(m_sorted_to_original[pos]); |
595 | 0 | return ret; |
596 | 0 | } |
597 | | |
598 | | /** Given a set of transactions with original indices, get their sorted indices. */ |
599 | | SetType OriginalToSorted(const SetType& arg) const noexcept |
600 | 0 | { |
601 | 0 | SetType ret; |
602 | 0 | for (auto pos : arg) ret.Set(m_original_to_sorted[pos]); |
603 | 0 | return ret; |
604 | 0 | } |
605 | | |
606 | | public: |
607 | | /** Construct a candidate finder for a graph. |
608 | | * |
609 | | * @param[in] depgraph Dependency graph for the to-be-linearized cluster. |
610 | | * @param[in] rng_seed A random seed to control the search order. |
611 | | * |
612 | | * Complexity: O(N^2) where N=depgraph.Count(). |
613 | | */ |
614 | | SearchCandidateFinder(const DepGraph<SetType>& depgraph, uint64_t rng_seed) noexcept : |
615 | 0 | m_rng(rng_seed), |
616 | 0 | m_sorted_to_original(depgraph.TxCount()), |
617 | 0 | m_original_to_sorted(depgraph.TxCount()), |
618 | 0 | m_todo(SetType::Fill(depgraph.TxCount())) |
619 | 0 | { |
620 | | // Determine reordering mapping, by sorting by decreasing feerate. |
621 | 0 | std::iota(m_sorted_to_original.begin(), m_sorted_to_original.end(), ClusterIndex{0}); |
622 | 0 | std::sort(m_sorted_to_original.begin(), m_sorted_to_original.end(), [&](auto a, auto b) { |
623 | 0 | auto feerate_cmp = depgraph.FeeRate(a) <=> depgraph.FeeRate(b); |
624 | 0 | if (feerate_cmp == 0) return a < b; |
625 | 0 | return feerate_cmp > 0; |
626 | 0 | }); |
627 | | // Compute reverse mapping. |
628 | 0 | for (ClusterIndex i = 0; i < depgraph.TxCount(); ++i) { |
629 | 0 | m_original_to_sorted[m_sorted_to_original[i]] = i; |
630 | 0 | } |
631 | | // Compute reordered dependency graph. |
632 | 0 | m_sorted_depgraph = DepGraph(depgraph, m_original_to_sorted); |
633 | 0 | } |
634 | | |
635 | | /** Check whether any unlinearized transactions remain. */ |
636 | | bool AllDone() const noexcept |
637 | 0 | { |
638 | 0 | return m_todo.None(); |
639 | 0 | } |
640 | | |
641 | | /** Find a high-feerate topologically-valid subset of what remains of the cluster. |
642 | | * Requires !AllDone(). |
643 | | * |
644 | | * @param[in] max_iterations The maximum number of optimization steps that will be performed. |
645 | | * @param[in] best A set/feerate pair with an already-known good candidate. This may |
646 | | * be empty. |
647 | | * @return A pair of: |
648 | | * - The best (highest feerate, smallest size as tiebreaker) |
649 | | * topologically valid subset (and its feerate) that was |
650 | | * encountered during search. It will be at least as good as the |
651 | | * best passed in (if not empty). |
652 | | * - The number of optimization steps that were performed. This will |
653 | | * be <= max_iterations. If strictly < max_iterations, the |
654 | | * returned subset is optimal. |
655 | | * |
656 | | * Complexity: possibly O(N * min(max_iterations, sqrt(2^N))) where N=depgraph.TxCount(). |
657 | | */ |
658 | | std::pair<SetInfo<SetType>, uint64_t> FindCandidateSet(uint64_t max_iterations, SetInfo<SetType> best) noexcept |
659 | 0 | { |
660 | 0 | Assume(!AllDone()); |
661 | | |
662 | | // Convert the provided best to internal sorted indices. |
663 | 0 | best.transactions = OriginalToSorted(best.transactions); |
664 | | |
665 | | /** Type for work queue items. */ |
666 | 0 | struct WorkItem |
667 | 0 | { |
668 | | /** Set of transactions definitely included (and its feerate). This must be a subset |
669 | | * of m_todo, and be topologically valid (includes all in-m_todo ancestors of |
670 | | * itself). */ |
671 | 0 | SetInfo<SetType> inc; |
672 | | /** Set of undecided transactions. This must be a subset of m_todo, and have no overlap |
673 | | * with inc. The set (inc | und) must be topologically valid. */ |
674 | 0 | SetType und; |
675 | | /** (Only when inc is not empty) The best feerate of any superset of inc that is also a |
676 | | * subset of (inc | und), without requiring it to be topologically valid. It forms a |
677 | | * conservative upper bound on how good a set this work item can give rise to. |
678 | | * Transactions whose feerate is below best's are ignored when determining this value, |
679 | | * which means it may technically be an underestimate, but if so, this work item |
680 | | * cannot result in something that beats best anyway. */ |
681 | 0 | FeeFrac pot_feerate; |
682 | | |
683 | | /** Construct a new work item. */ |
684 | 0 | WorkItem(SetInfo<SetType>&& i, SetType&& u, FeeFrac&& p_f) noexcept : |
685 | 0 | inc(std::move(i)), und(std::move(u)), pot_feerate(std::move(p_f)) |
686 | 0 | { |
687 | 0 | Assume(pot_feerate.IsEmpty() == inc.feerate.IsEmpty()); |
688 | 0 | } |
689 | | |
690 | | /** Swap two WorkItems. */ |
691 | 0 | void Swap(WorkItem& other) noexcept |
692 | 0 | { |
693 | 0 | swap(inc, other.inc); |
694 | 0 | swap(und, other.und); |
695 | 0 | swap(pot_feerate, other.pot_feerate); |
696 | 0 | } |
697 | 0 | }; |
698 | | |
699 | | /** The queue of work items. */ |
700 | 0 | VecDeque<WorkItem> queue; |
701 | 0 | queue.reserve(std::max<size_t>(256, 2 * m_todo.Count())); |
702 | | |
703 | | // Create initial entries per connected component of m_todo. While clusters themselves are |
704 | | // generally connected, this is not necessarily true after some parts have already been |
705 | | // removed from m_todo. Without this, effort can be wasted on searching "inc" sets that |
706 | | // span multiple components. |
707 | 0 | auto to_cover = m_todo; |
708 | 0 | do { |
709 | 0 | auto component = m_sorted_depgraph.FindConnectedComponent(to_cover); |
710 | 0 | to_cover -= component; |
711 | | // If best is not provided, set it to the first component, so that during the work |
712 | | // processing loop below, and during the add_fn/split_fn calls, we do not need to deal |
713 | | // with the best=empty case. |
714 | 0 | if (best.feerate.IsEmpty()) best = SetInfo(m_sorted_depgraph, component); |
715 | 0 | queue.emplace_back(/*inc=*/SetInfo<SetType>{}, |
716 | 0 | /*und=*/std::move(component), |
717 | 0 | /*pot_feerate=*/FeeFrac{}); |
718 | 0 | } while (to_cover.Any()); |
719 | | |
720 | | /** Local copy of the iteration limit. */ |
721 | 0 | uint64_t iterations_left = max_iterations; |
722 | | |
723 | | /** The set of transactions in m_todo which have feerate > best's. */ |
724 | 0 | SetType imp = m_todo; |
725 | 0 | while (imp.Any()) { |
726 | 0 | ClusterIndex check = imp.Last(); |
727 | 0 | if (m_sorted_depgraph.FeeRate(check) >> best.feerate) break; |
728 | 0 | imp.Reset(check); |
729 | 0 | } |
730 | | |
731 | | /** Internal function to add an item to the queue of elements to explore if there are any |
732 | | * transactions left to split on, possibly improving it before doing so, and to update |
733 | | * best/imp. |
734 | | * |
735 | | * - inc: the "inc" value for the new work item (must be topological). |
736 | | * - und: the "und" value for the new work item ((inc | und) must be topological). |
737 | | */ |
738 | 0 | auto add_fn = [&](SetInfo<SetType> inc, SetType und) noexcept { |
739 | | /** SetInfo object with the set whose feerate will become the new work item's |
740 | | * pot_feerate. It starts off equal to inc. */ |
741 | 0 | auto pot = inc; |
742 | 0 | if (!inc.feerate.IsEmpty()) { |
743 | | // Add entries to pot. We iterate over all undecided transactions whose feerate is |
744 | | // higher than best. While undecided transactions of lower feerate may improve pot, |
745 | | // the resulting pot feerate cannot possibly exceed best's (and this item will be |
746 | | // skipped in split_fn anyway). |
747 | 0 | for (auto pos : imp & und) { |
748 | | // Determine if adding transaction pos to pot (ignoring topology) would improve |
749 | | // it. If not, we're done updating pot. This relies on the fact that |
750 | | // m_sorted_depgraph, and thus the transactions iterated over, are in decreasing |
751 | | // individual feerate order. |
752 | 0 | if (!(m_sorted_depgraph.FeeRate(pos) >> pot.feerate)) break; |
753 | 0 | pot.Set(m_sorted_depgraph, pos); |
754 | 0 | } |
755 | | |
756 | | // The "jump ahead" optimization: whenever pot has a topologically-valid subset, |
757 | | // that subset can be added to inc. Any subset of (pot - inc) has the property that |
758 | | // its feerate exceeds that of any set compatible with this work item (superset of |
759 | | // inc, subset of (inc | und)). Thus, if T is a topological subset of pot, and B is |
760 | | // the best topologically-valid set compatible with this work item, and (T - B) is |
761 | | // non-empty, then (T | B) is better than B and also topological. This is in |
762 | | // contradiction with the assumption that B is best. Thus, (T - B) must be empty, |
763 | | // or T must be a subset of B. |
764 | | // |
765 | | // See https://delvingbitcoin.org/t/how-to-linearize-your-cluster/303 section 2.4. |
766 | 0 | const auto init_inc = inc.transactions; |
767 | 0 | for (auto pos : pot.transactions - inc.transactions) { |
768 | | // If the transaction's ancestors are a subset of pot, we can add it together |
769 | | // with its ancestors to inc. Just update the transactions here; the feerate |
770 | | // update happens below. |
771 | 0 | auto anc_todo = m_sorted_depgraph.Ancestors(pos) & m_todo; |
772 | 0 | if (anc_todo.IsSubsetOf(pot.transactions)) inc.transactions |= anc_todo; |
773 | 0 | } |
774 | | // Finally update und and inc's feerate to account for the added transactions. |
775 | 0 | und -= inc.transactions; |
776 | 0 | inc.feerate += m_sorted_depgraph.FeeRate(inc.transactions - init_inc); |
777 | | |
778 | | // If inc's feerate is better than best's, remember it as our new best. |
779 | 0 | if (inc.feerate > best.feerate) { |
780 | 0 | best = inc; |
781 | | // See if we can remove any entries from imp now. |
782 | 0 | while (imp.Any()) { |
783 | 0 | ClusterIndex check = imp.Last(); |
784 | 0 | if (m_sorted_depgraph.FeeRate(check) >> best.feerate) break; |
785 | 0 | imp.Reset(check); |
786 | 0 | } |
787 | 0 | } |
788 | | |
789 | | // If no potential transactions exist beyond the already included ones, no |
790 | | // improvement is possible anymore. |
791 | 0 | if (pot.feerate.size == inc.feerate.size) return; |
792 | | // At this point und must be non-empty. If it were empty then pot would equal inc. |
793 | 0 | Assume(und.Any()); |
794 | 0 | } else { |
795 | 0 | Assume(inc.transactions.None()); |
796 | | // If inc is empty, we just make sure there are undecided transactions left to |
797 | | // split on. |
798 | 0 | if (und.None()) return; |
799 | 0 | } |
800 | | |
801 | | // Actually construct a new work item on the queue. Due to the switch to DFS when queue |
802 | | // space runs out (see below), we know that no reallocation of the queue should ever |
803 | | // occur. |
804 | 0 | Assume(queue.size() < queue.capacity()); |
805 | 0 | queue.emplace_back(/*inc=*/std::move(inc), |
806 | 0 | /*und=*/std::move(und), |
807 | 0 | /*pot_feerate=*/std::move(pot.feerate)); |
808 | 0 | }; |
809 | | |
810 | | /** Internal process function. It takes an existing work item, and splits it in two: one |
811 | | * with a particular transaction (and its ancestors) included, and one with that |
812 | | * transaction (and its descendants) excluded. */ |
813 | 0 | auto split_fn = [&](WorkItem&& elem) noexcept { |
814 | | // Any queue element must have undecided transactions left, otherwise there is nothing |
815 | | // to explore anymore. |
816 | 0 | Assume(elem.und.Any()); |
817 | | // The included and undecided set are all subsets of m_todo. |
818 | 0 | Assume(elem.inc.transactions.IsSubsetOf(m_todo) && elem.und.IsSubsetOf(m_todo)); |
819 | | // Included transactions cannot be undecided. |
820 | 0 | Assume(!elem.inc.transactions.Overlaps(elem.und)); |
821 | | // If pot is empty, then so is inc. |
822 | 0 | Assume(elem.inc.feerate.IsEmpty() == elem.pot_feerate.IsEmpty()); |
823 | |
|
824 | 0 | const ClusterIndex first = elem.und.First(); |
825 | 0 | if (!elem.inc.feerate.IsEmpty()) { |
826 | | // If no undecided transactions remain with feerate higher than best, this entry |
827 | | // cannot be improved beyond best. |
828 | 0 | if (!elem.und.Overlaps(imp)) return; |
829 | | // We can ignore any queue item whose potential feerate isn't better than the best |
830 | | // seen so far. |
831 | 0 | if (elem.pot_feerate <= best.feerate) return; |
832 | 0 | } else { |
833 | | // In case inc is empty use a simpler alternative check. |
834 | 0 | if (m_sorted_depgraph.FeeRate(first) <= best.feerate) return; |
835 | 0 | } |
836 | | |
837 | | // Decide which transaction to split on. Splitting is how new work items are added, and |
838 | | // how progress is made. One split transaction is chosen among the queue item's |
839 | | // undecided ones, and: |
840 | | // - A work item is (potentially) added with that transaction plus its remaining |
841 | | // descendants excluded (removed from the und set). |
842 | | // - A work item is (potentially) added with that transaction plus its remaining |
843 | | // ancestors included (added to the inc set). |
844 | | // |
845 | | // To decide what to split on, consider the undecided ancestors of the highest |
846 | | // individual feerate undecided transaction. Pick the one which reduces the search space |
847 | | // most. Let I(t) be the size of the undecided set after including t, and E(t) the size |
848 | | // of the undecided set after excluding t. Then choose the split transaction t such |
849 | | // that 2^I(t) + 2^E(t) is minimal, tie-breaking by highest individual feerate for t. |
850 | 0 | ClusterIndex split = 0; |
851 | 0 | const auto select = elem.und & m_sorted_depgraph.Ancestors(first); |
852 | 0 | Assume(select.Any()); |
853 | 0 | std::optional<std::pair<ClusterIndex, ClusterIndex>> split_counts; |
854 | 0 | for (auto t : select) { |
855 | | // Call max = max(I(t), E(t)) and min = min(I(t), E(t)). Let counts = {max,min}. |
856 | | // Sorting by the tuple counts is equivalent to sorting by 2^I(t) + 2^E(t). This |
857 | | // expression is equal to 2^max + 2^min = 2^max * (1 + 1/2^(max - min)). The second |
858 | | // factor (1 + 1/2^(max - min)) there is in (1,2]. Thus increasing max will always |
859 | | // increase it, even when min decreases. Because of this, we can first sort by max. |
860 | 0 | std::pair<ClusterIndex, ClusterIndex> counts{ |
861 | 0 | (elem.und - m_sorted_depgraph.Ancestors(t)).Count(), |
862 | 0 | (elem.und - m_sorted_depgraph.Descendants(t)).Count()}; |
863 | 0 | if (counts.first < counts.second) std::swap(counts.first, counts.second); |
864 | | // Remember the t with the lowest counts. |
865 | 0 | if (!split_counts.has_value() || counts < *split_counts) { |
866 | 0 | split = t; |
867 | 0 | split_counts = counts; |
868 | 0 | } |
869 | 0 | } |
870 | | // Since there was at least one transaction in select, we must always find one. |
871 | 0 | Assume(split_counts.has_value()); |
872 | | |
873 | | // Add a work item corresponding to exclusion of the split transaction. |
874 | 0 | const auto& desc = m_sorted_depgraph.Descendants(split); |
875 | 0 | add_fn(/*inc=*/elem.inc, |
876 | 0 | /*und=*/elem.und - desc); |
877 | | |
878 | | // Add a work item corresponding to inclusion of the split transaction. |
879 | 0 | const auto anc = m_sorted_depgraph.Ancestors(split) & m_todo; |
880 | 0 | add_fn(/*inc=*/elem.inc.Add(m_sorted_depgraph, anc), |
881 | 0 | /*und=*/elem.und - anc); |
882 | | |
883 | | // Account for the performed split. |
884 | 0 | --iterations_left; |
885 | 0 | }; |
886 | | |
887 | | // Work processing loop. |
888 | | // |
889 | | // New work items are always added at the back of the queue, but items to process use a |
890 | | // hybrid approach where they can be taken from the front or the back. |
891 | | // |
892 | | // Depth-first search (DFS) corresponds to always taking from the back of the queue. This |
893 | | // is very memory-efficient (linear in the number of transactions). Breadth-first search |
894 | | // (BFS) corresponds to always taking from the front, which potentially uses more memory |
895 | | // (up to exponential in the transaction count), but seems to work better in practice. |
896 | | // |
897 | | // The approach here combines the two: use BFS (plus random swapping) until the queue grows |
898 | | // too large, at which point we temporarily switch to DFS until the size shrinks again. |
899 | 0 | while (!queue.empty()) { |
900 | | // Randomly swap the first two items to randomize the search order. |
901 | 0 | if (queue.size() > 1 && m_rng.randbool()) { |
902 | 0 | queue[0].Swap(queue[1]); |
903 | 0 | } |
904 | | |
905 | | // Processing the first queue item, and then using DFS for everything it gives rise to, |
906 | | // may increase the queue size by the number of undecided elements in there, minus 1 |
907 | | // for the first queue item being removed. Thus, only when that pushes the queue over |
908 | | // its capacity can we not process from the front (BFS), and should we use DFS. |
909 | 0 | while (queue.size() - 1 + queue.front().und.Count() > queue.capacity()) { |
910 | 0 | if (!iterations_left) break; |
911 | 0 | auto elem = queue.back(); |
912 | 0 | queue.pop_back(); |
913 | 0 | split_fn(std::move(elem)); |
914 | 0 | } |
915 | | |
916 | | // Process one entry from the front of the queue (BFS exploration) |
917 | 0 | if (!iterations_left) break; |
918 | 0 | auto elem = queue.front(); |
919 | 0 | queue.pop_front(); |
920 | 0 | split_fn(std::move(elem)); |
921 | 0 | } |
922 | | |
923 | | // Return the found best set (converted to the original transaction indices), and the |
924 | | // number of iterations performed. |
925 | 0 | best.transactions = SortedToOriginal(best.transactions); |
926 | 0 | return {std::move(best), max_iterations - iterations_left}; |
927 | 0 | } |
928 | | |
929 | | /** Remove a subset of transactions from the cluster being linearized. |
930 | | * |
931 | | * Complexity: O(N) where N=done.Count(). |
932 | | */ |
933 | | void MarkDone(const SetType& done) noexcept |
934 | 0 | { |
935 | 0 | const auto done_sorted = OriginalToSorted(done); |
936 | 0 | Assume(done_sorted.Any()); |
937 | 0 | Assume(done_sorted.IsSubsetOf(m_todo)); |
938 | 0 | m_todo -= done_sorted; |
939 | 0 | } |
940 | | }; |
941 | | |
942 | | /** Find or improve a linearization for a cluster. |
943 | | * |
944 | | * @param[in] depgraph Dependency graph of the cluster to be linearized. |
945 | | * @param[in] max_iterations Upper bound on the number of optimization steps that will be done. |
946 | | * @param[in] rng_seed A random number seed to control search order. This prevents peers |
947 | | * from predicting exactly which clusters would be hard for us to |
948 | | * linearize. |
949 | | * @param[in] old_linearization An existing linearization for the cluster (which must be |
950 | | * topologically valid), or empty. |
951 | | * @return A pair of: |
952 | | * - The resulting linearization. It is guaranteed to be at least as |
953 | | * good (in the feerate diagram sense) as old_linearization. |
954 | | * - A boolean indicating whether the result is guaranteed to be |
955 | | * optimal. |
956 | | * |
957 | | * Complexity: possibly O(N * min(max_iterations + N, sqrt(2^N))) where N=depgraph.TxCount(). |
958 | | */ |
959 | | template<typename SetType> |
960 | | std::pair<std::vector<ClusterIndex>, bool> Linearize(const DepGraph<SetType>& depgraph, uint64_t max_iterations, uint64_t rng_seed, Span<const ClusterIndex> old_linearization = {}) noexcept |
961 | 0 | { |
962 | 0 | Assume(old_linearization.empty() || old_linearization.size() == depgraph.TxCount()); |
963 | 0 | if (depgraph.TxCount() == 0) return {{}, true}; |
964 | | |
965 | 0 | uint64_t iterations_left = max_iterations; |
966 | 0 | std::vector<ClusterIndex> linearization; |
967 | |
|
968 | 0 | AncestorCandidateFinder anc_finder(depgraph); |
969 | 0 | std::optional<SearchCandidateFinder<SetType>> src_finder; |
970 | 0 | linearization.reserve(depgraph.TxCount()); |
971 | 0 | bool optimal = true; |
972 | | |
973 | | // Treat the initialization of SearchCandidateFinder as taking N^2/64 (rounded up) iterations |
974 | | // (largely due to the cost of constructing the internal sorted-by-feerate DepGraph inside |
975 | | // SearchCandidateFinder), a rough approximation based on benchmark. If we don't have that |
976 | | // many, don't start it. |
977 | 0 | uint64_t start_iterations = (uint64_t{depgraph.TxCount()} * depgraph.TxCount() + 63) / 64; |
978 | 0 | if (iterations_left > start_iterations) { |
979 | 0 | iterations_left -= start_iterations; |
980 | 0 | src_finder.emplace(depgraph, rng_seed); |
981 | 0 | } |
982 | | |
983 | | /** Chunking of what remains of the old linearization. */ |
984 | 0 | LinearizationChunking old_chunking(depgraph, old_linearization); |
985 | |
|
986 | 0 | while (true) { |
987 | | // Find the highest-feerate prefix of the remainder of old_linearization. |
988 | 0 | SetInfo<SetType> best_prefix; |
989 | 0 | if (old_chunking.NumChunksLeft()) best_prefix = old_chunking.GetChunk(0); |
990 | | |
991 | | // Then initialize best to be either the best remaining ancestor set, or the first chunk. |
992 | 0 | auto best = anc_finder.FindCandidateSet(); |
993 | 0 | if (!best_prefix.feerate.IsEmpty() && best_prefix.feerate >= best.feerate) best = best_prefix; |
994 | |
|
995 | 0 | uint64_t iterations_done_now = 0; |
996 | 0 | uint64_t max_iterations_now = 0; |
997 | 0 | if (src_finder) { |
998 | | // Treat the invocation of SearchCandidateFinder::FindCandidateSet() as costing N/4 |
999 | | // up-front (rounded up) iterations (largely due to the cost of connected-component |
1000 | | // splitting), a rough approximation based on benchmarks. |
1001 | 0 | uint64_t base_iterations = (anc_finder.NumRemaining() + 3) / 4; |
1002 | 0 | if (iterations_left > base_iterations) { |
1003 | | // Invoke bounded search to update best, with up to half of our remaining |
1004 | | // iterations as limit. |
1005 | 0 | iterations_left -= base_iterations; |
1006 | 0 | max_iterations_now = (iterations_left + 1) / 2; |
1007 | 0 | std::tie(best, iterations_done_now) = src_finder->FindCandidateSet(max_iterations_now, best); |
1008 | 0 | iterations_left -= iterations_done_now; |
1009 | 0 | } |
1010 | 0 | } |
1011 | |
|
1012 | 0 | if (iterations_done_now == max_iterations_now) { |
1013 | 0 | optimal = false; |
1014 | | // If the search result is not (guaranteed to be) optimal, run intersections to make |
1015 | | // sure we don't pick something that makes us unable to reach further diagram points |
1016 | | // of the old linearization. |
1017 | 0 | if (old_chunking.NumChunksLeft() > 0) { |
1018 | 0 | best = old_chunking.IntersectPrefixes(best); |
1019 | 0 | } |
1020 | 0 | } |
1021 | | |
1022 | | // Add to output in topological order. |
1023 | 0 | depgraph.AppendTopo(linearization, best.transactions); |
1024 | | |
1025 | | // Update state to reflect best is no longer to be linearized. |
1026 | 0 | anc_finder.MarkDone(best.transactions); |
1027 | 0 | if (anc_finder.AllDone()) break; |
1028 | 0 | if (src_finder) src_finder->MarkDone(best.transactions); |
1029 | 0 | if (old_chunking.NumChunksLeft() > 0) { |
1030 | 0 | old_chunking.MarkDone(best.transactions); |
1031 | 0 | } |
1032 | 0 | } |
1033 | |
|
1034 | 0 | return {std::move(linearization), optimal}; |
1035 | 0 | } |
1036 | | |
1037 | | /** Improve a given linearization. |
1038 | | * |
1039 | | * @param[in] depgraph Dependency graph of the cluster being linearized. |
1040 | | * @param[in,out] linearization On input, an existing linearization for depgraph. On output, a |
1041 | | * potentially better linearization for the same graph. |
1042 | | * |
1043 | | * Postlinearization guarantees: |
1044 | | * - The resulting chunks are connected. |
1045 | | * - If the input has a tree shape (either all transactions have at most one child, or all |
1046 | | * transactions have at most one parent), the result is optimal. |
1047 | | * - Given a linearization L1 and a leaf transaction T in it. Let L2 be L1 with T moved to the end, |
1048 | | * optionally with its fee increased. Let L3 be the postlinearization of L2. L3 will be at least |
1049 | | * as good as L1. This means that replacing transactions with same-size higher-fee transactions |
1050 | | * will not worsen linearizations through a "drop conflicts, append new transactions, |
1051 | | * postlinearize" process. |
1052 | | */ |
1053 | | template<typename SetType> |
1054 | | void PostLinearize(const DepGraph<SetType>& depgraph, Span<ClusterIndex> linearization) |
1055 | 0 | { |
1056 | | // This algorithm performs a number of passes (currently 2); the even ones operate from back to |
1057 | | // front, the odd ones from front to back. Each results in an equal-or-better linearization |
1058 | | // than the one started from. |
1059 | | // - One pass in either direction guarantees that the resulting chunks are connected. |
1060 | | // - Each direction corresponds to one shape of tree being linearized optimally (forward passes |
1061 | | // guarantee this for graphs where each transaction has at most one child; backward passes |
1062 | | // guarantee this for graphs where each transaction has at most one parent). |
1063 | | // - Starting with a backward pass guarantees the moved-tree property. |
1064 | | // |
1065 | | // During an odd (forward) pass, the high-level operation is: |
1066 | | // - Start with an empty list of groups L=[]. |
1067 | | // - For every transaction i in the old linearization, from front to back: |
1068 | | // - Append a new group C=[i], containing just i, to the back of L. |
1069 | | // - While L has at least one group before C, and the group immediately before C has feerate |
1070 | | // lower than C: |
1071 | | // - If C depends on P: |
1072 | | // - Merge P into C, making C the concatenation of P+C, continuing with the combined C. |
1073 | | // - Otherwise: |
1074 | | // - Swap P with C, continuing with the now-moved C. |
1075 | | // - The output linearization is the concatenation of the groups in L. |
1076 | | // |
1077 | | // During even (backward) passes, i iterates from the back to the front of the existing |
1078 | | // linearization, and new groups are prepended instead of appended to the list L. To enable |
1079 | | // more code reuse, both passes append groups, but during even passes the meanings of |
1080 | | // parent/child, and of high/low feerate are reversed, and the final concatenation is reversed |
1081 | | // on output. |
1082 | | // |
1083 | | // In the implementation below, the groups are represented by singly-linked lists (pointing |
1084 | | // from the back to the front), which are themselves organized in a singly-linked circular |
1085 | | // list (each group pointing to its predecessor, with a special sentinel group at the front |
1086 | | // that points back to the last group). |
1087 | | // |
1088 | | // Information about transaction t is stored in entries[t + 1], while the sentinel is in |
1089 | | // entries[0]. |
1090 | | |
1091 | | /** Index of the sentinel in the entries array below. */ |
1092 | 0 | static constexpr ClusterIndex SENTINEL{0}; |
1093 | | /** Indicator that a group has no previous transaction. */ |
1094 | 0 | static constexpr ClusterIndex NO_PREV_TX{0}; |
1095 | | |
1096 | | |
1097 | | /** Data structure per transaction entry. */ |
1098 | 0 | struct TxEntry |
1099 | 0 | { |
1100 | | /** The index of the previous transaction in this group; NO_PREV_TX if this is the first |
1101 | | * entry of a group. */ |
1102 | 0 | ClusterIndex prev_tx; |
1103 | | |
1104 | | // The fields below are only used for transactions that are the last one in a group |
1105 | | // (referred to as tail transactions below). |
1106 | | |
1107 | | /** Index of the first transaction in this group, possibly itself. */ |
1108 | 0 | ClusterIndex first_tx; |
1109 | | /** Index of the last transaction in the previous group. The first group (the sentinel) |
1110 | | * points back to the last group here, making it a singly-linked circular list. */ |
1111 | 0 | ClusterIndex prev_group; |
1112 | | /** All transactions in the group. Empty for the sentinel. */ |
1113 | 0 | SetType group; |
1114 | | /** All dependencies of the group (descendants in even passes; ancestors in odd ones). */ |
1115 | 0 | SetType deps; |
1116 | | /** The combined fee/size of transactions in the group. Fee is negated in even passes. */ |
1117 | 0 | FeeFrac feerate; |
1118 | 0 | }; |
1119 | | |
1120 | | // As an example, consider the state corresponding to the linearization [1,0,3,2], with |
1121 | | // groups [1,0,3] and [2], in an odd pass. The linked lists would be: |
1122 | | // |
1123 | | // +-----+ |
1124 | | // 0<-P-- | 0 S | ---\ Legend: |
1125 | | // +-----+ | |
1126 | | // ^ | - digit in box: entries index |
1127 | | // /--------------F---------+ G | (note: one more than tx value) |
1128 | | // v \ | | - S: sentinel group |
1129 | | // +-----+ +-----+ +-----+ | (empty feerate) |
1130 | | // 0<-P-- | 2 | <--P-- | 1 | <--P-- | 4 T | | - T: tail transaction, contains |
1131 | | // +-----+ +-----+ +-----+ | fields beyond prev_tv. |
1132 | | // ^ | - P: prev_tx reference |
1133 | | // G G - F: first_tx reference |
1134 | | // | | - G: prev_group reference |
1135 | | // +-----+ | |
1136 | | // 0<-P-- | 3 T | <--/ |
1137 | | // +-----+ |
1138 | | // ^ | |
1139 | | // \-F-/ |
1140 | | // |
1141 | | // During an even pass, the diagram above would correspond to linearization [2,3,0,1], with |
1142 | | // groups [2] and [3,0,1]. |
1143 | |
|
1144 | 0 | std::vector<TxEntry> entries(linearization.size() + 1); |
1145 | | |
1146 | | // Perform two passes over the linearization. |
1147 | 0 | for (int pass = 0; pass < 2; ++pass) { |
1148 | 0 | int rev = !(pass & 1); |
1149 | | // Construct a sentinel group, identifying the start of the list. |
1150 | 0 | entries[SENTINEL].prev_group = SENTINEL; |
1151 | 0 | Assume(entries[SENTINEL].feerate.IsEmpty()); |
1152 | | |
1153 | | // Iterate over all elements in the existing linearization. |
1154 | 0 | for (ClusterIndex i = 0; i < linearization.size(); ++i) { |
1155 | | // Even passes are from back to front; odd passes from front to back. |
1156 | 0 | ClusterIndex idx = linearization[rev ? linearization.size() - 1 - i : i]; |
1157 | | // Construct a new group containing just idx. In even passes, the meaning of |
1158 | | // parent/child and high/low feerate are swapped. |
1159 | 0 | ClusterIndex cur_group = idx + 1; |
1160 | 0 | entries[cur_group].group = SetType::Singleton(idx); |
1161 | 0 | entries[cur_group].deps = rev ? depgraph.Descendants(idx): depgraph.Ancestors(idx); |
1162 | 0 | entries[cur_group].feerate = depgraph.FeeRate(idx); |
1163 | 0 | if (rev) entries[cur_group].feerate.fee = -entries[cur_group].feerate.fee; |
1164 | 0 | entries[cur_group].prev_tx = NO_PREV_TX; // No previous transaction in group. |
1165 | 0 | entries[cur_group].first_tx = cur_group; // Transaction itself is first of group. |
1166 | | // Insert the new group at the back of the groups linked list. |
1167 | 0 | entries[cur_group].prev_group = entries[SENTINEL].prev_group; |
1168 | 0 | entries[SENTINEL].prev_group = cur_group; |
1169 | | |
1170 | | // Start merge/swap cycle. |
1171 | 0 | ClusterIndex next_group = SENTINEL; // We inserted at the end, so next group is sentinel. |
1172 | 0 | ClusterIndex prev_group = entries[cur_group].prev_group; |
1173 | | // Continue as long as the current group has higher feerate than the previous one. |
1174 | 0 | while (entries[cur_group].feerate >> entries[prev_group].feerate) { |
1175 | | // prev_group/cur_group/next_group refer to (the last transactions of) 3 |
1176 | | // consecutive entries in groups list. |
1177 | 0 | Assume(cur_group == entries[next_group].prev_group); |
1178 | 0 | Assume(prev_group == entries[cur_group].prev_group); |
1179 | | // The sentinel has empty feerate, which is neither higher or lower than other |
1180 | | // feerates. Thus, the while loop we are in here guarantees that cur_group and |
1181 | | // prev_group are not the sentinel. |
1182 | 0 | Assume(cur_group != SENTINEL); |
1183 | 0 | Assume(prev_group != SENTINEL); |
1184 | 0 | if (entries[cur_group].deps.Overlaps(entries[prev_group].group)) { |
1185 | | // There is a dependency between cur_group and prev_group; merge prev_group |
1186 | | // into cur_group. The group/deps/feerate fields of prev_group remain unchanged |
1187 | | // but become unused. |
1188 | 0 | entries[cur_group].group |= entries[prev_group].group; |
1189 | 0 | entries[cur_group].deps |= entries[prev_group].deps; |
1190 | 0 | entries[cur_group].feerate += entries[prev_group].feerate; |
1191 | | // Make the first of the current group point to the tail of the previous group. |
1192 | 0 | entries[entries[cur_group].first_tx].prev_tx = prev_group; |
1193 | | // The first of the previous group becomes the first of the newly-merged group. |
1194 | 0 | entries[cur_group].first_tx = entries[prev_group].first_tx; |
1195 | | // The previous group becomes whatever group was before the former one. |
1196 | 0 | prev_group = entries[prev_group].prev_group; |
1197 | 0 | entries[cur_group].prev_group = prev_group; |
1198 | 0 | } else { |
1199 | | // There is no dependency between cur_group and prev_group; swap them. |
1200 | 0 | ClusterIndex preprev_group = entries[prev_group].prev_group; |
1201 | | // If PP, P, C, N were the old preprev, prev, cur, next groups, then the new |
1202 | | // layout becomes [PP, C, P, N]. Update prev_groups to reflect that order. |
1203 | 0 | entries[next_group].prev_group = prev_group; |
1204 | 0 | entries[prev_group].prev_group = cur_group; |
1205 | 0 | entries[cur_group].prev_group = preprev_group; |
1206 | | // The current group remains the same, but the groups before/after it have |
1207 | | // changed. |
1208 | 0 | next_group = prev_group; |
1209 | 0 | prev_group = preprev_group; |
1210 | 0 | } |
1211 | 0 | } |
1212 | 0 | } |
1213 | | |
1214 | | // Convert the entries back to linearization (overwriting the existing one). |
1215 | 0 | ClusterIndex cur_group = entries[0].prev_group; |
1216 | 0 | ClusterIndex done = 0; |
1217 | 0 | while (cur_group != SENTINEL) { |
1218 | 0 | ClusterIndex cur_tx = cur_group; |
1219 | | // Traverse the transactions of cur_group (from back to front), and write them in the |
1220 | | // same order during odd passes, and reversed (front to back) in even passes. |
1221 | 0 | if (rev) { |
1222 | 0 | do { |
1223 | 0 | *(linearization.begin() + (done++)) = cur_tx - 1; |
1224 | 0 | cur_tx = entries[cur_tx].prev_tx; |
1225 | 0 | } while (cur_tx != NO_PREV_TX); |
1226 | 0 | } else { |
1227 | 0 | do { |
1228 | 0 | *(linearization.end() - (++done)) = cur_tx - 1; |
1229 | 0 | cur_tx = entries[cur_tx].prev_tx; |
1230 | 0 | } while (cur_tx != NO_PREV_TX); |
1231 | 0 | } |
1232 | 0 | cur_group = entries[cur_group].prev_group; |
1233 | 0 | } |
1234 | 0 | Assume(done == linearization.size()); |
1235 | 0 | } |
1236 | 0 | } |
1237 | | |
1238 | | /** Merge two linearizations for the same cluster into one that is as good as both. |
1239 | | * |
1240 | | * Complexity: O(N^2) where N=depgraph.TxCount(); O(N) if both inputs are identical. |
1241 | | */ |
1242 | | template<typename SetType> |
1243 | | std::vector<ClusterIndex> MergeLinearizations(const DepGraph<SetType>& depgraph, Span<const ClusterIndex> lin1, Span<const ClusterIndex> lin2) |
1244 | 0 | { |
1245 | 0 | Assume(lin1.size() == depgraph.TxCount()); |
1246 | 0 | Assume(lin2.size() == depgraph.TxCount()); |
1247 | | |
1248 | | /** Chunkings of what remains of both input linearizations. */ |
1249 | 0 | LinearizationChunking chunking1(depgraph, lin1), chunking2(depgraph, lin2); |
1250 | | /** Output linearization. */ |
1251 | 0 | std::vector<ClusterIndex> ret; |
1252 | 0 | if (depgraph.TxCount() == 0) return ret; |
1253 | 0 | ret.reserve(depgraph.TxCount()); |
1254 | |
|
1255 | 0 | while (true) { |
1256 | | // As long as we are not done, both linearizations must have chunks left. |
1257 | 0 | Assume(chunking1.NumChunksLeft() > 0); |
1258 | 0 | Assume(chunking2.NumChunksLeft() > 0); |
1259 | | // Find the set to output by taking the best remaining chunk, and then intersecting it with |
1260 | | // prefixes of remaining chunks of the other linearization. |
1261 | 0 | SetInfo<SetType> best; |
1262 | 0 | const auto& lin1_firstchunk = chunking1.GetChunk(0); |
1263 | 0 | const auto& lin2_firstchunk = chunking2.GetChunk(0); |
1264 | 0 | if (lin2_firstchunk.feerate >> lin1_firstchunk.feerate) { |
1265 | 0 | best = chunking1.IntersectPrefixes(lin2_firstchunk); |
1266 | 0 | } else { |
1267 | 0 | best = chunking2.IntersectPrefixes(lin1_firstchunk); |
1268 | 0 | } |
1269 | | // Append the result to the output and mark it as done. |
1270 | 0 | depgraph.AppendTopo(ret, best.transactions); |
1271 | 0 | chunking1.MarkDone(best.transactions); |
1272 | 0 | if (chunking1.NumChunksLeft() == 0) break; |
1273 | 0 | chunking2.MarkDone(best.transactions); |
1274 | 0 | } |
1275 | |
|
1276 | 0 | Assume(ret.size() == depgraph.TxCount()); |
1277 | 0 | return ret; |
1278 | 0 | } |
1279 | | |
1280 | | } // namespace cluster_linearize |
1281 | | |
1282 | | #endif // BITCOIN_CLUSTER_LINEARIZE_H |