Skip to content

fix(policy): bound threshold combination enumeration - #598

Open
j-kon wants to merge 2 commits into
bitcoindevkit:masterfrom
j-kon:fix/policy-bounded-combinations
Open

j-kon wants to merge 2 commits into
bitcoindevkit:masterfrom
j-kon:fix/policy-bounded-combinations

Conversation

@j-kon

@j-kon j-kon commented Oct 13, 2026 •

Copy link
Copy Markdown

Summary

Policy extraction in Satisfaction::finalize eagerly materializes all $m$-of-$n$ combinations and expands Cartesian condition alternatives via mix(). For large threshold descriptors (such as Taproot multi_a), this causes combinatorial explosion in memory and CPU execution time (e.g. 12-of-24 requires ~2.7 million combinations and takes seconds/gigabytes).

Because Satisfaction::PartialComplete publicly exposes a concrete FoldedConditionMap, replacing the map with a lazy iterator is not possible without breaking changes to the public API representation.

This PR introduces an explicit safeguard:

  • Upper bound of MAX_POLICY_COMBINATIONS = 200_000 candidates per threshold node.
  • Exact combination count and Cartesian condition expansion are checked ahead of allocation using dynamic programming with bounded arithmetic:
    • DP states use u128 with saturating operations clamped to cap = budget + 1.
    • Intermediate states can grow large (e.g. $C(68, 34) \approx 2.85 \times 10^{19} > \text{u64::MAX}$ or $C(36, 18) > \text{u32::MAX}$ on 32-bit systems) even when the final threshold count near $n$ is small ($C(68, 67) = 68$). Clamping intermediate DP states to budget + 1 prevents false rejection while guaranteeing mathematically exact answers whenever the final combination count is at or below the budget.
    • When the candidate enumeration budget is exceeded, extraction fails fast with PolicyError::ThresholdCombinationsExceeded.
    • Accepted policies within budget preserve their exact folded conditions and deterministic ordering.

Limitations & Design Notes

  1. Per-node allocation limit: The safeguard bounds candidate enumeration per policy threshold node (Satisfaction::Partial), not globally across the entire descriptor tree. For descriptors with multiple independent or nested threshold sub-policies, each node is capped at 200,000 candidate combinations.
  2. Compatibility: Adds PolicyError::ThresholdCombinationsExceeded to PolicyError. Since PolicyError is currently not marked #[non_exhaustive], downstream code exhaustively matching without a wildcard could require updating.
  3. Condition filtering: Incompatible timelock conditions (mixed height/time CLTV or CSV) continue to be filtered out during condition folding exactly as before; the pre-check only counts potential Cartesian combinations before compatibility pruning.

Testing

Comprehensive regression tests cover:

  • High thresholds near $n$: 67-of-68 (Some(68)), 68-of-68 (Some(1)), 1-of-68 (Some(68)).
  • 32-bit intermediate overflow considerations: 35-of-36 (Some(36)).
  • Budget boundaries: 10-of-20 (Some(184756)), 8-of-21 (None at 200k), 12-of-24 (None at 200k).
  • Alternative condition branches legitimately exceeding vs within budget.
  • Zero and missing condition map entries.
  • Arithmetic safety for extreme $n$ and $m$ values (including usize::MAX).
  • Full descriptor policy extraction on Taproot multi_a(20, ...) with 21 keys (Satisfaction::PartialComplete with 21 folded combinations).
  • FoldedConditionMap verification for all combinations in accepted policies.
  • Validated with:
    • cargo +nightly fmt --all -- --check
    • cargo test --lib (debug and release)
    • RUSTFLAGS="-D warnings --cfg bdk_wallet_unstable" cargo clippy --all-features --all-targets
    • RUSTFLAGS="--cfg bdk_wallet_unstable" cargo check --all-targets --no-default-features --features miniscript/no-std,bdk_chain/hashbrown
    • RUSTDOCFLAGS="-D warnings --cfg bdk_wallet_unstable" cargo doc --workspace --all-features --no-deps

Closes #555.

Eager materialization of m-of-n combinations during policy extraction
in Satisfaction::finalize can lead to exponential time and memory
consumption for large threshold descriptors (such as Taproot multi_a).

Because Satisfaction::PartialComplete publicly exposes a concrete
FoldedConditionMap, replacing the map with a lazy iterator alone is
insufficient without breaking changes to the public API.

This commit introduces a checked upper bound (MAX_POLICY_COMBINATIONS = 200,000)
on the number of materialized threshold combinations and Cartesian condition
expansions before allocation. This bound accommodates all conventional
20-key multisig thresholds (including 10-of-20 with 184,756 combinations)
while preventing unconstrained allocation and long hangs on larger thresholds.

When the combination budget or condition expansion is exceeded, policy
extraction returns PolicyError::ThresholdCombinationsExceeded rather than
hanging or allocating unbounded memory. Accepted policies retain their exact
conditions and deterministic behavior.
Intermediate DP states in checked_expanded_combinations_count could
overflow usize::MAX on large n policies with high thresholds near n
(such as 67-of-68 where C(68, 67) = 68, or 35-of-36 on 32-bit systems)
because intermediate combinations around n / 2 grow combinatorially
large before descending near n. This caused false rejections even
when the true candidate count was well within the enumeration budget.

This commit resolves intermediate overflow by:
- Representing DP states as u128.
- Using saturating multiplication and addition for intermediate states.
- Clamping each DP state to (budget + 1), which prevents intermediate
  overflow while preserving exact values for any final total at or
  below the budget.
- Safely handling m = 0, m = items.len(), and zero/missing condition items.

Added regression tests covering 67-of-68, 68-of-68, 1-of-68, 35-of-36,
10-of-20, budget boundary rejections (8-of-21, 12-of-24), Cartesian
condition alternatives, zero/missing condition items, large n/m values,
Taproot multi_a descriptors near n, and FoldedConditionMap combination
preservation.
@j-kon
j-kon marked this pull request as ready for review October 17, 2026 02:57
@j-kon
j-kon requested a review from a team as a code owner October 17, 2026 02:57

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Triage

Development

Successfully merging this pull request may close these issues.

extract_policy enumerates all m-of-n combinations; impractical for large multi_a

1 participant