Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_TEST_UTIL_CLUSTER_LINEARIZE_H6#define BITCOIN_TEST_UTIL_CLUSTER_LINEARIZE_H8#include <cluster_linearize.h>9#include <serialize.h>10#include <span.h>11#include <streams.h>12#include <util/bitset.h>13#include <util/feefrac.h>15#include <cstdint>16#include <numeric>17#include <utility>18#include <vector>20namespace cluster_linearize {22using TestBitSet = BitSet<32>;24/** A formatter for a bespoke serialization for acyclic DepGraph objects.25*26* The serialization format outputs information about transactions in a topological order (parents27* before children), together with position information so transactions can be moved back to their28* correct position on deserialization.29*30* - For each transaction t in the DepGraph (in some topological order);31* - The size: VARINT(t.size), which cannot be 0.32* - The fee: VARINT(SignedToUnsigned(t.fee)), see below for SignedToUnsigned.33* - For each direct dependency:34* - VARINT(skip)35* - The position of t in the cluster: VARINT(skip)36* - The end of the graph: VARINT(0)37*38* The list of skip values encodes the dependencies of t, as well as its position in the cluster.39* Each skip value is the number of possibilities that were available, but were not taken. These40* possibilities are, in order:41* - For each previous transaction in the graph, in reverse serialization order, whether it is a42* direct parent of t (but excluding transactions which are already implied to be dependencies43* by parent relations that were serialized before it).44* - The various insertion positions in the cluster, from the very end of the cluster, to the45* front.46* - The appending of 1, 2, 3, ... holes at the end of the cluster, followed by appending the new47* transaction.48*49* Let's say you have a 7-transaction cluster, consisting of transactions F,A,C,B,_,G,E,_,D50* (where _ represent holes; unused positions within the DepGraph) but serialized in order51* A,B,C,D,E,F,G, because that happens to be a topological ordering. By the time G gets serialized,52* what has been serialized already represents the cluster F,A,C,B,_,E,_,D (in that order). G has B53* and E as direct parents, and E depends on C.54*55* In this case, the possibilities are, in order:56* - [ ] the dependency G->F57* - [X] the dependency G->E58* - [ ] the dependency G->D59* - [X] the dependency G->B60* - [ ] the dependency G->A61* - [ ] put G at the end of the cluster62* - [ ] put G before D63* - [ ] put G before the hole before D64* - [X] put G before E65* - [ ] put G before the hole before E66* - [ ] put G before B67* - [ ] put G before C68* - [ ] put G before A69* - [ ] put G before F70* - [ ] add 1 hole at the end of the cluster, followed by G71* - [ ] add 2 holes at the end of the cluster, followed by G72* - [ ] add ...73*74* The skip values in this case are 1 (G->F), 1 (G->D), 4 (G->A, G at end, G before D, G before75* hole). No skip after 4 is needed (or permitted), because there can only be one position for G.76* Also note that G->C is not included in the list of possibilities, as it is implied by the77* included G->E and E->C that came before it. On deserialization, if the last skip value was 8 or78* larger (putting G before the beginning of the cluster), it is interpreted as wrapping around79* back to the end.80*81*82* Rationale:83* - Why VARINTs? They are flexible enough to represent large numbers where needed, but more84* compact for smaller numbers. The serialization format is designed so that simple structures85* involve smaller numbers, so smaller size maps to simpler graphs.86* - Why use SignedToUnsigned? It results in small unsigned values for signed values with small87* absolute value. This way we can encode negative fees in graphs, but still let small negative88* numbers have small encodings.89* - Why are the parents emitted in reverse order compared to the transactions themselves? This90* naturally lets us skip parents-of-parents, as they will be reflected as implied dependencies.91* - Why encode skip values and not a bitmask to convey the list positions? It turns out that the92* most complex graphs (in terms of linearization complexity) are ones with ~1 dependency per93* transaction. The current encoding uses ~1 byte per transaction for dependencies in this case,94* while a bitmask would require ~N/2 bits per transaction.95*/97struct DepGraphFormatter98{99/** Convert x>=0 to 2x (even), x<0 to -2x-1 (odd). */100static uint64_t SignedToUnsigned(int64_t x) noexcept101{102if (x < 0) {103return 2 * uint64_t(-(x + 1)) + 1;104} else {105return 2 * uint64_t(x);106}107}109/** Convert even x to x/2 (>=0), odd x to -(x/2)-1 (<0). */110static int64_t UnsignedToSigned(uint64_t x) noexcept111{112if (x & 1) {113return -int64_t(x / 2) - 1;114} else {115return int64_t(x / 2);116}117}119template <typename Stream, typename SetType>120static void Ser(Stream& s, const DepGraph<SetType>& depgraph)121{122/** Construct a topological order to serialize the transactions in. */123std::vector<DepGraphIndex> topo_order;124topo_order.reserve(depgraph.TxCount());125for (auto i : depgraph.Positions()) topo_order.push_back(i);126std::sort(topo_order.begin(), topo_order.end(), [&](DepGraphIndex a, DepGraphIndex b) {127auto anc_a = depgraph.Ancestors(a).Count(), anc_b = depgraph.Ancestors(b).Count();128if (anc_a != anc_b) return anc_a < anc_b;129return a < b;130});132/** Which positions (incl. holes) the deserializer already knows when it has deserialized133* what has been serialized here so far. */134SetType done;136// Loop over the transactions in topological order.137for (DepGraphIndex topo_idx = 0; topo_idx < topo_order.size(); ++topo_idx) {138/** Which depgraph index we are currently writing. */139DepGraphIndex idx = topo_order[topo_idx];140// Write size, which must be larger than 0.141s << VARINT_MODE(depgraph.FeeRate(idx).size, VarIntMode::NONNEGATIVE_SIGNED);142// Write fee, encoded as an unsigned varint (odd=negative, even=non-negative).143s << VARINT(SignedToUnsigned(depgraph.FeeRate(idx).fee));144// Write dependency information.145SetType written_parents;146uint64_t diff = 0; //!< How many potential parent/child relations we have skipped over.147for (DepGraphIndex dep_dist = 0; dep_dist < topo_idx; ++dep_dist) {148/** Which depgraph index we are currently considering as parent of idx. */149DepGraphIndex dep_idx = topo_order[topo_idx - 1 - dep_dist];150// Ignore transactions which are already known to be ancestors.151if (depgraph.Descendants(dep_idx).Overlaps(written_parents)) continue;152if (depgraph.Ancestors(idx)[dep_idx]) {153// When an actual parent is encountered, encode how many non-parents were skipped154// before it.155s << VARINT(diff);156diff = 0;157written_parents.Set(dep_idx);158} else {159// When a non-parent is encountered, increment the skip counter.160++diff;161}162}163// Write position information.164auto add_holes = SetType::Fill(idx) - done - depgraph.Positions();165if (add_holes.None()) {166// The new transaction is to be inserted N positions back from the end of the167// cluster. Emit N to indicate that that many insertion choices are skipped.168auto skips = (done - SetType::Fill(idx)).Count();169s << VARINT(diff + skips);170} else {171// The new transaction is to be appended at the end of the cluster, after N holes.172// Emit current_cluster_size + N, to indicate all insertion choices are skipped,173// plus N possibilities for the number of holes.174s << VARINT(diff + done.Count() + add_holes.Count());175done |= add_holes;176}177done.Set(idx);178}180// Output a final 0 to denote the end of the graph.181s << uint8_t{0};182}184template <typename Stream, typename SetType>185void Unser(Stream& s, DepGraph<SetType>& depgraph)186{187/** The dependency graph which we deserialize into first, with transactions in188* topological serialization order, not original cluster order. */189DepGraph<SetType> topo_depgraph;190/** Mapping from serialization order to cluster order, used later to reconstruct the191* cluster order. */192std::vector<DepGraphIndex> reordering;193/** How big the entries vector in the reconstructed depgraph will be (including holes). */194DepGraphIndex total_size{0};196// Read transactions in topological order.197while (true) {198FeeFrac new_feerate; //!< The new transaction's fee and size.199SetType new_ancestors; //!< The new transaction's ancestors (excluding itself).200uint64_t diff{0}; //!< How many potential parents/insertions we have to skip.201bool read_error{false};202try {203// Read size. Size 0 signifies the end of the DepGraph.204int32_t size;205s >> VARINT_MODE(size, VarIntMode::NONNEGATIVE_SIGNED);206size &= 0x3FFFFF; // Enough for size up to 4M.207static_assert(0x3FFFFF >= 4000000);208if (size == 0 || topo_depgraph.TxCount() == SetType::Size()) break;209// Read fee, encoded as an unsigned varint (odd=negative, even=non-negative).210uint64_t coded_fee;211s >> VARINT(coded_fee);212coded_fee &= 0xFFFFFFFFFFFFF; // Enough for fee between -21M...21M BTC.213static_assert(0xFFFFFFFFFFFFF > uint64_t{2} * 21000000 * 100000000);214new_feerate = {UnsignedToSigned(coded_fee), size};215// Read dependency information.216auto topo_idx = reordering.size();217s >> VARINT(diff);218for (DepGraphIndex dep_dist = 0; dep_dist < topo_idx; ++dep_dist) {219/** Which topo_depgraph index we are currently considering as parent of topo_idx. */220DepGraphIndex dep_topo_idx = topo_idx - 1 - dep_dist;221// Ignore transactions which are already known ancestors of topo_idx.222if (new_ancestors[dep_topo_idx]) continue;223if (diff == 0) {224// When the skip counter has reached 0, add an actual dependency.225new_ancestors |= topo_depgraph.Ancestors(dep_topo_idx);226// And read the number of skips after it.227s >> VARINT(diff);228} else {229// Otherwise, dep_topo_idx is not a parent. Decrement and continue.230--diff;231}232}233} catch (const std::ios_base::failure&) {234// Continue even if a read error was encountered.235read_error = true;236}237// Construct a new transaction whenever we made it past the new_feerate construction.238if (new_feerate.IsEmpty()) break;239assert(reordering.size() < SetType::Size());240auto topo_idx = topo_depgraph.AddTransaction(new_feerate);241topo_depgraph.AddDependencies(new_ancestors, topo_idx);242if (total_size < SetType::Size()) {243// Normal case.244diff %= SetType::Size();245if (diff <= total_size) {246// Insert the new transaction at distance diff back from the end.247for (auto& pos : reordering) {248pos += (pos >= total_size - diff);249}250reordering.push_back(total_size++ - diff);
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.