19#include <unordered_set>
27static constexpr int MAX_LEVELS{2};
33using LinearizationIndex = uint32_t;
35using ClusterSetIndex = uint32_t;
38enum class QualityLevel
76 uint32_t m_parent_count;
78 uint32_t m_parent_offset;
80 uint32_t m_children_count;
82 uint32_t m_children_offset;
94 TrimTxData* m_uf_parent;
104 friend class TxGraphImpl;
105 friend class BlockBuilderImpl;
113 ClusterSetIndex m_setindex{ClusterSetIndex(-1)};
122 virtual ~Cluster() =
default;
125 Cluster(
const Cluster&) =
delete;
126 Cluster& operator=(
const Cluster&) =
delete;
127 Cluster(Cluster&&) =
delete;
128 Cluster& operator=(Cluster&&) =
delete;
133 bool IsAcceptable() const noexcept
135 return m_quality == QualityLevel::ACCEPTABLE || m_quality == QualityLevel::OPTIMAL;
138 bool IsTopological() const noexcept
140 return m_quality != QualityLevel::NEEDS_FIX && m_quality != QualityLevel::NEEDS_SPLIT_FIX;
143 bool IsOptimal() const noexcept
145 return m_quality == QualityLevel::OPTIMAL;
150 bool IsOversized() const noexcept {
return m_quality == QualityLevel::OVERSIZED_SINGLETON; }
152 bool NeedsSplitting() const noexcept
154 return m_quality == QualityLevel::NEEDS_SPLIT || m_quality == QualityLevel::NEEDS_SPLIT_FIX;
158 virtual DepGraphIndex GetMinIntendedTxCount() const noexcept = 0;
163 virtual
size_t TotalMemoryUsage() const noexcept = 0;
165 virtual
DepGraphIndex GetDepGraphIndexRange() const noexcept = 0;
167 virtual LinearizationIndex GetTxCount() const noexcept = 0;
169 virtual uint64_t GetTotalTxSize() const noexcept = 0;
171 virtual GraphIndex GetClusterEntry(
DepGraphIndex index) const noexcept = 0;
176 virtual
void AddDependencies(SetType parents,
DepGraphIndex child) noexcept = 0;
182 virtual
int GetLevel(const TxGraphImpl& graph) const noexcept = 0;
184 virtual
void UpdateMapping(
DepGraphIndex cluster_idx, GraphIndex graph_idx) noexcept = 0;
186 virtual
void Updated(TxGraphImpl& graph,
int level) noexcept = 0;
188 virtual Cluster* CopyToStaging(TxGraphImpl& graph) const noexcept = 0;
190 virtual
void GetConflicts(const TxGraphImpl& graph,
std::vector<Cluster*>&
out) const noexcept = 0;
193 virtual
void MakeStagingTransactionsMissing(TxGraphImpl& graph) noexcept = 0;
195 virtual
void Clear(TxGraphImpl& graph,
int level) noexcept = 0;
197 virtual
void MoveToMain(TxGraphImpl& graph) noexcept = 0;
199 virtual
void Compact() noexcept = 0;
205 virtual
void ApplyRemovals(TxGraphImpl& graph,
int level,
std::span<GraphIndex>& to_remove) noexcept = 0;
208 [[nodiscard]] virtual
bool Split(TxGraphImpl& graph,
int level) noexcept = 0;
210 virtual
void Merge(TxGraphImpl& graph,
int level, Cluster& cluster) noexcept = 0;
212 virtual
void ApplyDependencies(TxGraphImpl& graph,
int level,
std::span<
std::pair<GraphIndex, GraphIndex>> to_apply) noexcept = 0;
215 virtual
std::pair<uint64_t,
bool> Relinearize(TxGraphImpl& graph,
int level, uint64_t max_iters) noexcept = 0;
217 virtual
void AppendChunkFeerates(
std::vector<
FeeFrac>&
ret) const noexcept = 0;
221 virtual uint64_t AppendTrimData(
std::vector<TrimTxData>&
ret,
std::vector<
std::pair<GraphIndex, GraphIndex>>& deps) const noexcept = 0;
234 virtual
bool GetClusterRefs(TxGraphImpl& graph,
std::span<
TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept = 0;
238 virtual
void SetFee(TxGraphImpl& graph,
int level,
DepGraphIndex idx, int64_t
fee) noexcept = 0;
242 virtual
void SanityCheck(const TxGraphImpl& graph,
int level) const = 0;
247class GenericClusterImpl final : public Cluster
249 friend class TxGraphImpl;
255 std::vector<GraphIndex> m_mapping;
258 std::vector<DepGraphIndex> m_linearization;
264 static constexpr DepGraphIndex MAX_TX_COUNT{SetType::Size()};
266 GenericClusterImpl() noexcept = delete;
268 explicit GenericClusterImpl(uint64_t
sequence) noexcept;
270 size_t TotalMemoryUsage() const noexcept final;
271 constexpr
DepGraphIndex GetMinIntendedTxCount() const noexcept final {
return MIN_INTENDED_TX_COUNT; }
272 constexpr DepGraphIndex GetMaxTxCount() const noexcept final {
return MAX_TX_COUNT; }
274 LinearizationIndex GetTxCount() const noexcept final {
return m_linearization.size(); }
275 uint64_t GetTotalTxSize() const noexcept final;
276 GraphIndex GetClusterEntry(
DepGraphIndex index) const noexcept final {
return m_mapping[index]; }
278 void AddDependencies(SetType parents,
DepGraphIndex child)
noexcept final;
279 void ExtractTransactions(
const std::function<
void (
DepGraphIndex, GraphIndex,
FeePerWeight)>& visit1_fn,
const std::function<
void (
DepGraphIndex, GraphIndex, SetType)>& visit2_fn)
noexcept final;
280 int GetLevel(
const TxGraphImpl& graph)
const noexcept final;
281 void UpdateMapping(
DepGraphIndex cluster_idx, GraphIndex graph_idx)
noexcept final { m_mapping[cluster_idx] = graph_idx; }
282 void Updated(TxGraphImpl& graph,
int level)
noexcept final;
283 Cluster* CopyToStaging(TxGraphImpl& graph)
const noexcept final;
284 void GetConflicts(
const TxGraphImpl& graph, std::vector<Cluster*>&
out)
const noexcept final;
285 void MakeStagingTransactionsMissing(TxGraphImpl& graph)
noexcept final;
286 void Clear(TxGraphImpl& graph,
int level)
noexcept final;
287 void MoveToMain(TxGraphImpl& graph)
noexcept final;
288 void Compact() noexcept final;
289 void ApplyRemovals(TxGraphImpl& graph,
int level,
std::span<GraphIndex>& to_remove) noexcept final;
290 [[nodiscard]]
bool Split(TxGraphImpl& graph,
int level) noexcept final;
291 void Merge(TxGraphImpl& graph,
int level, Cluster& cluster) noexcept final;
292 void ApplyDependencies(TxGraphImpl& graph,
int level,
std::span<
std::pair<GraphIndex, GraphIndex>> to_apply) noexcept final;
293 std::pair<uint64_t,
bool> Relinearize(TxGraphImpl& graph,
int level, uint64_t max_iters) noexcept final;
294 void AppendChunkFeerates(
std::vector<
FeeFrac>&
ret) const noexcept final;
295 uint64_t AppendTrimData(
std::vector<TrimTxData>&
ret,
std::vector<
std::pair<GraphIndex, GraphIndex>>& deps) const noexcept final;
298 bool GetClusterRefs(TxGraphImpl& graph,
std::span<
TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept final;
300 void SetFee(TxGraphImpl& graph,
int level,
DepGraphIndex idx, int64_t
fee) noexcept final;
301 void SanityCheck(const TxGraphImpl& graph,
int level) const final;
305class SingletonClusterImpl final : public Cluster
307 friend class TxGraphImpl;
312 static constexpr auto NO_GRAPH_INDEX = GraphIndex(-1);
314 GraphIndex m_graph_index = NO_GRAPH_INDEX;
322 SingletonClusterImpl() noexcept = delete;
324 explicit SingletonClusterImpl(uint64_t
sequence) noexcept : Cluster(
sequence) {}
326 size_t TotalMemoryUsage() const noexcept final;
327 constexpr
DepGraphIndex GetMinIntendedTxCount() const noexcept final {
return MIN_INTENDED_TX_COUNT; }
328 constexpr DepGraphIndex GetMaxTxCount() const noexcept final {
return MAX_TX_COUNT; }
329 LinearizationIndex GetTxCount() const noexcept final {
return m_graph_index != NO_GRAPH_INDEX; }
330 DepGraphIndex GetDepGraphIndexRange() const noexcept final {
return GetTxCount(); }
331 uint64_t GetTotalTxSize() const noexcept final {
return GetTxCount() ? m_feerate.
size : 0; }
332 GraphIndex GetClusterEntry(
DepGraphIndex index)
const noexcept final {
Assume(index == 0);
Assume(GetTxCount());
return m_graph_index; }
334 void AddDependencies(SetType parents,
DepGraphIndex child)
noexcept final;
335 void ExtractTransactions(
const std::function<
void (
DepGraphIndex, GraphIndex,
FeePerWeight)>& visit1_fn,
const std::function<
void (
DepGraphIndex, GraphIndex, SetType)>& visit2_fn)
noexcept final;
336 int GetLevel(
const TxGraphImpl& graph)
const noexcept final;
337 void UpdateMapping(
DepGraphIndex cluster_idx, GraphIndex graph_idx)
noexcept final {
Assume(cluster_idx == 0); m_graph_index = graph_idx; }
338 void Updated(TxGraphImpl& graph,
int level)
noexcept final;
339 Cluster* CopyToStaging(TxGraphImpl& graph)
const noexcept final;
340 void GetConflicts(
const TxGraphImpl& graph, std::vector<Cluster*>&
out)
const noexcept final;
341 void MakeStagingTransactionsMissing(TxGraphImpl& graph)
noexcept final;
342 void Clear(TxGraphImpl& graph,
int level)
noexcept final;
343 void MoveToMain(TxGraphImpl& graph)
noexcept final;
344 void Compact() noexcept final;
345 void ApplyRemovals(TxGraphImpl& graph,
int level,
std::span<GraphIndex>& to_remove) noexcept final;
346 [[nodiscard]]
bool Split(TxGraphImpl& graph,
int level) noexcept final;
347 void Merge(TxGraphImpl& graph,
int level, Cluster& cluster) noexcept final;
348 void ApplyDependencies(TxGraphImpl& graph,
int level,
std::span<
std::pair<GraphIndex, GraphIndex>> to_apply) noexcept final;
349 std::pair<uint64_t,
bool> Relinearize(TxGraphImpl& graph,
int level, uint64_t max_iters) noexcept final;
350 void AppendChunkFeerates(
std::vector<
FeeFrac>&
ret) const noexcept final;
351 uint64_t AppendTrimData(
std::vector<TrimTxData>&
ret,
std::vector<
std::pair<GraphIndex, GraphIndex>>& deps) const noexcept final;
354 bool GetClusterRefs(TxGraphImpl& graph,
std::span<
TxGraph::Ref*> range, LinearizationIndex start_pos) noexcept final;
356 void SetFee(TxGraphImpl& graph,
int level,
DepGraphIndex idx, int64_t
fee) noexcept final;
357 void SanityCheck(const TxGraphImpl& graph,
int level) const final;
383class TxGraphImpl final : public
TxGraph
385 friend class Cluster;
386 friend class SingletonClusterImpl;
387 friend class GenericClusterImpl;
388 friend class BlockBuilderImpl;
395 const uint64_t m_max_cluster_size;
398 const uint64_t m_acceptable_iters;
404 uint32_t m_cluster_offset;
406 uint32_t m_cluster_count;
408 uint32_t m_deps_offset;
410 uint32_t m_deps_count;
417 std::vector<GroupEntry> m_groups;
419 std::vector<Cluster*> m_group_clusters;
426 std::array<std::vector<std::unique_ptr<Cluster>>, int(
QualityLevel::NONE)> m_clusters;
428 std::vector<GraphIndex> m_to_remove;
431 std::vector<std::pair<GraphIndex, GraphIndex>> m_deps_to_add;
433 std::optional<GroupData> m_group_data = GroupData{};
437 std::vector<GraphIndex> m_removed;
440 GraphIndex m_txcount{0};
442 GraphIndex m_txcount_oversized{0};
444 std::optional<bool> m_oversized{
false};
447 size_t m_cluster_usage{0};
449 ClusterSet() noexcept = default;
453 ClusterSet m_main_clusterset;
455 std::optional<ClusterSet> m_staging_clusterset;
457 uint64_t m_next_sequence_counter{0};
463 mutable GraphIndex m_graph_index;
465 LinearizationIndex m_chunk_count;
467 ChunkData(GraphIndex graph_index, LinearizationIndex chunk_count) noexcept :
468 m_graph_index{graph_index}, m_chunk_count{chunk_count} {}
472 static std::strong_ordering CompareClusters(Cluster* a, Cluster* b)
noexcept
475 if (a ==
nullptr || b ==
nullptr) {
476 return (a !=
nullptr) <=> (b !=
nullptr);
479 Assume(a == b || a->m_sequence != b->m_sequence);
480 return a->m_sequence <=> b->m_sequence;
484 std::strong_ordering CompareMainTransactions(GraphIndex a, GraphIndex b)
const noexcept
486 Assume(a < m_entries.size() && b < m_entries.size());
487 const auto& entry_a = m_entries[a];
488 const auto& entry_b = m_entries[b];
490 auto feerate_cmp = FeeRateCompare(entry_b.m_main_chunk_feerate, entry_a.m_main_chunk_feerate);
491 if (feerate_cmp < 0)
return std::strong_ordering::less;
492 if (feerate_cmp > 0)
return std::strong_ordering::greater;
494 const auto& locator_a = entry_a.m_locator[0];
495 const auto& locator_b = entry_b.m_locator[0];
496 Assume(locator_a.IsPresent() && locator_b.IsPresent());
497 if (locator_a.cluster != locator_b.cluster) {
498 return CompareClusters(locator_a.cluster, locator_b.cluster);
501 return entry_a.m_main_lin_index <=> entry_b.m_main_lin_index;
507 const TxGraphImpl*
const m_graph;
509 explicit ChunkOrder(
const TxGraphImpl* graph) : m_graph(graph) {}
511 bool operator()(
const ChunkData& a,
const ChunkData& b)
const noexcept
513 return m_graph->CompareMainTransactions(a.m_graph_index, b.m_graph_index) < 0;
518 using ChunkIndex = std::set<ChunkData, ChunkOrder>;
522 ChunkIndex m_main_chunkindex;
524 size_t m_main_chunkindex_observers{0};
526 std::vector<ChunkIndex::node_type> m_main_chunkindex_discarded;
561 Cluster* cluster{
nullptr};
566 void SetMissing() noexcept { cluster =
nullptr; index = 0; }
568 void SetRemoved() noexcept { cluster =
nullptr; index =
DepGraphIndex(-1); }
570 void SetPresent(Cluster* c,
DepGraphIndex i)
noexcept { cluster = c; index = i; }
572 bool IsMissing() const noexcept {
return cluster ==
nullptr && index == 0; }
574 bool IsRemoved() const noexcept {
return cluster ==
nullptr && index ==
DepGraphIndex(-1); }
576 bool IsPresent() const noexcept {
return cluster !=
nullptr; }
586 ChunkIndex::iterator m_main_chunkindex_iterator;
588 Locator m_locator[MAX_LEVELS];
592 LinearizationIndex m_main_lin_index;
596 std::vector<Entry> m_entries;
599 std::vector<GraphIndex> m_unlinked;
603 explicit TxGraphImpl(
DepGraphIndex max_cluster_count, uint64_t max_cluster_size, uint64_t acceptable_iters) noexcept :
604 m_max_cluster_count(max_cluster_count),
605 m_max_cluster_size(max_cluster_size),
606 m_acceptable_iters(acceptable_iters),
607 m_main_chunkindex(ChunkOrder(
this))
609 Assume(max_cluster_count >= 1);
614 ~TxGraphImpl() noexcept;
617 TxGraphImpl(const TxGraphImpl&) = delete;
618 TxGraphImpl& operator=(const TxGraphImpl&) = delete;
619 TxGraphImpl(TxGraphImpl&&) = delete;
620 TxGraphImpl& operator=(TxGraphImpl&&) = delete;
625 void SwapIndexes(GraphIndex a, GraphIndex b) noexcept;
628 Cluster* FindCluster(GraphIndex idx,
int level) const noexcept {
return FindClusterAndLevel(idx, level).first; }
630 std::pair<Cluster*, int> FindClusterAndLevel(GraphIndex idx,
int level)
const noexcept;
632 std::unique_ptr<Cluster> ExtractCluster(
int level, QualityLevel quality, ClusterSetIndex setindex)
noexcept;
634 void DeleteCluster(Cluster& cluster,
int level)
noexcept;
636 ClusterSetIndex InsertCluster(
int level, std::unique_ptr<Cluster>&& cluster, QualityLevel quality)
noexcept;
638 void SetClusterQuality(
int level, QualityLevel old_quality, ClusterSetIndex old_index, QualityLevel new_quality)
noexcept;
640 int GetTopLevel() const noexcept {
return m_staging_clusterset.has_value(); }
642 int GetSpecifiedLevel(
Level level)
const noexcept {
return level == Level::TOP && m_staging_clusterset.has_value(); }
644 ClusterSet& GetClusterSet(
int level)
noexcept;
645 const ClusterSet& GetClusterSet(
int level)
const noexcept;
649 void ClearLocator(
int level, GraphIndex index,
bool oversized_tx)
noexcept;
651 std::vector<Cluster*> GetConflicts() const noexcept;
653 void ClearChunkData(Entry& entry) noexcept;
655 void CreateChunkData(GraphIndex idx, LinearizationIndex chunk_count) noexcept;
657 std::unique_ptr<GenericClusterImpl> CreateEmptyGenericCluster() noexcept
659 return std::make_unique<GenericClusterImpl>(m_next_sequence_counter++);
662 std::unique_ptr<SingletonClusterImpl> CreateEmptySingletonCluster() noexcept
664 return std::make_unique<SingletonClusterImpl>(m_next_sequence_counter++);
668 std::unique_ptr<Cluster> CreateEmptyCluster(
DepGraphIndex tx_count)
noexcept
670 if (tx_count >= SingletonClusterImpl::MIN_INTENDED_TX_COUNT && tx_count <= SingletonClusterImpl::MAX_TX_COUNT) {
671 return CreateEmptySingletonCluster();
673 if (tx_count >= GenericClusterImpl::MIN_INTENDED_TX_COUNT && tx_count <= GenericClusterImpl::MAX_TX_COUNT) {
674 return CreateEmptyGenericCluster();
683 void UpdateRef(GraphIndex idx, Ref& new_location)
noexcept final
685 auto& entry = m_entries[idx];
686 Assume(entry.m_ref !=
nullptr);
687 entry.m_ref = &new_location;
691 void UnlinkRef(GraphIndex idx)
noexcept final
693 auto& entry = m_entries[idx];
694 Assume(entry.m_ref !=
nullptr);
695 Assume(m_main_chunkindex_observers == 0 || !entry.m_locator[0].IsPresent());
696 entry.m_ref =
nullptr;
699 bool exists_anywhere{
false};
701 for (
int level = 0; level <= GetTopLevel(); ++level) {
702 if (entry.m_locator[level].IsPresent()) {
703 exists_anywhere =
true;
705 }
else if (entry.m_locator[level].IsRemoved()) {
709 auto& clusterset = GetClusterSet(level);
710 clusterset.m_to_remove.push_back(idx);
712 clusterset.m_group_data = std::nullopt;
718 if (level == GetTopLevel() && clusterset.m_oversized ==
true) {
719 clusterset.m_oversized = std::nullopt;
723 m_unlinked.push_back(idx);
724 if (!exists_anywhere) Compact();
731 void Compact() noexcept;
735 Cluster* PullIn(Cluster* cluster,
int level) noexcept;
738 void ApplyRemovals(
int up_to_level) noexcept;
740 void Split(Cluster& cluster,
int level) noexcept;
742 void SplitAll(
int up_to_level) noexcept;
744 void GroupClusters(
int level) noexcept;
746 void Merge(
std::span<Cluster*> to_merge,
int level) noexcept;
748 void ApplyDependencies(
int level) noexcept;
750 void MakeAcceptable(Cluster& cluster,
int level) noexcept;
752 void MakeAllAcceptable(
int level) noexcept;
756 Ref AddTransaction(const
FeePerWeight& feerate) noexcept final;
757 void RemoveTransaction(const Ref& arg) noexcept final;
758 void AddDependency(const Ref& parent, const Ref& child) noexcept final;
759 void SetTransactionFee(const Ref&, int64_t
fee) noexcept final;
761 bool DoWork(uint64_t iters) noexcept final;
763 void StartStaging() noexcept final;
764 void CommitStaging() noexcept final;
765 void AbortStaging() noexcept final;
766 bool HaveStaging() const noexcept final {
return m_staging_clusterset.has_value(); }
768 bool Exists(
const Ref& arg,
Level level)
noexcept final;
769 FeePerWeight GetMainChunkFeerate(
const Ref& arg)
noexcept final;
770 FeePerWeight GetIndividualFeerate(
const Ref& arg)
noexcept final;
771 std::vector<Ref*> GetCluster(
const Ref& arg,
Level level)
noexcept final;
772 std::vector<Ref*> GetAncestors(
const Ref& arg,
Level level)
noexcept final;
773 std::vector<Ref*> GetDescendants(
const Ref& arg,
Level level)
noexcept final;
774 std::vector<Ref*> GetAncestorsUnion(std::span<const Ref* const>
args,
Level level)
noexcept final;
775 std::vector<Ref*> GetDescendantsUnion(std::span<const Ref* const>
args,
Level level)
noexcept final;
776 GraphIndex GetTransactionCount(
Level level)
noexcept final;
777 bool IsOversized(
Level level)
noexcept final;
778 std::strong_ordering CompareMainOrder(
const Ref& a,
const Ref& b)
noexcept final;
779 GraphIndex CountDistinctClusters(std::span<const Ref* const> refs,
Level level)
noexcept final;
780 std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>> GetMainStagingDiagrams() noexcept final;
781 std::vector<Ref*> Trim() noexcept final;
783 std::unique_ptr<BlockBuilder> GetBlockBuilder() noexcept final;
786 size_t GetMainMemoryUsage() noexcept final;
788 void SanityCheck() const final;
791TxGraphImpl::ClusterSet& TxGraphImpl::GetClusterSet(
int level) noexcept
793 if (level == 0)
return m_main_clusterset;
795 Assume(m_staging_clusterset.has_value());
796 return *m_staging_clusterset;
799const TxGraphImpl::ClusterSet& TxGraphImpl::GetClusterSet(
int level)
const noexcept
801 if (level == 0)
return m_main_clusterset;
803 Assume(m_staging_clusterset.has_value());
804 return *m_staging_clusterset;
812 TxGraphImpl*
const m_graph;
814 std::unordered_set<uint64_t> m_excluded_clusters;
816 TxGraphImpl::ChunkIndex::const_iterator m_cur_iter;
819 Cluster* m_cur_cluster;
821 bool m_known_end_of_cluster;
824 void Next() noexcept;
828 BlockBuilderImpl(TxGraphImpl& graph) noexcept;
831 ~BlockBuilderImpl() final;
833 void Include() noexcept final;
834 void Skip() noexcept final;
837void TxGraphImpl::ClearChunkData(Entry& entry) noexcept
839 if (entry.m_main_chunkindex_iterator != m_main_chunkindex.end()) {
840 Assume(m_main_chunkindex_observers == 0);
843 m_main_chunkindex_discarded.emplace_back(m_main_chunkindex.extract(entry.m_main_chunkindex_iterator));
844 entry.m_main_chunkindex_iterator = m_main_chunkindex.end();
848void TxGraphImpl::CreateChunkData(GraphIndex idx, LinearizationIndex chunk_count)
noexcept
850 auto& entry = m_entries[idx];
851 if (!m_main_chunkindex_discarded.empty()) {
853 auto&
node = m_main_chunkindex_discarded.back().value();
854 node.m_graph_index = idx;
855 node.m_chunk_count = chunk_count;
856 auto insert_result = m_main_chunkindex.insert(std::move(m_main_chunkindex_discarded.back()));
857 Assume(insert_result.inserted);
858 entry.m_main_chunkindex_iterator = insert_result.position;
859 m_main_chunkindex_discarded.pop_back();
862 auto emplace_result = m_main_chunkindex.emplace(idx, chunk_count);
863 Assume(emplace_result.second);
864 entry.m_main_chunkindex_iterator = emplace_result.first;
868size_t GenericClusterImpl::TotalMemoryUsage() const noexcept
877 sizeof(std::unique_ptr<Cluster>);
880size_t SingletonClusterImpl::TotalMemoryUsage() const noexcept
885 sizeof(std::unique_ptr<Cluster>);
888uint64_t GenericClusterImpl::GetTotalTxSize() const noexcept
891 for (
auto i : m_linearization) {
899 Assume(graph_idx != GraphIndex(-1));
901 m_mapping.push_back(graph_idx);
902 m_linearization.push_back(
ret);
909 m_graph_index = graph_idx;
914void GenericClusterImpl::AddDependencies(SetType parents,
DepGraphIndex child)
noexcept
919void SingletonClusterImpl::AddDependencies(SetType parents,
DepGraphIndex child)
noexcept
923 Assume(parents == SetType{} || parents == SetType::Fill(0));
926void GenericClusterImpl::ExtractTransactions(
const std::function<
void (
DepGraphIndex, GraphIndex,
FeePerWeight)>& visit1_fn,
const std::function<
void (
DepGraphIndex, GraphIndex, SetType)>& visit2_fn)
noexcept
928 for (
auto pos : m_linearization) {
931 for (
auto pos : m_linearization) {
936 m_linearization.clear();
940void SingletonClusterImpl::ExtractTransactions(
const std::function<
void (
DepGraphIndex, GraphIndex,
FeePerWeight)>& visit1_fn,
const std::function<
void (
DepGraphIndex, GraphIndex, SetType)>& visit2_fn)
noexcept
943 visit1_fn(0, m_graph_index, m_feerate);
944 visit2_fn(0, m_graph_index, SetType{});
945 m_graph_index = NO_GRAPH_INDEX;
949int GenericClusterImpl::GetLevel(
const TxGraphImpl& graph)
const noexcept
952 if (!
Assume(!m_linearization.empty()))
return -1;
955 const auto& entry = graph.m_entries[m_mapping[m_linearization.front()]];
957 for (
int level = 0; level < MAX_LEVELS; ++level) {
958 if (entry.m_locator[level].cluster ==
this)
return level;
966int SingletonClusterImpl::GetLevel(
const TxGraphImpl& graph)
const noexcept
969 if (!
Assume(GetTxCount()))
return -1;
972 const auto& entry = graph.m_entries[m_graph_index];
974 for (
int level = 0; level < MAX_LEVELS; ++level) {
975 if (entry.m_locator[level].cluster ==
this)
return level;
983void TxGraphImpl::ClearLocator(
int level, GraphIndex idx,
bool oversized_tx)
noexcept
985 auto& entry = m_entries[idx];
986 auto& clusterset = GetClusterSet(level);
987 Assume(entry.m_locator[level].IsPresent());
989 if (level == 0 || !entry.m_locator[level - 1].IsPresent()) {
990 entry.m_locator[level].SetMissing();
992 entry.m_locator[level].SetRemoved();
993 clusterset.m_removed.push_back(idx);
996 --clusterset.m_txcount;
997 clusterset.m_txcount_oversized -= oversized_tx;
999 if (level == 0 && GetTopLevel() == 1) {
1000 if (entry.m_locator[1].IsRemoved()) {
1001 entry.m_locator[1].SetMissing();
1002 }
else if (!entry.m_locator[1].IsPresent()) {
1003 --m_staging_clusterset->m_txcount;
1004 m_staging_clusterset->m_txcount_oversized -= oversized_tx;
1007 if (level == 0) ClearChunkData(entry);
1010void GenericClusterImpl::Updated(TxGraphImpl& graph,
int level)
noexcept
1014 auto& entry = graph.m_entries[m_mapping[idx]];
1017 if (level == 0) graph.ClearChunkData(entry);
1018 entry.m_locator[level].SetPresent(
this, idx);
1025 if (level == 0 && IsAcceptable()) {
1027 LinearizationIndex lin_idx{0};
1029 for (
unsigned chunk_idx = 0; chunk_idx < chunking.size(); ++chunk_idx) {
1030 auto& chunk = chunking[chunk_idx];
1031 auto chunk_count = chunk.transactions.Count();
1036 GraphIndex graph_idx = m_mapping[idx];
1037 auto& entry = graph.m_entries[graph_idx];
1038 entry.m_main_lin_index = lin_idx++;
1040 Assume(chunk.transactions[idx]);
1041 chunk.transactions.Reset(idx);
1042 if (chunk.transactions.None()) {
1044 if (chunk_count == 1 && chunk_idx + 1 == chunking.size()) {
1048 chunk_count = LinearizationIndex(-1);
1050 graph.CreateChunkData(graph_idx, chunk_count);
1058void SingletonClusterImpl::Updated(TxGraphImpl& graph,
int level)
noexcept
1061 if (GetTxCount() == 0)
return;
1063 auto& entry = graph.m_entries[m_graph_index];
1066 if (level == 0) graph.ClearChunkData(entry);
1067 entry.m_locator[level].SetPresent(
this, 0);
1070 if (level == 0 && IsAcceptable()) {
1071 entry.m_main_lin_index = 0;
1072 entry.m_main_chunk_feerate = m_feerate;
1075 graph.CreateChunkData(m_graph_index, LinearizationIndex(-1));
1079void GenericClusterImpl::GetConflicts(
const TxGraphImpl& graph, std::vector<Cluster*>&
out)
const noexcept
1081 for (
auto i : m_linearization) {
1082 auto& entry = graph.m_entries[m_mapping[i]];
1085 if (entry.m_locator[0].IsPresent()) {
1086 out.push_back(entry.m_locator[0].cluster);
1091void SingletonClusterImpl::GetConflicts(
const TxGraphImpl& graph, std::vector<Cluster*>&
out)
const noexcept
1094 if (GetTxCount() == 0)
return;
1096 auto& entry = graph.m_entries[m_graph_index];
1099 if (entry.m_locator[0].IsPresent()) {
1100 out.push_back(entry.m_locator[0].cluster);
1104std::vector<Cluster*> TxGraphImpl::GetConflicts() const noexcept
1106 Assume(GetTopLevel() == 1);
1107 auto& clusterset = GetClusterSet(1);
1108 std::vector<Cluster*>
ret;
1110 for (
auto i : clusterset.m_removed) {
1111 auto& entry = m_entries[i];
1112 if (entry.m_locator[0].IsPresent()) {
1113 ret.push_back(entry.m_locator[0].cluster);
1118 auto& clusters = clusterset.m_clusters[quality];
1119 for (
const auto& cluster : clusters) {
1120 cluster->GetConflicts(*
this,
ret);
1124 std::sort(
ret.begin(),
ret.end(), [](Cluster* a, Cluster* b)
noexcept { return CompareClusters(a, b) < 0; });
1125 ret.erase(std::unique(
ret.begin(),
ret.end()),
ret.end());
1129Cluster* GenericClusterImpl::CopyToStaging(TxGraphImpl& graph)
const noexcept
1132 auto ret = graph.CreateEmptyGenericCluster();
1133 auto ptr =
ret.get();
1135 ptr->m_depgraph = m_depgraph;
1136 ptr->m_mapping = m_mapping;
1137 ptr->m_linearization = m_linearization;
1139 graph.InsertCluster(1, std::move(
ret), m_quality);
1141 ptr->Updated(graph, 1);
1143 graph.GetClusterSet(1).m_cluster_usage += ptr->TotalMemoryUsage();
1147Cluster* SingletonClusterImpl::CopyToStaging(TxGraphImpl& graph)
const noexcept
1150 auto ret = graph.CreateEmptySingletonCluster();
1151 auto ptr =
ret.get();
1153 ptr->m_graph_index = m_graph_index;
1154 ptr->m_feerate = m_feerate;
1156 graph.InsertCluster(1, std::move(
ret), m_quality);
1158 ptr->Updated(graph, 1);
1160 graph.GetClusterSet(1).m_cluster_usage += ptr->TotalMemoryUsage();
1164void GenericClusterImpl::ApplyRemovals(TxGraphImpl& graph,
int level, std::span<GraphIndex>& to_remove)
noexcept
1167 Assume(!to_remove.empty());
1169 graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1171 GraphIndex idx = to_remove.front();
1172 Assume(idx < graph.m_entries.size());
1173 auto& entry = graph.m_entries[idx];
1174 auto& locator = entry.m_locator[level];
1176 if (locator.cluster !=
this)
break;
1178 todo.Set(locator.index);
1182 m_mapping[locator.index] = GraphIndex(-1);
1185 entry.m_main_lin_index = LinearizationIndex(-1);
1188 graph.ClearLocator(level, idx, m_quality == QualityLevel::OVERSIZED_SINGLETON);
1189 to_remove = to_remove.subspan(1);
1190 }
while(!to_remove.empty());
1199 m_linearization.erase(std::remove_if(m_linearization.begin(), m_linearization.end(),
1200 [&](
auto pos) { return todo[pos]; }),
1201 m_linearization.end());
1204 graph.GetClusterSet(level).m_cluster_usage += TotalMemoryUsage();
1205 auto new_quality = IsTopological() ? QualityLevel::NEEDS_SPLIT : QualityLevel::NEEDS_SPLIT_FIX;
1206 graph.SetClusterQuality(level, m_quality, m_setindex, new_quality);
1207 Updated(graph, level);
1210void SingletonClusterImpl::ApplyRemovals(TxGraphImpl& graph,
int level, std::span<GraphIndex>& to_remove)
noexcept
1213 Assume(!to_remove.empty());
1215 Assume(to_remove.front() == m_graph_index);
1219 to_remove = to_remove.subspan(1);
1220 }
while (!to_remove.empty() && to_remove.front() == m_graph_index);
1222 graph.ClearLocator(level, m_graph_index, m_quality == QualityLevel::OVERSIZED_SINGLETON);
1223 m_graph_index = NO_GRAPH_INDEX;
1224 graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_SPLIT);
1229void GenericClusterImpl::Clear(TxGraphImpl& graph,
int level)
noexcept
1232 graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1233 for (
auto i : m_linearization) {
1234 graph.ClearLocator(level, m_mapping[i], m_quality == QualityLevel::OVERSIZED_SINGLETON);
1237 m_linearization.clear();
1241void SingletonClusterImpl::Clear(TxGraphImpl& graph,
int level)
noexcept
1244 graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1245 graph.ClearLocator(level, m_graph_index, m_quality == QualityLevel::OVERSIZED_SINGLETON);
1246 m_graph_index = NO_GRAPH_INDEX;
1249void GenericClusterImpl::MoveToMain(TxGraphImpl& graph)
noexcept
1251 for (
auto i : m_linearization) {
1252 GraphIndex idx = m_mapping[i];
1253 auto& entry = graph.m_entries[idx];
1254 entry.m_locator[1].SetMissing();
1256 auto quality = m_quality;
1258 graph.GetClusterSet(1).m_cluster_usage -= TotalMemoryUsage();
1259 graph.GetClusterSet(0).m_cluster_usage += TotalMemoryUsage();
1261 auto cluster = graph.ExtractCluster(1, quality, m_setindex);
1262 graph.InsertCluster(0, std::move(cluster), quality);
1266void SingletonClusterImpl::MoveToMain(TxGraphImpl& graph)
noexcept
1269 auto& entry = graph.m_entries[m_graph_index];
1270 entry.m_locator[1].SetMissing();
1272 auto quality = m_quality;
1273 graph.GetClusterSet(1).m_cluster_usage -= TotalMemoryUsage();
1274 auto cluster = graph.ExtractCluster(1, quality, m_setindex);
1275 graph.InsertCluster(0, std::move(cluster), quality);
1276 graph.GetClusterSet(0).m_cluster_usage += TotalMemoryUsage();
1280void GenericClusterImpl::Compact() noexcept
1282 m_linearization.shrink_to_fit();
1283 m_mapping.shrink_to_fit();
1287void SingletonClusterImpl::Compact() noexcept
1292void GenericClusterImpl::AppendChunkFeerates(std::vector<FeeFrac>&
ret)
const noexcept
1295 ret.reserve(
ret.size() + chunk_feerates.size());
1296 ret.insert(
ret.end(), chunk_feerates.begin(), chunk_feerates.end());
1299void SingletonClusterImpl::AppendChunkFeerates(std::vector<FeeFrac>&
ret)
const noexcept
1302 ret.push_back(m_feerate);
1306uint64_t GenericClusterImpl::AppendTrimData(std::vector<TrimTxData>&
ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps)
const noexcept
1310 LinearizationIndex pos{0};
1312 auto prev_index = GraphIndex(-1);
1314 for (
const auto& [chunk, chunk_feerate] : linchunking) {
1316 auto chunk_tx_count = chunk.Count();
1317 for (
unsigned j = 0; j < chunk_tx_count; ++j) {
1318 auto cluster_idx = m_linearization[pos];
1320 Assume(chunk[cluster_idx]);
1322 auto& entry =
ret.emplace_back();
1324 entry.m_index = m_mapping[cluster_idx];
1327 if (pos != 0) deps.emplace_back(prev_index, entry.m_index);
1328 prev_index = entry.m_index;
1329 entry.m_tx_size = m_depgraph.
FeeRate(cluster_idx).
size;
1330 size += entry.m_tx_size;
1337uint64_t SingletonClusterImpl::AppendTrimData(std::vector<TrimTxData>&
ret, std::vector<std::pair<GraphIndex, GraphIndex>>& deps)
const noexcept
1339 if (!GetTxCount())
return 0;
1340 auto& entry =
ret.emplace_back();
1341 entry.m_chunk_feerate = m_feerate;
1342 entry.m_index = m_graph_index;
1343 entry.m_tx_size = m_feerate.
size;
1344 return m_feerate.
size;
1350 Assume(NeedsSplitting());
1352 QualityLevel new_quality = IsTopological() ? QualityLevel::NEEDS_RELINEARIZE : QualityLevel::NEEDS_FIX;
1357 std::vector<std::pair<Cluster*, DepGraphIndex>> remap(m_depgraph.
PositionRange());
1358 std::vector<Cluster*> new_clusters;
1361 while (todo.Any()) {
1363 auto component_size = component.Count();
1364 auto split_quality = component_size <= 1 ? QualityLevel::OPTIMAL : new_quality;
1365 if (first && component == todo && SetType::Fill(component_size) == component && component_size >= MIN_INTENDED_TX_COUNT) {
1372 graph.SetClusterQuality(level, m_quality, m_setindex, split_quality);
1375 Updated(graph, level);
1380 auto new_cluster = graph.CreateEmptyCluster(component_size);
1381 new_clusters.push_back(new_cluster.get());
1384 for (
auto i : component) {
1387 graph.InsertCluster(level, std::move(new_cluster), split_quality);
1391 graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1393 for (
auto i : m_linearization) {
1395 Cluster* new_cluster = remap[i].first;
1400 for (
auto i : m_linearization) {
1402 Cluster* new_cluster = remap[i].first;
1404 SetType new_parents;
1405 for (
auto par : m_depgraph.
GetReducedParents(i)) new_parents.Set(remap[par].second);
1406 new_cluster->AddDependencies(new_parents, remap[i].second);
1409 for (Cluster* new_cluster : new_clusters) {
1410 new_cluster->Updated(graph, level);
1411 new_cluster->Compact();
1412 graph.GetClusterSet(level).m_cluster_usage += new_cluster->TotalMemoryUsage();
1417 m_linearization.clear();
1423 Assume(NeedsSplitting());
1425 graph.GetClusterSet(level).m_cluster_usage -= TotalMemoryUsage();
1429void GenericClusterImpl::Merge(TxGraphImpl& graph,
int level, Cluster& other)
noexcept
1432 std::vector<DepGraphIndex> remap(other.GetDepGraphIndexRange());
1439 Assume(new_pos == m_mapping.size());
1440 remap[pos] = new_pos;
1441 m_mapping.push_back(idx);
1442 m_linearization.push_back(new_pos);
1443 }, [&](
DepGraphIndex pos, GraphIndex idx, SetType other_parents)
noexcept {
1446 for (
auto par : other_parents) {
1447 parents.Set(remap[par]);
1453 auto& entry = graph.m_entries[idx];
1456 if (level == 0) graph.ClearChunkData(entry);
1457 entry.m_locator[level].SetPresent(
this, remap[pos]);
1461void SingletonClusterImpl::Merge(TxGraphImpl&,
int, Cluster&)
noexcept
1467void GenericClusterImpl::ApplyDependencies(TxGraphImpl& graph,
int level, std::span<std::pair<GraphIndex, GraphIndex>> to_apply)
noexcept
1470 std::sort(to_apply.begin(), to_apply.end(), [](
auto& a,
auto& b) { return a.second < b.second; });
1472 auto it = to_apply.begin();
1473 while (it != to_apply.end()) {
1474 auto& first_child = graph.m_entries[it->second].m_locator[level];
1475 const auto child_idx = first_child.index;
1479 while (it != to_apply.end()) {
1480 auto& child = graph.m_entries[it->second].m_locator[level];
1481 auto& parent = graph.m_entries[it->first].m_locator[level];
1482 Assume(child.cluster ==
this && parent.cluster ==
this);
1483 if (child.index != child_idx)
break;
1484 parents.Set(parent.index);
1495 Assume(!NeedsSplitting());
1497 graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_FIX);
1500 Updated(graph, level);
1503void SingletonClusterImpl::ApplyDependencies(TxGraphImpl&,
int, std::span<std::pair<GraphIndex, GraphIndex>>) noexcept
1509TxGraphImpl::~TxGraphImpl() noexcept
1513 for (
auto& entry : m_entries) {
1514 if (entry.m_ref !=
nullptr) {
1515 GetRefGraph(*entry.m_ref) =
nullptr;
1520std::unique_ptr<Cluster> TxGraphImpl::ExtractCluster(
int level, QualityLevel quality, ClusterSetIndex setindex)
noexcept
1524 auto& clusterset = GetClusterSet(level);
1525 auto& quality_clusters = clusterset.m_clusters[int(quality)];
1526 Assume(setindex < quality_clusters.size());
1529 std::unique_ptr<Cluster>
ret = std::move(quality_clusters[setindex]);
1531 ret->m_setindex = ClusterSetIndex(-1);
1534 auto max_setindex = quality_clusters.size() - 1;
1535 if (setindex != max_setindex) {
1537 quality_clusters.back()->m_setindex = setindex;
1538 quality_clusters[setindex] = std::move(quality_clusters.back());
1541 quality_clusters.pop_back();
1546ClusterSetIndex TxGraphImpl::InsertCluster(
int level, std::unique_ptr<Cluster>&& cluster, QualityLevel quality)
noexcept
1554 auto& clusterset = GetClusterSet(level);
1555 auto& quality_clusters = clusterset.m_clusters[int(quality)];
1556 ClusterSetIndex
ret = quality_clusters.size();
1557 cluster->m_quality = quality;
1558 cluster->m_setindex =
ret;
1559 quality_clusters.push_back(std::move(cluster));
1563void TxGraphImpl::SetClusterQuality(
int level, QualityLevel old_quality, ClusterSetIndex old_index, QualityLevel new_quality)
noexcept
1568 if (old_quality == new_quality)
return;
1570 auto cluster_ptr = ExtractCluster(level, old_quality, old_index);
1572 InsertCluster(level, std::move(cluster_ptr), new_quality);
1575void TxGraphImpl::DeleteCluster(Cluster& cluster,
int level)
noexcept
1578 auto cluster_ptr = ExtractCluster(level, cluster.m_quality, cluster.m_setindex);
1580 cluster_ptr.reset();
1583std::pair<Cluster*, int> TxGraphImpl::FindClusterAndLevel(GraphIndex idx,
int level)
const noexcept
1585 Assume(level >= 0 && level <= GetTopLevel());
1586 auto& entry = m_entries[idx];
1588 for (
int l = level; l >= 0; --l) {
1591 if (entry.m_locator[l].IsMissing())
continue;
1593 if (entry.m_locator[l].IsRemoved())
break;
1595 return {entry.m_locator[l].cluster, l};
1598 return {
nullptr, -1};
1601Cluster* TxGraphImpl::PullIn(Cluster* cluster,
int level)
noexcept
1603 int to_level = GetTopLevel();
1605 Assume(level <= to_level);
1610 MakeAcceptable(*cluster, level);
1611 cluster = cluster->CopyToStaging(*
this);
1616void TxGraphImpl::ApplyRemovals(
int up_to_level)
noexcept
1618 Assume(up_to_level >= 0 && up_to_level <= GetTopLevel());
1619 for (
int level = 0; level <= up_to_level; ++level) {
1620 auto& clusterset = GetClusterSet(level);
1621 auto& to_remove = clusterset.m_to_remove;
1623 if (to_remove.empty())
continue;
1626 for (GraphIndex index : to_remove) {
1627 auto [cluster, cluster_level] = FindClusterAndLevel(index, level);
1628 if (cluster !=
nullptr) PullIn(cluster, cluster_level);
1632 std::sort(to_remove.begin(), to_remove.end(), [&](GraphIndex a, GraphIndex b)
noexcept {
1633 Cluster* cluster_a = m_entries[a].m_locator[level].cluster;
1634 Cluster* cluster_b = m_entries[b].m_locator[level].cluster;
1635 return CompareClusters(cluster_a, cluster_b) < 0;
1638 std::span to_remove_span{to_remove};
1639 while (!to_remove_span.empty()) {
1640 Cluster* cluster = m_entries[to_remove_span.front()].m_locator[level].cluster;
1641 if (cluster !=
nullptr) {
1644 cluster->ApplyRemovals(*
this, level, to_remove_span);
1648 to_remove_span = to_remove_span.subspan(1);
1656void TxGraphImpl::SwapIndexes(GraphIndex a, GraphIndex b)
noexcept
1658 Assume(a < m_entries.size());
1659 Assume(b < m_entries.size());
1661 std::swap(m_entries[a], m_entries[b]);
1663 for (
int i = 0; i < 2; ++i) {
1664 GraphIndex idx = i ? b : a;
1665 Entry& entry = m_entries[idx];
1667 if (entry.m_ref) GetRefIndex(*entry.m_ref) = idx;
1669 if (entry.m_main_chunkindex_iterator != m_main_chunkindex.end()) {
1670 entry.m_main_chunkindex_iterator->m_graph_index = idx;
1674 for (
int level = 0; level < MAX_LEVELS; ++level) {
1675 Locator& locator = entry.m_locator[level];
1676 if (locator.IsPresent()) {
1677 locator.cluster->UpdateMapping(locator.index, idx);
1683void TxGraphImpl::Compact() noexcept
1687 if (!m_main_clusterset.m_deps_to_add.empty())
return;
1688 if (!m_main_clusterset.m_to_remove.empty())
return;
1689 Assume(m_main_clusterset.m_removed.empty());
1690 if (m_staging_clusterset.has_value()) {
1691 if (!m_staging_clusterset->m_deps_to_add.empty())
return;
1692 if (!m_staging_clusterset->m_to_remove.empty())
return;
1693 if (!m_staging_clusterset->m_removed.empty())
return;
1703 std::sort(m_unlinked.begin(), m_unlinked.end(), std::greater{});
1705 auto last = GraphIndex(-1);
1706 for (GraphIndex idx : m_unlinked) {
1713 Entry& entry = m_entries[idx];
1714 Assume(entry.m_ref ==
nullptr);
1716 for (
int level = 0; level < MAX_LEVELS; ++level) {
1717 Assume(!entry.m_locator[level].IsPresent());
1721 if (idx != m_entries.size() - 1) SwapIndexes(idx, m_entries.size() - 1);
1723 m_entries.pop_back();
1732 ApplyRemovals(level);
1733 bool del = cluster.Split(*
this, level);
1736 DeleteCluster(cluster, level);
1740void TxGraphImpl::SplitAll(
int up_to_level)
noexcept
1742 Assume(up_to_level >= 0 && up_to_level <= GetTopLevel());
1744 ApplyRemovals(up_to_level);
1745 for (
int level = 0; level <= up_to_level; ++level) {
1746 for (
auto quality : {QualityLevel::NEEDS_SPLIT_FIX, QualityLevel::NEEDS_SPLIT}) {
1747 auto& queue = GetClusterSet(level).m_clusters[int(quality)];
1748 while (!queue.empty()) {
1749 Split(*queue.back().get(), level);
1755void TxGraphImpl::GroupClusters(
int level)
noexcept
1757 auto& clusterset = GetClusterSet(level);
1759 if (clusterset.m_group_data.has_value())
return;
1769 std::vector<std::pair<Cluster*, uint64_t>> an_clusters;
1774 std::vector<std::pair<std::pair<GraphIndex, GraphIndex>, uint64_t>> an_deps;
1778 for (
int level_iter = 0; level_iter <= level; ++level_iter) {
1779 for (
auto& cluster : GetClusterSet(level_iter).m_clusters[
int(QualityLevel::OVERSIZED_SINGLETON)]) {
1780 auto graph_idx = cluster->GetClusterEntry(0);
1781 auto cur_cluster = FindCluster(graph_idx, level);
1782 if (cur_cluster ==
nullptr)
continue;
1783 an_clusters.emplace_back(cur_cluster, cur_cluster->m_sequence);
1789 an_deps.reserve(clusterset.m_deps_to_add.size());
1790 for (
const auto& [par, chl] : clusterset.m_deps_to_add) {
1791 auto par_cluster = FindCluster(par, level);
1792 auto chl_cluster = FindCluster(chl, level);
1794 if (par_cluster ==
nullptr || chl_cluster ==
nullptr)
continue;
1795 an_clusters.emplace_back(par_cluster, par_cluster->m_sequence);
1798 if (chl_cluster != par_cluster) an_clusters.emplace_back(chl_cluster, chl_cluster->m_sequence);
1800 an_deps.emplace_back(std::pair{par, chl}, chl_cluster->m_sequence);
1804 std::sort(an_clusters.begin(), an_clusters.end(), [](
auto& a,
auto& b)
noexcept { return a.second < b.second; });
1805 an_clusters.erase(std::unique(an_clusters.begin(), an_clusters.end()), an_clusters.end());
1807 std::sort(an_deps.begin(), an_deps.end(), [&](
auto& a,
auto& b)
noexcept { return a.second < b.second; });
1813 struct PartitionData
1821 PartitionData* parent;
1827 std::vector<PartitionData> partition_data;
1830 auto locate_fn = [&](uint64_t
sequence)
noexcept -> PartitionData* {
1831 auto it = std::lower_bound(partition_data.begin(), partition_data.end(),
sequence,
1832 [](
auto& a, uint64_t seq)
noexcept { return a.sequence < seq; });
1833 Assume(it != partition_data.end());
1839 static constexpr auto find_root_fn = [](PartitionData*
data)
noexcept -> PartitionData* {
1843 auto par =
data->parent;
1844 data->parent = par->parent;
1852 static constexpr auto union_fn = [](PartitionData* arg1, PartitionData* arg2)
noexcept {
1855 auto rep1 = find_root_fn(arg1);
1856 auto rep2 = find_root_fn(arg2);
1857 if (rep1 == rep2)
return rep1;
1860 if (rep1->rank < rep2->rank) std::swap(rep1, rep2);
1861 rep2->parent = rep1;
1862 rep1->rank += (rep1->rank == rep2->rank);
1867 partition_data.resize(an_clusters.size());
1868 for (
size_t i = 0; i < an_clusters.size(); ++i) {
1869 partition_data[i].sequence = an_clusters[i].first->m_sequence;
1870 partition_data[i].parent = &partition_data[i];
1871 partition_data[i].rank = 0;
1876 Cluster* last_chl_cluster{
nullptr};
1877 PartitionData* last_partition{
nullptr};
1878 for (
const auto& [dep,
_] : an_deps) {
1879 auto [par, chl] = dep;
1880 auto par_cluster = FindCluster(par, level);
1881 auto chl_cluster = FindCluster(chl, level);
1882 Assume(chl_cluster !=
nullptr && par_cluster !=
nullptr);
1884 if (par_cluster == chl_cluster)
continue;
1886 if (chl_cluster == last_chl_cluster) {
1890 last_partition = union_fn(locate_fn(par_cluster->m_sequence), last_partition);
1892 last_chl_cluster = chl_cluster;
1893 last_partition = union_fn(locate_fn(par_cluster->m_sequence), locate_fn(chl_cluster->m_sequence));
1899 auto deps_it = an_deps.begin();
1900 for (
size_t i = 0; i < partition_data.size(); ++i) {
1901 auto&
data = partition_data[i];
1904 auto rep_seq = find_root_fn(&
data)->sequence;
1905 an_clusters[i].second = rep_seq;
1907 while (deps_it != an_deps.end()) {
1908 auto [par, chl] = deps_it->first;
1909 auto chl_cluster = FindCluster(chl, level);
1910 Assume(chl_cluster !=
nullptr);
1911 if (chl_cluster->m_sequence >
data.sequence)
break;
1912 deps_it->second = rep_seq;
1920 std::sort(an_deps.begin(), an_deps.end(), [](
auto& a,
auto& b)
noexcept { return a.second < b.second; });
1921 std::sort(an_clusters.begin(), an_clusters.end(), [](
auto& a,
auto& b)
noexcept { return a.second < b.second; });
1925 clusterset.m_group_data = GroupData{};
1926 clusterset.m_group_data->m_group_clusters.reserve(an_clusters.size());
1927 clusterset.m_deps_to_add.clear();
1928 clusterset.m_deps_to_add.reserve(an_deps.size());
1929 clusterset.m_oversized =
false;
1930 auto an_deps_it = an_deps.begin();
1931 auto an_clusters_it = an_clusters.begin();
1932 while (an_clusters_it != an_clusters.end()) {
1934 auto rep = an_clusters_it->second;
1936 auto& new_entry = clusterset.m_group_data->m_groups.emplace_back();
1937 new_entry.m_cluster_offset = clusterset.m_group_data->m_group_clusters.size();
1938 new_entry.m_cluster_count = 0;
1939 new_entry.m_deps_offset = clusterset.m_deps_to_add.size();
1940 new_entry.m_deps_count = 0;
1941 uint32_t total_count{0};
1942 uint64_t total_size{0};
1944 while (an_clusters_it != an_clusters.end() && an_clusters_it->second == rep) {
1945 clusterset.m_group_data->m_group_clusters.push_back(an_clusters_it->first);
1946 total_count += an_clusters_it->first->GetTxCount();
1947 total_size += an_clusters_it->first->GetTotalTxSize();
1949 ++new_entry.m_cluster_count;
1952 while (an_deps_it != an_deps.end() && an_deps_it->second == rep) {
1953 clusterset.m_deps_to_add.push_back(an_deps_it->first);
1955 ++new_entry.m_deps_count;
1958 if (total_count > m_max_cluster_count || total_size > m_max_cluster_size) {
1959 clusterset.m_oversized =
true;
1962 Assume(an_deps_it == an_deps.end());
1963 Assume(an_clusters_it == an_clusters.end());
1967void TxGraphImpl::Merge(std::span<Cluster*> to_merge,
int level)
noexcept
1969 Assume(!to_merge.empty());
1971 if (to_merge.size() == 1)
return;
1976 size_t max_size_pos{0};
1977 DepGraphIndex max_size = to_merge[max_size_pos]->GetTxCount();
1978 GetClusterSet(level).m_cluster_usage -= to_merge[max_size_pos]->TotalMemoryUsage();
1980 for (
size_t i = 1; i < to_merge.size(); ++i) {
1981 GetClusterSet(level).m_cluster_usage -= to_merge[i]->TotalMemoryUsage();
1984 if (size > max_size) {
1989 if (max_size_pos != 0) std::swap(to_merge[0], to_merge[max_size_pos]);
1991 size_t start_idx = 1;
1992 Cluster* into_cluster = to_merge[0];
1993 if (total_size > into_cluster->GetMaxTxCount()) {
1997 auto new_cluster = CreateEmptyCluster(total_size);
1998 into_cluster = new_cluster.get();
1999 InsertCluster(level, std::move(new_cluster), QualityLevel::OPTIMAL);
2005 for (
size_t i = start_idx; i < to_merge.size(); ++i) {
2006 into_cluster->Merge(*
this, level, *to_merge[i]);
2007 DeleteCluster(*to_merge[i], level);
2009 into_cluster->Compact();
2010 GetClusterSet(level).m_cluster_usage += into_cluster->TotalMemoryUsage();
2013void TxGraphImpl::ApplyDependencies(
int level)
noexcept
2015 auto& clusterset = GetClusterSet(level);
2017 if (clusterset.m_oversized ==
true)
return;
2019 GroupClusters(level);
2020 Assume(clusterset.m_group_data.has_value());
2022 if (clusterset.m_deps_to_add.empty())
return;
2024 if (clusterset.m_oversized ==
true)
return;
2027 for (
const auto& group_entry : clusterset.m_group_data->m_groups) {
2028 auto cluster_span = std::span{clusterset.m_group_data->m_group_clusters}
2029 .subspan(group_entry.m_cluster_offset, group_entry.m_cluster_count);
2032 for (Cluster*& cluster : cluster_span) {
2033 cluster = PullIn(cluster, cluster->GetLevel(*
this));
2037 Merge(cluster_span, level);
2040 auto deps_span = std::span{clusterset.m_deps_to_add}
2041 .subspan(group_entry.m_deps_offset, group_entry.m_deps_count);
2042 Assume(!deps_span.empty());
2043 const auto& loc = m_entries[deps_span[0].second].m_locator[level];
2045 loc.cluster->ApplyDependencies(*
this, level, deps_span);
2049 clusterset.m_deps_to_add.clear();
2053 clusterset.m_group_data = GroupData{};
2056std::pair<uint64_t, bool> GenericClusterImpl::Relinearize(TxGraphImpl& graph,
int level, uint64_t max_iters)
noexcept
2059 Assume(!NeedsSplitting());
2061 if (IsOptimal())
return {0,
false};
2063 uint64_t rng_seed = graph.m_rng.rand64();
2064 auto [linearization, optimal, cost] =
Linearize(m_depgraph, max_iters, rng_seed, m_linearization, IsTopological());
2070 m_linearization = std::move(linearization);
2072 bool improved =
false;
2074 graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::OPTIMAL);
2076 }
else if (max_iters >= graph.m_acceptable_iters && !IsAcceptable()) {
2077 graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::ACCEPTABLE);
2079 }
else if (!IsTopological()) {
2080 graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_RELINEARIZE);
2084 Updated(graph, level);
2085 return {cost, improved};
2088std::pair<uint64_t, bool> SingletonClusterImpl::Relinearize(TxGraphImpl& graph,
int level, uint64_t max_iters)
noexcept
2096void TxGraphImpl::MakeAcceptable(Cluster& cluster,
int level)
noexcept
2099 if (!cluster.NeedsSplitting() && !cluster.IsAcceptable() && !cluster.IsOversized()) {
2100 cluster.Relinearize(*
this, level, m_acceptable_iters);
2104void TxGraphImpl::MakeAllAcceptable(
int level)
noexcept
2106 ApplyDependencies(level);
2107 auto& clusterset = GetClusterSet(level);
2108 if (clusterset.m_oversized ==
true)
return;
2109 for (
auto quality : {QualityLevel::NEEDS_FIX, QualityLevel::NEEDS_RELINEARIZE}) {
2110 auto& queue = clusterset.m_clusters[int(quality)];
2111 while (!queue.empty()) {
2112 MakeAcceptable(*queue.back().get(), level);
2117GenericClusterImpl::GenericClusterImpl(uint64_t
sequence) noexcept : Cluster{
sequence} {}
2121 Assume(m_main_chunkindex_observers == 0 || GetTopLevel() != 0);
2126 auto idx = m_entries.size();
2127 m_entries.emplace_back();
2128 auto& entry = m_entries.back();
2129 entry.m_main_chunkindex_iterator = m_main_chunkindex.end();
2131 GetRefGraph(
ret) =
this;
2132 GetRefIndex(
ret) = idx;
2134 bool oversized = uint64_t(feerate.
size) > m_max_cluster_size;
2135 auto cluster = CreateEmptyCluster(1);
2136 cluster->AppendTransaction(idx, feerate);
2137 auto cluster_ptr = cluster.get();
2138 int level = GetTopLevel();
2139 auto& clusterset = GetClusterSet(level);
2140 InsertCluster(level, std::move(cluster), oversized ? QualityLevel::OVERSIZED_SINGLETON : QualityLevel::OPTIMAL);
2141 cluster_ptr->Updated(*
this, level);
2142 clusterset.m_cluster_usage += cluster_ptr->TotalMemoryUsage();
2143 ++clusterset.m_txcount;
2146 ++clusterset.m_txcount_oversized;
2147 clusterset.m_oversized =
true;
2148 clusterset.m_group_data = std::nullopt;
2154void TxGraphImpl::RemoveTransaction(
const Ref& arg)
noexcept
2158 if (GetRefGraph(arg) ==
nullptr)
return;
2159 Assume(GetRefGraph(arg) ==
this);
2160 Assume(m_main_chunkindex_observers == 0 || GetTopLevel() != 0);
2162 int level = GetTopLevel();
2163 auto cluster = FindCluster(GetRefIndex(arg), level);
2164 if (cluster ==
nullptr)
return;
2166 auto& clusterset = GetClusterSet(level);
2167 clusterset.m_to_remove.push_back(GetRefIndex(arg));
2169 clusterset.m_group_data.reset();
2170 if (clusterset.m_oversized ==
true) clusterset.m_oversized = std::nullopt;
2173void TxGraphImpl::AddDependency(
const Ref& parent,
const Ref& child)
noexcept
2177 if (GetRefGraph(parent) ==
nullptr || GetRefGraph(child) ==
nullptr)
return;
2178 Assume(GetRefGraph(parent) ==
this && GetRefGraph(child) ==
this);
2179 Assume(m_main_chunkindex_observers == 0 || GetTopLevel() != 0);
2181 if (GetRefIndex(parent) == GetRefIndex(child))
return;
2184 int level = GetTopLevel();
2185 auto par_cluster = FindCluster(GetRefIndex(parent), level);
2186 if (par_cluster ==
nullptr)
return;
2187 auto chl_cluster = FindCluster(GetRefIndex(child), level);
2188 if (chl_cluster ==
nullptr)
return;
2190 auto& clusterset = GetClusterSet(level);
2191 clusterset.m_deps_to_add.emplace_back(GetRefIndex(parent), GetRefIndex(child));
2193 clusterset.m_group_data.reset();
2194 if (clusterset.m_oversized ==
false) clusterset.m_oversized = std::nullopt;
2197bool TxGraphImpl::Exists(
const Ref& arg,
Level level_select)
noexcept
2199 if (GetRefGraph(arg) ==
nullptr)
return false;
2200 Assume(GetRefGraph(arg) ==
this);
2201 size_t level = GetSpecifiedLevel(level_select);
2203 ApplyRemovals(level);
2204 auto cluster = FindCluster(GetRefIndex(arg), level);
2205 return cluster !=
nullptr;
2208void GenericClusterImpl::GetAncestorRefs(
const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>&
args, std::vector<TxGraph::Ref*>& output)
noexcept
2211 SetType ancestors_union;
2213 while (!
args.empty()) {
2214 if (
args.front().first !=
this)
break;
2215 ancestors_union |= m_depgraph.
Ancestors(
args.front().second);
2218 Assume(ancestors_union.Any());
2220 for (
auto idx : ancestors_union) {
2221 const auto& entry = graph.m_entries[m_mapping[idx]];
2222 Assume(entry.m_ref !=
nullptr);
2223 output.push_back(entry.m_ref);
2227void SingletonClusterImpl::GetAncestorRefs(
const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>&
args, std::vector<TxGraph::Ref*>& output)
noexcept
2230 while (!
args.empty()) {
2231 if (
args.front().first !=
this)
break;
2234 const auto& entry = graph.m_entries[m_graph_index];
2235 Assume(entry.m_ref !=
nullptr);
2236 output.push_back(entry.m_ref);
2239void GenericClusterImpl::GetDescendantRefs(
const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>&
args, std::vector<TxGraph::Ref*>& output)
noexcept
2242 SetType descendants_union;
2244 while (!
args.empty()) {
2245 if (
args.front().first !=
this)
break;
2249 Assume(descendants_union.Any());
2251 for (
auto idx : descendants_union) {
2252 const auto& entry = graph.m_entries[m_mapping[idx]];
2253 Assume(entry.m_ref !=
nullptr);
2254 output.push_back(entry.m_ref);
2258void SingletonClusterImpl::GetDescendantRefs(
const TxGraphImpl& graph, std::span<std::pair<Cluster*, DepGraphIndex>>&
args, std::vector<TxGraph::Ref*>& output)
noexcept
2261 GetAncestorRefs(graph,
args, output);
2264bool GenericClusterImpl::GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos)
noexcept
2268 for (
auto& ref : range) {
2269 Assume(start_pos < m_linearization.size());
2270 const auto& entry = graph.m_entries[m_mapping[m_linearization[start_pos++]]];
2271 Assume(entry.m_ref !=
nullptr);
2275 return start_pos == m_linearization.size();
2278bool SingletonClusterImpl::GetClusterRefs(TxGraphImpl& graph, std::span<TxGraph::Ref*> range, LinearizationIndex start_pos)
noexcept
2283 const auto& entry = graph.m_entries[m_graph_index];
2284 Assume(entry.m_ref !=
nullptr);
2285 range[0] = entry.m_ref;
2301void GenericClusterImpl::MakeStagingTransactionsMissing(TxGraphImpl& graph)
noexcept
2305 for (
auto ci : m_linearization) {
2306 GraphIndex idx = m_mapping[ci];
2307 auto& entry = graph.m_entries[idx];
2308 entry.m_locator[1].SetMissing();
2312void SingletonClusterImpl::MakeStagingTransactionsMissing(TxGraphImpl& graph)
noexcept
2315 auto& entry = graph.m_entries[m_graph_index];
2316 entry.m_locator[1].SetMissing();
2320std::vector<TxGraph::Ref*> TxGraphImpl::GetAncestors(
const Ref& arg,
Level level_select)
noexcept
2323 if (GetRefGraph(arg) ==
nullptr)
return {};
2324 Assume(GetRefGraph(arg) ==
this);
2326 size_t level = GetSpecifiedLevel(level_select);
2327 ApplyDependencies(level);
2329 Assume(GetClusterSet(level).m_deps_to_add.empty());
2331 auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), level);
2332 if (cluster ==
nullptr)
return {};
2334 std::pair<Cluster*, DepGraphIndex> match = {cluster, m_entries[GetRefIndex(arg)].m_locator[cluster_level].index};
2335 auto matches = std::span(&match, 1);
2336 std::vector<TxGraph::Ref*>
ret;
2337 cluster->GetAncestorRefs(*
this, matches,
ret);
2341std::vector<TxGraph::Ref*> TxGraphImpl::GetDescendants(
const Ref& arg,
Level level_select)
noexcept
2344 if (GetRefGraph(arg) ==
nullptr)
return {};
2345 Assume(GetRefGraph(arg) ==
this);
2347 size_t level = GetSpecifiedLevel(level_select);
2348 ApplyDependencies(level);
2350 Assume(GetClusterSet(level).m_deps_to_add.empty());
2352 auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), level);
2353 if (cluster ==
nullptr)
return {};
2355 std::pair<Cluster*, DepGraphIndex> match = {cluster, m_entries[GetRefIndex(arg)].m_locator[cluster_level].index};
2356 auto matches = std::span(&match, 1);
2357 std::vector<TxGraph::Ref*>
ret;
2358 cluster->GetDescendantRefs(*
this, matches,
ret);
2362std::vector<TxGraph::Ref*> TxGraphImpl::GetAncestorsUnion(std::span<const Ref* const>
args,
Level level_select)
noexcept
2365 size_t level = GetSpecifiedLevel(level_select);
2366 ApplyDependencies(level);
2368 Assume(GetClusterSet(level).m_deps_to_add.empty());
2371 std::vector<std::pair<Cluster*, DepGraphIndex>> matches;
2372 matches.reserve(
args.size());
2373 for (
auto arg :
args) {
2376 if (GetRefGraph(*arg) ==
nullptr)
continue;
2377 Assume(GetRefGraph(*arg) ==
this);
2379 auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(*arg), level);
2380 if (cluster ==
nullptr)
continue;
2382 matches.emplace_back(cluster, m_entries[GetRefIndex(*arg)].m_locator[cluster_level].index);
2385 std::sort(matches.begin(), matches.end(), [](
auto& a,
auto& b)
noexcept { return CompareClusters(a.first, b.first) < 0; });
2387 std::span match_span(matches);
2388 std::vector<TxGraph::Ref*>
ret;
2389 while (!match_span.empty()) {
2390 match_span.front().first->GetAncestorRefs(*
this, match_span,
ret);
2395std::vector<TxGraph::Ref*> TxGraphImpl::GetDescendantsUnion(std::span<const Ref* const>
args,
Level level_select)
noexcept
2398 size_t level = GetSpecifiedLevel(level_select);
2399 ApplyDependencies(level);
2401 Assume(GetClusterSet(level).m_deps_to_add.empty());
2404 std::vector<std::pair<Cluster*, DepGraphIndex>> matches;
2405 matches.reserve(
args.size());
2406 for (
auto arg :
args) {
2409 if (GetRefGraph(*arg) ==
nullptr)
continue;
2410 Assume(GetRefGraph(*arg) ==
this);
2412 auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(*arg), level);
2413 if (cluster ==
nullptr)
continue;
2415 matches.emplace_back(cluster, m_entries[GetRefIndex(*arg)].m_locator[cluster_level].index);
2418 std::sort(matches.begin(), matches.end(), [](
auto& a,
auto& b)
noexcept { return CompareClusters(a.first, b.first) < 0; });
2420 std::span match_span(matches);
2421 std::vector<TxGraph::Ref*>
ret;
2422 while (!match_span.empty()) {
2423 match_span.front().first->GetDescendantRefs(*
this, match_span,
ret);
2428std::vector<TxGraph::Ref*> TxGraphImpl::GetCluster(
const Ref& arg,
Level level_select)
noexcept
2432 if (GetRefGraph(arg) ==
nullptr)
return {};
2433 Assume(GetRefGraph(arg) ==
this);
2435 size_t level = GetSpecifiedLevel(level_select);
2436 ApplyDependencies(level);
2438 Assume(GetClusterSet(level).m_deps_to_add.empty());
2440 auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), level);
2441 if (cluster ==
nullptr)
return {};
2443 MakeAcceptable(*cluster, cluster_level);
2444 std::vector<TxGraph::Ref*>
ret(cluster->GetTxCount());
2445 cluster->GetClusterRefs(*
this,
ret, 0);
2451 size_t level = GetSpecifiedLevel(level_select);
2452 ApplyRemovals(level);
2453 return GetClusterSet(level).m_txcount;
2456FeePerWeight TxGraphImpl::GetIndividualFeerate(
const Ref& arg)
noexcept
2459 if (GetRefGraph(arg) ==
nullptr)
return {};
2460 Assume(GetRefGraph(arg) ==
this);
2463 Cluster* cluster{
nullptr};
2465 for (level = 0; level <= GetTopLevel(); ++level) {
2468 ApplyRemovals(level);
2469 if (m_entries[GetRefIndex(arg)].m_locator[level].IsPresent()) {
2470 cluster = m_entries[GetRefIndex(arg)].m_locator[level].cluster;
2474 if (cluster ==
nullptr)
return {};
2476 return cluster->GetIndividualFeerate(m_entries[GetRefIndex(arg)].m_locator[level].index);
2479FeePerWeight TxGraphImpl::GetMainChunkFeerate(
const Ref& arg)
noexcept
2482 if (GetRefGraph(arg) ==
nullptr)
return {};
2483 Assume(GetRefGraph(arg) ==
this);
2485 ApplyDependencies(0);
2487 Assume(m_main_clusterset.m_deps_to_add.empty());
2489 auto [cluster, cluster_level] = FindClusterAndLevel(GetRefIndex(arg), 0);
2490 if (cluster ==
nullptr)
return {};
2493 MakeAcceptable(*cluster, cluster_level);
2494 const auto& entry = m_entries[GetRefIndex(arg)];
2495 return entry.m_main_chunk_feerate;
2498bool TxGraphImpl::IsOversized(
Level level_select)
noexcept
2500 size_t level = GetSpecifiedLevel(level_select);
2501 auto& clusterset = GetClusterSet(level);
2502 if (clusterset.m_oversized.has_value()) {
2504 return *clusterset.m_oversized;
2506 ApplyRemovals(level);
2507 if (clusterset.m_txcount_oversized > 0) {
2508 clusterset.m_oversized =
true;
2512 GroupClusters(level);
2514 Assume(clusterset.m_oversized.has_value());
2515 return *clusterset.m_oversized;
2518void TxGraphImpl::StartStaging() noexcept
2521 Assume(!m_staging_clusterset.has_value());
2528 ApplyDependencies(0);
2530 m_staging_clusterset.emplace();
2533 m_staging_clusterset->m_txcount = m_main_clusterset.m_txcount;
2534 m_staging_clusterset->m_txcount_oversized = m_main_clusterset.m_txcount_oversized;
2535 m_staging_clusterset->m_deps_to_add = m_main_clusterset.m_deps_to_add;
2536 m_staging_clusterset->m_group_data = m_main_clusterset.m_group_data;
2537 m_staging_clusterset->m_oversized = m_main_clusterset.m_oversized;
2538 Assume(m_staging_clusterset->m_oversized.has_value());
2539 m_staging_clusterset->m_cluster_usage = 0;
2542void TxGraphImpl::AbortStaging() noexcept
2545 Assume(m_staging_clusterset.has_value());
2548 for (
auto idx : m_staging_clusterset->m_removed) {
2549 m_entries[idx].m_locator[1].SetMissing();
2553 for (
auto& cluster : m_staging_clusterset->m_clusters[quality]) {
2554 cluster->MakeStagingTransactionsMissing(*
this);
2558 m_staging_clusterset.reset();
2560 if (!m_main_clusterset.m_group_data.has_value()) {
2563 if (m_main_clusterset.m_to_remove.empty() && m_main_clusterset.m_txcount_oversized > 0) {
2566 m_main_clusterset.m_oversized =
true;
2568 m_main_clusterset.m_oversized = std::nullopt;
2573void TxGraphImpl::CommitStaging() noexcept
2576 Assume(m_staging_clusterset.has_value());
2577 Assume(m_main_chunkindex_observers == 0);
2580 auto conflicts = GetConflicts();
2581 for (Cluster* conflict : conflicts) {
2582 conflict->Clear(*
this, 0);
2583 DeleteCluster(*conflict, 0);
2587 for (
auto idx : m_staging_clusterset->m_removed) {
2588 m_entries[idx].m_locator[1].SetMissing();
2592 auto& stage_sets = m_staging_clusterset->m_clusters[quality];
2593 while (!stage_sets.empty()) {
2594 stage_sets.back()->MoveToMain(*
this);
2598 m_main_clusterset.m_deps_to_add = std::move(m_staging_clusterset->m_deps_to_add);
2599 m_main_clusterset.m_to_remove = std::move(m_staging_clusterset->m_to_remove);
2600 m_main_clusterset.m_group_data = std::move(m_staging_clusterset->m_group_data);
2601 m_main_clusterset.m_oversized = std::move(m_staging_clusterset->m_oversized);
2602 m_main_clusterset.m_txcount = std::move(m_staging_clusterset->m_txcount);
2603 m_main_clusterset.m_txcount_oversized = std::move(m_staging_clusterset->m_txcount_oversized);
2605 m_staging_clusterset.reset();
2609void GenericClusterImpl::SetFee(TxGraphImpl& graph,
int level,
DepGraphIndex idx, int64_t
fee)
noexcept
2618 if (m_quality == QualityLevel::OVERSIZED_SINGLETON) {
2620 }
else if (IsAcceptable()) {
2621 graph.SetClusterQuality(level, m_quality, m_setindex, QualityLevel::NEEDS_RELINEARIZE);
2623 Updated(graph, level);
2626void SingletonClusterImpl::SetFee(TxGraphImpl& graph,
int level,
DepGraphIndex idx, int64_t
fee)
noexcept
2631 Updated(graph, level);
2634void TxGraphImpl::SetTransactionFee(
const Ref& ref, int64_t
fee)
noexcept
2637 if (GetRefGraph(ref) ==
nullptr)
return;
2638 Assume(GetRefGraph(ref) ==
this);
2639 Assume(m_main_chunkindex_observers == 0);
2641 auto& entry = m_entries[GetRefIndex(ref)];
2642 for (
int level = 0; level < MAX_LEVELS; ++level) {
2643 auto& locator = entry.m_locator[level];
2644 if (locator.IsPresent()) {
2645 locator.cluster->SetFee(*
this, level, locator.index,
fee);
2650std::strong_ordering TxGraphImpl::CompareMainOrder(
const Ref& a,
const Ref& b)
noexcept
2653 Assume(GetRefGraph(a) ==
this);
2654 Assume(GetRefGraph(b) ==
this);
2656 ApplyDependencies(0);
2657 Assume(m_main_clusterset.m_deps_to_add.empty());
2659 const auto& entry_a = m_entries[GetRefIndex(a)];
2660 const auto& entry_b = m_entries[GetRefIndex(b)];
2661 const auto& locator_a = entry_a.m_locator[0];
2662 const auto& locator_b = entry_b.m_locator[0];
2663 Assume(locator_a.IsPresent());
2664 Assume(locator_b.IsPresent());
2665 MakeAcceptable(*locator_a.cluster, 0);
2666 MakeAcceptable(*locator_b.cluster, 0);
2668 return CompareMainTransactions(GetRefIndex(a), GetRefIndex(b));
2671TxGraph::GraphIndex TxGraphImpl::CountDistinctClusters(std::span<const Ref* const> refs,
Level level_select)
noexcept
2673 size_t level = GetSpecifiedLevel(level_select);
2674 ApplyDependencies(level);
2675 auto& clusterset = GetClusterSet(level);
2676 Assume(clusterset.m_deps_to_add.empty());
2678 std::vector<Cluster*> clusters;
2679 clusters.reserve(refs.size());
2680 for (
const Ref* ref : refs) {
2682 if (GetRefGraph(*ref) ==
nullptr)
continue;
2683 Assume(GetRefGraph(*ref) ==
this);
2684 auto cluster = FindCluster(GetRefIndex(*ref), level);
2685 if (cluster !=
nullptr) clusters.push_back(cluster);
2688 std::sort(clusters.begin(), clusters.end(), [](Cluster* a, Cluster* b)
noexcept { return CompareClusters(a, b) < 0; });
2689 Cluster* last{
nullptr};
2691 for (Cluster* cluster : clusters) {
2692 ret += (cluster != last);
2698std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>> TxGraphImpl::GetMainStagingDiagrams() noexcept
2700 Assume(m_staging_clusterset.has_value());
2701 MakeAllAcceptable(0);
2702 Assume(m_main_clusterset.m_deps_to_add.empty());
2703 MakeAllAcceptable(1);
2704 Assume(m_staging_clusterset->m_deps_to_add.empty());
2707 auto main_clusters = GetConflicts();
2708 std::vector<FeeFrac> main_feerates, staging_feerates;
2709 for (Cluster* cluster : main_clusters) {
2710 cluster->AppendChunkFeerates(main_feerates);
2714 for (
const auto& cluster : m_staging_clusterset->m_clusters[quality]) {
2715 cluster->AppendChunkFeerates(staging_feerates);
2719 std::sort(main_feerates.begin(), main_feerates.end(), [](
auto& a,
auto& b) { return a > b; });
2720 std::sort(staging_feerates.begin(), staging_feerates.end(), [](
auto& a,
auto& b) { return a > b; });
2721 return std::make_pair(std::move(main_feerates), std::move(staging_feerates));
2724void GenericClusterImpl::SanityCheck(
const TxGraphImpl& graph,
int level)
const
2731 if (!NeedsSplitting()) {
2737 unsigned chunk_num{0};
2741 LinearizationIndex linindex{0};
2744 for (
auto lin_pos : m_linearization) {
2745 assert(lin_pos < m_mapping.size());
2746 const auto& entry = graph.m_entries[m_mapping[lin_pos]];
2748 m_done.Set(lin_pos);
2749 if (IsTopological()) {
2753 assert(entry.m_locator[level].cluster ==
this);
2754 assert(entry.m_locator[level].index == lin_pos);
2756 if (level == 0 && IsAcceptable()) {
2757 assert(entry.m_main_lin_index == linindex);
2759 if (!linchunking[chunk_num].transactions[lin_pos]) {
2763 assert(entry.m_main_chunk_feerate == linchunking[chunk_num].feerate);
2766 bool is_chunk_end = (chunk_pos == linchunking[chunk_num].transactions.Count());
2767 assert((entry.m_main_chunkindex_iterator != graph.m_main_chunkindex.end()) == is_chunk_end);
2769 auto& chunk_data = *entry.m_main_chunkindex_iterator;
2770 if (m_done == m_depgraph.
Positions() && chunk_pos == 1) {
2771 assert(chunk_data.m_chunk_count == LinearizationIndex(-1));
2773 assert(chunk_data.m_chunk_count == chunk_pos);
2784void SingletonClusterImpl::SanityCheck(
const TxGraphImpl& graph,
int level)
const
2787 Assume(IsOptimal() || IsOversized() || NeedsSplitting());
2789 const auto& entry = graph.m_entries[m_graph_index];
2791 assert(entry.m_locator[level].cluster ==
this);
2792 assert(entry.m_locator[level].index == 0);
2794 if (level == 0 && IsAcceptable()) {
2795 assert(entry.m_main_lin_index == 0);
2796 assert(entry.m_main_chunk_feerate == m_feerate);
2797 assert(entry.m_main_chunkindex_iterator != graph.m_main_chunkindex.end());
2798 auto& chunk_data = *entry.m_main_chunkindex_iterator;
2799 assert(chunk_data.m_chunk_count == LinearizationIndex(-1));
2804void TxGraphImpl::SanityCheck()
const
2807 std::set<GraphIndex> expected_unlinked;
2809 std::set<const Cluster*> expected_clusters[MAX_LEVELS];
2811 std::set<GraphIndex> expected_removed[MAX_LEVELS];
2813 std::set<uint64_t> sequences;
2815 std::set<GraphIndex> expected_chunkindex;
2817 bool compact_possible{
true};
2820 for (GraphIndex idx = 0; idx < m_entries.size(); ++idx) {
2821 const auto& entry = m_entries[idx];
2822 if (entry.m_ref ==
nullptr) {
2824 expected_unlinked.insert(idx);
2827 assert(GetRefGraph(*entry.m_ref) ==
this);
2828 assert(GetRefIndex(*entry.m_ref) == idx);
2830 if (entry.m_main_chunkindex_iterator != m_main_chunkindex.end()) {
2832 assert(entry.m_locator[0].IsPresent());
2833 expected_chunkindex.insert(idx);
2836 bool was_present{
false}, was_removed{
false};
2837 for (
int level = 0; level < MAX_LEVELS; ++level) {
2838 const auto& locator = entry.m_locator[level];
2840 assert(locator.IsMissing() + locator.IsRemoved() + locator.IsPresent() == 1);
2841 if (locator.IsPresent()) {
2845 assert(locator.cluster->GetClusterEntry(locator.index) == idx);
2847 expected_clusters[level].insert(locator.cluster);
2849 }
else if (locator.IsRemoved()) {
2853 assert(was_present && !was_removed);
2855 expected_removed[level].insert(idx);
2862 for (
int level = 0; level <= GetTopLevel(); ++level) {
2863 assert(level < MAX_LEVELS);
2864 auto& clusterset = GetClusterSet(level);
2865 std::set<const Cluster*> actual_clusters;
2866 size_t recomputed_cluster_usage{0};
2870 QualityLevel quality{qual};
2871 const auto& quality_clusters = clusterset.m_clusters[qual];
2873 for (ClusterSetIndex setindex = 0; setindex < quality_clusters.size(); ++setindex) {
2874 const auto& cluster = *quality_clusters[setindex];
2876 assert(cluster.GetTxCount() <= m_max_cluster_count);
2879 assert(cluster.GetTxCount() == 0 || level == cluster.GetLevel(*
this));
2884 assert(cluster.IsOversized() || cluster.GetTotalTxSize() <= m_max_cluster_size);
2886 assert(!cluster.IsOversized() || cluster.GetTxCount() == 1);
2889 assert(cluster.GetTxCount() <= cluster.GetMaxTxCount());
2892 if (!cluster.NeedsSplitting()) {
2893 assert(cluster.GetTxCount() >= cluster.GetMinIntendedTxCount());
2897 assert(cluster.m_sequence < m_next_sequence_counter);
2898 assert(!sequences.contains(cluster.m_sequence));
2899 sequences.insert(cluster.m_sequence);
2902 if (cluster.GetTxCount() != 0) {
2903 actual_clusters.insert(&cluster);
2906 cluster.SanityCheck(*
this, level);
2908 assert(cluster.m_quality == quality);
2909 assert(cluster.m_setindex == setindex);
2911 recomputed_cluster_usage += cluster.TotalMemoryUsage();
2916 assert(clusterset.m_cluster_usage == recomputed_cluster_usage);
2919 for (GraphIndex idx : clusterset.m_to_remove) {
2920 assert(idx < m_entries.size());
2928 for (
auto [par_idx, chl_idx] : clusterset.m_deps_to_add) {
2929 assert(par_idx != chl_idx);
2930 assert(par_idx < m_entries.size());
2931 assert(chl_idx < m_entries.size());
2935 assert(actual_clusters == expected_clusters[level]);
2938 std::set<GraphIndex> actual_removed(clusterset.m_removed.begin(), clusterset.m_removed.end());
2939 for (
auto i : expected_unlinked) {
2944 actual_removed.erase(i);
2945 expected_removed[level].erase(i);
2948 assert(actual_removed == expected_removed[level]);
2951 if (!clusterset.m_deps_to_add.empty()) compact_possible =
false;
2952 if (!clusterset.m_to_remove.empty()) compact_possible =
false;
2953 if (!clusterset.m_removed.empty()) compact_possible =
false;
2957 if (level < GetTopLevel())
assert(clusterset.m_oversized.has_value());
2961 std::set<GraphIndex> actual_unlinked(m_unlinked.begin(), m_unlinked.end());
2962 assert(actual_unlinked == expected_unlinked);
2966 if (compact_possible) {
2967 assert(actual_unlinked.empty());
2971 std::set<GraphIndex> actual_chunkindex;
2973 for (
const auto& chunk : m_main_chunkindex) {
2974 GraphIndex idx = chunk.m_graph_index;
2975 actual_chunkindex.insert(idx);
2976 auto chunk_feerate = m_entries[idx].m_main_chunk_feerate;
2977 if (!last_chunk_feerate.
IsEmpty()) {
2978 assert(FeeRateCompare(last_chunk_feerate, chunk_feerate) >= 0);
2980 last_chunk_feerate = chunk_feerate;
2982 assert(actual_chunkindex == expected_chunkindex);
2985bool TxGraphImpl::DoWork(uint64_t iters)
noexcept
2987 uint64_t iters_done{0};
2990 for (QualityLevel quality : {QualityLevel::NEEDS_FIX, QualityLevel::NEEDS_RELINEARIZE, QualityLevel::ACCEPTABLE}) {
2992 for (
int level = GetTopLevel(); level >= 0; --level) {
2994 if (level == 0 && m_main_chunkindex_observers != 0)
continue;
2995 ApplyDependencies(level);
2996 auto& clusterset = GetClusterSet(level);
2998 if (clusterset.m_oversized ==
true)
continue;
2999 auto& queue = clusterset.m_clusters[int(quality)];
3000 while (!queue.empty()) {
3001 if (iters_done >= iters)
return false;
3005 auto pos = m_rng.
randrange<
size_t>(queue.size());
3006 auto iters_now = iters - iters_done;
3007 if (quality == QualityLevel::NEEDS_FIX || quality == QualityLevel::NEEDS_RELINEARIZE) {
3012 iters_now = std::min(iters_now, m_acceptable_iters);
3014 auto [cost, improved] = queue[pos].get()->Relinearize(*
this, level, iters_now);
3021 if (!improved)
return false;
3031void BlockBuilderImpl::Next() noexcept
3034 if (m_cur_iter == m_graph->m_main_chunkindex.end())
return;
3038 m_cur_cluster =
nullptr;
3039 if (m_cur_iter == m_graph->m_main_chunkindex.end())
break;
3041 const auto& chunk_data = *m_cur_iter;
3042 const auto& chunk_end_entry = m_graph->m_entries[chunk_data.m_graph_index];
3043 m_cur_cluster = chunk_end_entry.m_locator[0].cluster;
3044 m_known_end_of_cluster =
false;
3046 if (!m_excluded_clusters.contains(m_cur_cluster->m_sequence))
break;
3050std::optional<std::pair<std::vector<TxGraph::Ref*>,
FeePerWeight>> BlockBuilderImpl::GetCurrentChunk() noexcept
3052 std::optional<std::pair<std::vector<TxGraph::Ref*>,
FeePerWeight>>
ret;
3054 if (m_cur_iter != m_graph->m_main_chunkindex.end()) {
3056 const auto& chunk_data = *m_cur_iter;
3057 const auto& chunk_end_entry = m_graph->m_entries[chunk_data.m_graph_index];
3058 if (chunk_data.m_chunk_count == LinearizationIndex(-1)) {
3061 ret->first.resize(1);
3062 Assume(chunk_end_entry.m_ref !=
nullptr);
3063 ret->first[0] = chunk_end_entry.m_ref;
3064 m_known_end_of_cluster =
true;
3067 ret->first.resize(chunk_data.m_chunk_count);
3068 auto start_pos = chunk_end_entry.m_main_lin_index + 1 - chunk_data.m_chunk_count;
3069 m_known_end_of_cluster = m_cur_cluster->GetClusterRefs(*m_graph,
ret->first, start_pos);
3072 Assume(!m_known_end_of_cluster || chunk_data.m_chunk_count > 1);
3074 ret->second = chunk_end_entry.m_main_chunk_feerate;
3079BlockBuilderImpl::BlockBuilderImpl(TxGraphImpl& graph) noexcept : m_graph(&graph)
3082 m_graph->MakeAllAcceptable(0);
3084 Assume(m_graph->m_main_clusterset.m_deps_to_add.empty());
3087 ++m_graph->m_main_chunkindex_observers;
3089 m_cur_iter = m_graph->m_main_chunkindex.begin();
3090 m_cur_cluster =
nullptr;
3091 if (m_cur_iter != m_graph->m_main_chunkindex.end()) {
3093 const auto& chunk_data = *m_cur_iter;
3094 const auto& chunk_end_entry = m_graph->m_entries[chunk_data.m_graph_index];
3095 m_cur_cluster = chunk_end_entry.m_locator[0].cluster;
3099BlockBuilderImpl::~BlockBuilderImpl()
3101 Assume(m_graph->m_main_chunkindex_observers > 0);
3103 --m_graph->m_main_chunkindex_observers;
3106void BlockBuilderImpl::Include() noexcept
3113void BlockBuilderImpl::Skip() noexcept
3119 if (m_cur_cluster !=
nullptr && !m_known_end_of_cluster) {
3120 m_excluded_clusters.insert(m_cur_cluster->m_sequence);
3125std::unique_ptr<TxGraph::BlockBuilder> TxGraphImpl::GetBlockBuilder() noexcept
3127 return std::make_unique<BlockBuilderImpl>(*
this);
3130std::pair<std::vector<TxGraph::Ref*>,
FeePerWeight> TxGraphImpl::GetWorstMainChunk() noexcept
3134 MakeAllAcceptable(0);
3135 Assume(m_main_clusterset.m_deps_to_add.empty());
3137 if (!m_main_chunkindex.empty()) {
3138 const auto& chunk_data = *m_main_chunkindex.rbegin();
3139 const auto& chunk_end_entry = m_entries[chunk_data.m_graph_index];
3140 Cluster* cluster = chunk_end_entry.m_locator[0].cluster;
3141 if (chunk_data.m_chunk_count == LinearizationIndex(-1) || chunk_data.m_chunk_count == 1) {
3143 ret.first.resize(1);
3144 Assume(chunk_end_entry.m_ref !=
nullptr);
3145 ret.first[0] = chunk_end_entry.m_ref;
3147 ret.first.resize(chunk_data.m_chunk_count);
3148 auto start_pos = chunk_end_entry.m_main_lin_index + 1 - chunk_data.m_chunk_count;
3149 cluster->GetClusterRefs(*
this,
ret.first, start_pos);
3150 std::reverse(
ret.first.begin(),
ret.first.end());
3152 ret.second = chunk_end_entry.m_main_chunk_feerate;
3157std::vector<TxGraph::Ref*> TxGraphImpl::Trim() noexcept
3159 int level = GetTopLevel();
3160 Assume(m_main_chunkindex_observers == 0 || level != 0);
3161 std::vector<TxGraph::Ref*>
ret;
3164 auto& clusterset = GetClusterSet(level);
3165 if (clusterset.m_oversized ==
false)
return ret;
3166 GroupClusters(level);
3167 Assume(clusterset.m_group_data.has_value());
3169 Assume(clusterset.m_oversized.has_value());
3170 if (clusterset.m_oversized ==
false)
return ret;
3194 std::vector<std::pair<GraphIndex, GraphIndex>> deps_by_parent;
3196 std::vector<std::pair<GraphIndex, GraphIndex>> deps_by_child;
3200 std::vector<TrimTxData> trim_data;
3203 std::vector<std::vector<TrimTxData>::iterator> trim_heap;
3205 std::vector<TrimTxData*> current_deps;
3208 static constexpr auto cmp_fn = [](
auto a,
auto b)
noexcept {
3213 return a->m_chunk_feerate < b->m_chunk_feerate;
3217 static constexpr auto find_fn = [](TrimTxData* arg)
noexcept {
3218 while (arg != arg->m_uf_parent) {
3221 auto par = arg->m_uf_parent;
3222 arg->m_uf_parent = par->m_uf_parent;
3230 static constexpr auto union_fn = [](TrimTxData* arg1, TrimTxData* arg2)
noexcept {
3232 auto rep1 = find_fn(arg1);
3233 auto rep2 = find_fn(arg2);
3236 if (rep1 == rep2)
return rep1;
3239 if (rep1->m_uf_count < rep2->m_uf_count) std::swap(rep1, rep2);
3240 rep2->m_uf_parent = rep1;
3243 rep1->m_uf_size += rep2->m_uf_size;
3244 rep1->m_uf_count += rep2->m_uf_count;
3249 auto locate_fn = [&](GraphIndex index)
noexcept {
3250 auto it = std::lower_bound(trim_data.begin(), trim_data.end(), index, [](TrimTxData& elem, GraphIndex idx)
noexcept {
3251 return elem.m_index < idx;
3253 Assume(it != trim_data.end() && it->m_index == index);
3258 for (
const auto& group_data : clusterset.m_group_data->m_groups) {
3261 deps_by_child.clear();
3262 deps_by_parent.clear();
3265 auto cluster_span = std::span{clusterset.m_group_data->m_group_clusters}
3266 .subspan(group_data.m_cluster_offset, group_data.m_cluster_count);
3268 for (Cluster* cluster : cluster_span) {
3269 MakeAcceptable(*cluster, cluster->GetLevel(*
this));
3270 size += cluster->AppendTrimData(trim_data, deps_by_child);
3273 if (trim_data.size() <= m_max_cluster_count && size <= m_max_cluster_size)
continue;
3277 std::sort(trim_data.begin(), trim_data.end(), [](
auto& a,
auto& b)
noexcept { return a.m_index < b.m_index; });
3280 deps_by_child.insert(deps_by_child.end(),
3281 clusterset.m_deps_to_add.begin() + group_data.m_deps_offset,
3282 clusterset.m_deps_to_add.begin() + group_data.m_deps_offset + group_data.m_deps_count);
3286 std::sort(deps_by_child.begin(), deps_by_child.end(), [](
auto& a,
auto& b)
noexcept { return a.second < b.second; });
3290 auto deps_it = deps_by_child.begin();
3291 for (
auto trim_it = trim_data.begin(); trim_it != trim_data.end(); ++trim_it) {
3292 trim_it->m_parent_offset = deps_it - deps_by_child.begin();
3293 trim_it->m_deps_left = 0;
3294 while (deps_it != deps_by_child.end() && deps_it->second == trim_it->m_index) {
3295 ++trim_it->m_deps_left;
3298 trim_it->m_parent_count = trim_it->m_deps_left;
3301 if (trim_it->m_deps_left == 0 && trim_it->m_tx_size <= m_max_cluster_size) {
3302 trim_heap.push_back(trim_it);
3305 Assume(deps_it == deps_by_child.end());
3309 deps_by_parent = deps_by_child;
3310 std::sort(deps_by_parent.begin(), deps_by_parent.end(), [](
auto& a,
auto& b)
noexcept { return a.first < b.first; });
3314 deps_it = deps_by_parent.begin();
3315 for (
auto& trim_entry : trim_data) {
3316 trim_entry.m_children_count = 0;
3317 trim_entry.m_children_offset = deps_it - deps_by_parent.begin();
3318 while (deps_it != deps_by_parent.end() && deps_it->first == trim_entry.m_index) {
3319 ++trim_entry.m_children_count;
3323 Assume(deps_it == deps_by_parent.end());
3326 std::make_heap(trim_heap.begin(), trim_heap.end(), cmp_fn);
3340 while (!trim_heap.empty()) {
3342 std::pop_heap(trim_heap.begin(), trim_heap.end(), cmp_fn);
3344 auto& entry = *trim_heap.back();
3345 trim_heap.pop_back();
3348 entry.m_uf_parent = &entry;
3349 entry.m_uf_count = 1;
3350 entry.m_uf_size = entry.m_tx_size;
3353 current_deps.clear();
3354 for (
auto& [par, chl] : std::span{deps_by_child}.subspan(entry.m_parent_offset, entry.m_parent_count)) {
3355 Assume(chl == entry.m_index);
3356 current_deps.push_back(find_fn(&*locate_fn(par)));
3358 std::sort(current_deps.begin(), current_deps.end());
3359 current_deps.erase(std::unique(current_deps.begin(), current_deps.end()), current_deps.end());
3362 uint32_t new_count = 1;
3363 uint64_t new_size = entry.m_tx_size;
3364 for (TrimTxData* ptr : current_deps) {
3365 new_count += ptr->m_uf_count;
3366 new_size += ptr->m_uf_size;
3369 if (new_count > m_max_cluster_count || new_size > m_max_cluster_size)
continue;
3373 for (TrimTxData* ptr : current_deps) rep = union_fn(ptr, rep);
3375 entry.m_deps_left = uint32_t(-1);
3377 for (
auto& [par, chl] : std::span{deps_by_parent}.subspan(entry.m_children_offset, entry.m_children_count)) {
3378 Assume(par == entry.m_index);
3379 auto chl_it = locate_fn(chl);
3382 Assume(chl_it->m_deps_left > 0);
3383 if (--chl_it->m_deps_left == 0) {
3384 trim_heap.push_back(chl_it);
3385 std::push_heap(trim_heap.begin(), trim_heap.end(), cmp_fn);
3394 for (
const auto& trim_entry : trim_data) {
3395 if (trim_entry.m_deps_left != uint32_t(-1)) {
3396 ret.push_back(m_entries[trim_entry.m_index].m_ref);
3397 clusterset.m_to_remove.push_back(trim_entry.m_index);
3401 clusterset.m_group_data.reset();
3402 clusterset.m_oversized =
false;
3407size_t TxGraphImpl::GetMainMemoryUsage() noexcept
3411 ApplyDependencies(0);
3414 m_main_clusterset.m_cluster_usage +
3416 sizeof(Entry) * m_main_clusterset.m_txcount +
3428 m_graph->UnlinkRef(m_index);
3436 if (other.m_graph) other.m_graph->UpdateRef(other.m_index, *
this);
3438 std::swap(m_graph, other.m_graph);
3439 std::swap(m_index, other.m_index);
3442std::unique_ptr<TxGraph>
MakeTxGraph(
unsigned max_cluster_count, uint64_t max_cluster_size, uint64_t acceptable_iters)
noexcept
3444 return std::make_unique<TxGraphImpl>(max_cluster_count, max_cluster_size, acceptable_iters);
std::conditional_t<(BITS<=32), bitset_detail::IntBitSet< uint32_t >, std::conditional_t<(BITS<=std::numeric_limits< size_t >::digits), bitset_detail::IntBitSet< size_t >, bitset_detail::MultiIntBitSet< size_t,(BITS+std::numeric_limits< size_t >::digits - 1)/std::numeric_limits< size_t >::digits > > > BitSet
#define Assume(val)
Assume is the identity function.
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Interface returned by GetBlockBuilder.
virtual ~Ref()
Destroy this Ref.
Ref() noexcept=default
Construct an empty Ref.
Data structure to encapsulate fees, sizes, and dependencies for a set of transactions.
uint32_t GraphIndex
Internal identifier for a transaction within a TxGraph.
Data structure that holds a transaction graph's preprocessed data (fee, size, ancestors,...
const SetType & Ancestors(DepGraphIndex i) const noexcept
Get the ancestors of a given transaction i.
SetType GetReducedParents(DepGraphIndex i) const noexcept
Compute the (reduced) set of parents of node i in this graph.
const FeeFrac & FeeRate(DepGraphIndex i) const noexcept
Get the feerate of a given transaction i.
bool IsConnected(const SetType &subset) const noexcept
Determine if a subset is connected.
DepGraphIndex PositionRange() const noexcept
Get the range of positions in this DepGraph.
SetType FindConnectedComponent(const SetType &todo) const noexcept
Find some connected component within the subset "todo" of this graph.
DepGraphIndex AddTransaction(const FeeFrac &feefrac) noexcept
Add a new unconnected transaction to this transaction graph (in the first available position),...
void RemoveTransactions(const SetType &del) noexcept
Remove the specified positions from this DepGraph.
auto TxCount() const noexcept
Get the number of transactions in the graph.
const SetType & Descendants(DepGraphIndex i) const noexcept
Get the descendants of a given transaction i.
size_t DynamicMemoryUsage() const noexcept
const SetType & Positions() const noexcept
Get the set of transactions positions in use.
void Compact() noexcept
Reduce memory usage if possible.
void AddDependencies(const SetType &parents, DepGraphIndex child) noexcept
Modify this transaction graph, adding multiple parents to a specified child.
bool IsAcyclic() const noexcept
Check if this graph is acyclic.
std::tuple< std::vector< DepGraphIndex >, bool, uint64_t > Linearize(const DepGraph< SetType > &depgraph, uint64_t max_iterations, uint64_t rng_seed, std::span< const DepGraphIndex > old_linearization={}, bool is_topological=true) noexcept
Find or improve a linearization for a cluster.
std::vector< FeeFrac > ChunkLinearization(const DepGraph< SetType > &depgraph, std::span< const DepGraphIndex > linearization) noexcept
Compute the feerates of the chunks of linearization.
uint32_t DepGraphIndex
Data type to represent transaction indices in DepGraphs and the clusters they represent.
void PostLinearize(const DepGraph< SetType > &depgraph, std::span< DepGraphIndex > linearization)
Improve a given linearization.
std::vector< SetInfo< SetType > > ChunkLinearizationInfo(const DepGraph< SetType > &depgraph, std::span< const DepGraphIndex > linearization) noexcept
Compute the chunks of linearization as SetInfos.
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
std::vector< T > Split(const std::span< const char > &sp, std::string_view separators, bool include_sep=false)
Split a string on any char found in separators, returning a vector.
Data structure storing a fee and size, ordered by increasing fee/size.
bool IsEmpty() const noexcept
Check if this is empty (size and fee are 0).
Tagged wrapper around FeeFrac to avoid unit confusion.
static FeePerUnit FromFeeFrac(const FeeFrac &feefrac) noexcept
Convert a FeeFrac to a FeePerUnit.
consteval auto _(util::TranslatedLiteral str)
std::unique_ptr< TxGraph > MakeTxGraph(unsigned max_cluster_count, uint64_t max_cluster_size, uint64_t acceptable_iters) noexcept
Construct a new TxGraph with the specified limit on the number of transactions within a cluster,...
static constexpr unsigned MAX_CLUSTER_COUNT_LIMIT
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.