polycratia

A coin selection policy is a filter and a sort, not a strategy

· 10 min read

Your wallet is a pile of outputs, and a payment has to be assembled out of some subset of them. Once the arithmetic works (cover the targets, price the size, compute change), three requirements show up that look like they want algorithms of their own: do not spend an output that is not buried deeply enough, do not tie more of the wallet together than the payment needs, and sweep small outputs up while blocks are cheap. None of the three is an algorithm. Each one only changes which outputs are in play and the order they get tried, and committing to that in the types is what keeps the strategy list from multiplying.

I work this out in the open in utxo-select, a pre-alpha coin selection library in Python. The code below comes from it.

The version that multiplies#

Say confirmation depth is a strategy. Now you have select_largest_first and some confirmed variant of it, and the second one is the first one with a comprehension at the top. Say consolidation is a strategy too. Now there are four. Branch-and-bound needs the same four, and the eight have to agree about one more thing: branch-and-bound does not always find a match, so it falls back to largest-first. Which largest-first? A caller who asked for the confirmed, consolidating search needs the confirmed, consolidating fallback, or the wallet quietly spends a mempool output on exactly the path nobody tested. Each new axis multiplies the pairings somebody keeps consistent by hand, and the fallback is where the inconsistency hides, because it only runs when the fast path failed.

The way out is to notice that none of the three requirements touches the search. The search asks for candidates and takes them in the order it is given. So the policy becomes a parameter of the strategies you already have rather than a strategy of its own:

python
def select_largest_first(
    utxos: Iterable[Utxo],
    request: SelectionRequest,
    *,
    policy: SelectionPolicy = DEFAULT_POLICY,
) -> Selection | SelectionFailure:
    ...

select_branch_and_bound has the same keyword with the same default. Neither body branches on the policy anywhere, and the fallback hands the policy it was given straight down to largest-first. Two strategies, one policy type, and the fallback comes out correct by construction instead of by review.

Two predicates and three fields#

The policy is a frozen value object. It answers two questions and nothing else.

python
@dataclass(frozen=True, slots=True)
class SelectionPolicy:
    min_confirmations: int = 0
    input_preference: InputPreference = InputPreference.FEWER_INPUTS
    consolidation_fee_rate: int = DEFAULT_CONSOLIDATION_FEE_RATE

    def accepts(self, utxo: Utxo) -> bool:
        """Whether this output is confirmed deeply enough to be spent."""
        return utxo.confirmations >= self.min_confirmations

    def consolidates_at(self, fee_rate: int) -> bool:
        """Whether small outputs are taken first at this fee rate."""
        if self.input_preference is InputPreference.MORE_INPUTS:
            return True
        if self.input_preference is InputPreference.CONSOLIDATE_WHEN_CHEAP:
            return fee_rate <= self.consolidation_fee_rate
        return False

accepts is eligibility, one output at a time. consolidates_at is direction, one boolean for the whole selection. That is the entire surface.

Validation happens once, in __post_init__. Both integer fields go through an internal int check with a minimum of zero, so a negative depth is a ValueError, and a bool, a float or a string is a TypeError. True is not an acceptable min_confirmations even though Python would happily compare it. An input_preference that is not an InputPreference is a TypeError too. After construction the object is immutable, and that matters: within one call the same policy instance is read by the strategy, by the candidate filter and by the failure explainer.

The default deserves saying out loud, in plain text where you can see it. min_confirmations is zero, so the policy you get without asking will spend an output that is still sitting in the mempool. Deliberate, that one. Spend anything, largest first. It is also the first thing I would change in a wallet that holds other people's money.

One function applies both#

Everything the policy does to a selection happens here, before any strategy sees a candidate:

python
eligible = [
    utxo
    for utxo in candidates
    if policy.accepts(utxo) and _effective_value(utxo, request.fee_rate) > 0
]
if policy.consolidates_at(request.fee_rate):
    return tuple(sorted(eligible, key=lambda u: (u.value, u.outpoint)))
return tuple(sorted(eligible, key=lambda u: (-u.value, u.outpoint)))

Three details in five lines.

The dust drop sits beside policy.accepts rather than inside it. An output that costs at least as much to spend as it holds gets removed whichever way the policy leans, because spending it moves a selection further from covering the targets rather than closer. That test is priced from the request's fee rate, which is why it is not a policy field. The same output is worth spending at one rate and worthless at another. With the library's legacy defaults an input is 148 virtual bytes, so at fee_rate=12_000 per 1000 vbytes it costs 1_776 to move, and an output holding 900 is not a small contribution, it is a negative one.

Ties break on outpoint. Sorting by value alone leaves equal-valued outputs in whatever order the caller's iterable happened to produce, which means the same wallet can hand you a different transaction depending on how the candidates came out of the database that morning. Adding the outpoint as a secondary key makes the selection a pure function of the wallet contents, the request and the policy. I have spent enough time reconciling payment systems to treat that as a correctness property, full stop: a decision you cannot reproduce from stored inputs is a decision you cannot audit, and "the rows came back in a different order" is not an explanation anybody accepts.

Branch-and-bound does not re-derive any of this. It takes the same filtered, policy-ordered pool and re-sorts it by effective value in the same direction, so a consolidating policy still sweeps upward inside the search.

One threshold flips the order, with no new code path#

CONSOLIDATE_WHEN_CHEAP is the case that would have forced a new strategy in the multiplying design. It does not, because the direction is already a boolean computed from the request:

python
policy = SelectionPolicy(
    input_preference=InputPreference.CONSOLIDATE_WHEN_CHEAP,
    consolidation_fee_rate=2_000,
)

wallet = [
    Utxo(txid="a" * 64, vout=0, value=30_000, confirmations=6),
    Utxo(txid="b" * 64, vout=0, value=40_000, confirmations=6),
    Utxo(txid="c" * 64, vout=0, value=50_000, confirmations=6),
    Utxo(txid="d" * 64, vout=0, value=90_000, confirmations=6),
]


def request(fee_rate):
    return SelectionRequest(
        targets=(Target(value=100_000),),
        fee_rate=fee_rate,
        change_policy=ChangePolicy.ALLOW_CHANGE,
    )

At fee_rate=1_000 and at 2_000 the selection is 30_000 + 40_000 + 50_000: three inputs, the small ones gone. At 5_000 it is 50_000 + 90_000, two inputs, the small ones left alone. The switch is inclusive at the threshold, and above it the behaviour is FEWER_INPUTS exactly, down to the identical sort key.

Consolidating costs real money, and the library's own README measures it on a different wallet at fee_rate=12_000:

Selection Inputs vsize fee change
select_largest_first 200_000 226 2_712 97_288
select_branch_and_bound 102_400 192 2_400 none
select_largest_first, MORE_INPUTS 12_000 + 45_000 + 102_400 522 6_264 53_136

More than twice the baseline fee to sweep three outputs into one spend. That is the whole argument for gating it on a rate instead of a flag somebody sets once and forgets.

A filter has to confess what it held back#

Filtering before the algorithm brings in one failure mode that a strategy-per-requirement design does not have: the strategy can now fail while looking at a wallet that would have paid. Compute the explanation from the eligible candidates alone and it reports a funding problem, and then you go looking for money you already have.

So the failure explanation looks at the withheld set too. It recomputes the fee as if the withheld outputs had been spent alongside the eligible ones, and only if that total would have covered the bill does it report a depth problem:

python
result = select_largest_first(
    [utxo(50_000, confirmations=6), utxo(100_000, confirmations=0, tag="b")],
    request(120_000),
    policy=SelectionPolicy(min_confirmations=1),
)

assert result.reason is FailureReason.INSUFFICIENT_CONFIRMATIONS
assert result.eligible_count == 1
assert result.withheld_count == 1
assert result.withheld_value == 100_000
assert result.shortfall == 70_192

Shrink the shallow output to 10_000 and the same call reports INSUFFICIENT_FUNDS with a shortfall of 70_000, still carrying withheld_value so you can see what got excluded. That distinction is the difference between "wait" and "fund the wallet", and it exists only because the filter keeps a record of its own effect. A filter that forgets what it removed produces honest-looking lies.

What a policy cannot say#

This is the cost, and it is not small. Eligibility is a predicate on one output. Order is a total ordering of all of them. Anything that depends on the chosen subset is inexpressible. "These two outputs may both be spent, but not in the same transaction." "At most four inputs." "Prefer not to combine outputs that an observer could already group." None of those is a filter and none is a sort, and none of them can be bolted onto SelectionPolicy without making accepts a predicate the strategy is allowed to violate.

Notice what is deliberately kept off the policy as well: change. Whether a selection may create a change output is a field on the request rather than the policy, because it constrains the output side of the transaction, a different part of the problem from which candidates are in play. To a caller the two look like the same kind of knob. Structurally they are unrelated.

A requirement that has to examine the selected set needs a strategy, or a constraint the strategy enforces as it builds, a different mechanism with a different contract. The honest version of this design: "policies are exactly two predicates, and anything else is somebody else's job."

What I would do differently#

I would resist consolidates_at(fee_rate) a little harder, or at least name what it opens. It is the one place where the policy reads the request, and that is step one toward a policy that wants to read more of it, then the candidate set, then the partial selection ... at which point it is a strategy wearing a value object's name. The threshold earns its place because it is the whole point of CONSOLIDATE_WHEN_CHEAP, but the next field that needs request access, I would want it to justify itself twice.

The other thing I would do soon: write the property test that runs both strategies under randomised policies and checks that every returned selection balances, covers its reported fee and never returns change below the dust threshold. Probably the policy is not going to break those properties. A design whose selling point is "the algorithms are identical under every policy" should still have something other than my reading of the code asserting it.

The filter-and-sort factoring is not clever. It is the smallest shape that covers the three requirements I actually had, and it is worth writing down because the obvious alternative (one function per requirement) fails quietly, and only in the fallback.

react

$ new-project --brief

or email hey@polycratia.com