Skip to content

Implement lane-stable assumevalid burial-time calculation #83

Closed

Description

@kiwidream

Summary

GetBlockProofEquivalentTime converts a chainwork delta into seconds using the
proof of the current best-header tip. Under qbit's dual-lane cadence, the
permissionless and AuxPoW lanes can have very different per-block proof. The
result therefore depends on which lane produced the tip rather than the
aggregate rate at which the chain accumulated work.

Once a non-zero defaultAssumeValid is configured, an adverse permissionless
tip during high AuxPoW proof dominance can make the two-week script-check
burial window appear much older than it is in wall-clock time. Nodes may then
skip historical script checks with substantially less burial than intended.

This is inactive by default while defaultAssumeValid=0, but it should be
fixed before a non-zero assumevalid checkpoint is set.

Current behavior

ChainstateManager::CanSkipScriptChecks calls:

GetBlockProofEquivalentTime(
    *m_best_header,
    block_index,
    *m_best_header,
    GetConsensus())

The helper multiplies the work delta by nPowTargetSpacing and divides by
GetBlockProof(tip). In a dual-lane chain, changing only the tip from a
permissionless block to a high-proof AuxPoW block can move the estimate across
the two-week threshold.

For a fixed 4:1 cadence and AuxPoW-to-permissionless proof ratio k, the
estimate-to-wall-clock ratios are:

  • Permissionless tip: (4 + k) / 5
  • AuxPoW tip: (4 + k) / (5k)

At large k, a permissionless tip can overstate burial time by orders of
magnitude.

Expected behavior

Assumevalid script-check skipping should use a lane-stable estimate of the
aggregate chainwork rate. Tip lane parity alone must not materially shorten the
two-week defense-in-depth window.

The existing generic equivalent-time behavior used by other policies, such as
stale-relay handling, is outside the scope of this change.

Implementation plan

1. Keep the change scoped to assumevalid policy

Modify the full-block branch of
ChainstateManager::CanSkipScriptChecks in src/validation.cpp.

Preserve these existing behaviors:

  • IsAssumedValidAncestor remains the first gate and continues to enforce the
    configured assumevalid hash, best-header ancestry, and minimum-chainwork
    requirements.
  • witness_unavailable=true continues to use the existing witness-pruned
    ancestry/work behavior.
  • GetBlockProofEquivalentTime remains unchanged because it is also used by
    stale-relay policy. Changing its global semantics would unnecessarily widen
    the scope of this fix.
  • Fork choice, nChainWork accumulation, difficulty adjustment, and
    nMinimumChainWork are not changed.

This is a validation-policy change only. It does not alter block validity,
serialization, the block-index database format, or consensus rules.

2. Define the sampling and threshold constants

Add policy-local constants near the assumevalid helpers in
src/validation.cpp:

static constexpr int ASSUMEVALID_WORK_RATE_WINDOW{120};
static constexpr uint32_t ASSUMEVALID_BURIAL_SECONDS{
    60 * 60 * 24 * 7 * 2
};

The 120-block window provides a bounded recent sample containing many blocks
from both lanes under the expected cadence, while avoiding an unbounded scan
for every script-skip decision. Median time past will be used for the window
endpoints so one block timestamp cannot directly control the rate.

3. Add an overflow-safe ratio comparison

Add a private helper with this responsibility:

static bool WorkDurationExceeds(
    const arith_uint256& burial_work,
    const arith_uint256& sample_work,
    uint32_t sample_seconds,
    uint32_t required_seconds);

It must evaluate this strict comparison:

burial_work / sample_work > required_seconds / sample_seconds

This is equivalent to asking whether the burial work represents more than the
required number of seconds at the sampled aggregate work rate.

Do not calculate the direct cross-products
burial_work * sample_seconds and sample_work * required_seconds; either can
overflow arith_uint256. Instead:

  1. Reject zero work or zero elapsed time.
  2. Divide both ratios into integer quotient and remainder components.
  3. Compare the integer quotients first.
  4. If the quotients are equal, compare the fractional components by deriving
    the remainder threshold through quotient/remainder arithmetic.
  5. Keep the comparison strict so a value exactly equal to two weeks does not
    permit script skipping; it must be greater than two weeks, matching current
    behavior.

Every intermediate multiplication must be proven smaller than its containing
arith_uint256 value, or limited to a uint64_t product of two uint32_t
remainders.

4. Compute a lane-stable recent work rate

Add a private helper:

static bool HasAssumeValidBurial(
    const CBlockIndex& tip,
    const CBlockIndex& block_index);

Implement it in this order:

  1. Start at tip and walk pprev exactly 120 times.

  2. Return false if the chain does not contain the complete sample window.
    Walking pprev directly also fails safely if the available history is
    shorter than the stored height suggests.

  3. Require both of these work deltas to be positive:

    burial_work = tip.nChainWork - block_index.nChainWork;
    sample_work = tip.nChainWork - window_start->nChainWork;
  4. Calculate elapsed sample time from median time past:

    sample_seconds =
        tip.GetMedianTimePast() - window_start->GetMedianTimePast();
  5. Return false if elapsed time is zero, negative, or cannot be represented
    by the unsigned type used by the comparison helper.

  6. Call WorkDurationExceeds with burial_work, sample_work,
    sample_seconds, and ASSUMEVALID_BURIAL_SECONDS.

The aggregate sample_work includes the actual work contributed by both
lanes. No branch should inspect the lane of tip or select a single block's
proof as the rate denominator.

5. Wire the new check into script skipping

Keep the existing gates in CanSkipScriptChecks and replace only the final
full-block calculation:

if (!IsAssumedValidAncestor(*this, block_index)) return false;
if (witness_unavailable) return true;

return HasAssumeValidBurial(*m_best_header, block_index);

This ensures every invalid, incomplete, or ambiguous rate sample fails closed
and retains script verification.

6. Extend the chainstate-manager test fixture

In src/test/validation_chainstatemanager_tests.cpp, extend the local
InsertTestBlockIndex helper with optional block-time and AuxPoW-lane inputs.
Use those inputs to build synthetic index chains with controlled:

  • timestamps;
  • per-block chainwork;
  • permissionless/AuxPoW version signaling; and
  • complete skip-list ancestry.

Default values must preserve existing call-site behavior.

Update the existing assumevalid gate test so its successful burial case has:

  • at least 120 ancestors available to the tip;
  • enough earlier history for both endpoint median-time-past calculations to
    use their full samples; and
  • work representing strictly more than two weeks at the sampled rate.

7. Add the mixed-lane regression

Add a dedicated test that reproduces the original failure mode:

  1. Derive a permissionless proof value from the regtest target.
  2. Derive an AuxPoW target producing approximately 1,000 times more proof per
    block.
  3. Build a 120-block recent window with a 4:1 permissionless-to-AuxPoW mix.
  4. Place the candidate's total burial work just below two weeks at that
    window's aggregate rate.
  5. End the first chain at a permissionless tip and demonstrate that the old
    GetBlockProofEquivalentTime calculation reports more than two weeks.
  6. Assert the replacement policy keeps script verification enabled.
  7. Append an AuxPoW tip while dropping an equivalent AuxPoW block from the
    start of the rolling window, keeping the aggregate sample effectively
    stable.
  8. Demonstrate that the old calculation now reports less than two weeks.
  9. Assert the replacement policy still keeps script verification enabled.

The test must show both properties simultaneously:

  • the old result changes sides of the threshold based on tip lane parity; and
  • the new result remains stable near the threshold.

8. Cover fail-closed and boundary behavior

Exercise the following cases through CanSkipScriptChecksForTest:

Scenario Expected result
Fewer than 120 ancestors Do not skip scripts
Candidate work equal to or above tip work Do not skip scripts
Non-increasing work across the sample Do not skip scripts
Zero or negative MTP interval Do not skip scripts
Burial exactly equal to two weeks Do not skip scripts
Burial strictly greater than two weeks Skip scripts
Large chainwork values that would overflow direct multiplication Return the mathematically correct result without overflow
Candidate not covered by assumevalid ancestry Do not skip scripts
Best header below nMinimumChainWork Do not skip scripts

Keep witness-pruned coverage separate so this change does not accidentally add
the full-block burial requirement to the existing
witness_unavailable=true path.

9. Validate the implementation

Configure and build the unit-test binary, then run:

cmake --build build --target test_bitcoin
build/bin/test_qbit --run_test=validation_chainstatemanager_tests
build/bin/test_qbit --run_test=pow_tests
build/bin/test_qbit --run_test=validation_tests
git diff --check

Run the repository lint suite in its documented Docker environment. If a
functional assumevalid fixture can model the mixed-lane work distribution
without excessive runtime, add and run that coverage as well; otherwise the
unit regression is sufficient for the lane-parity calculation.

10. Check operational impact

  • Confirm that nodes with defaultAssumeValid=0 are behaviorally unchanged.
  • Confirm that no block-index migration or chainstate rebuild is required.
  • Confirm that the generic equivalent-time helper and stale-relay policy are
    unchanged.
  • Confirm that the policy remains conservative during startup, short chains,
    malformed samples, and stalled timestamp windows.
  • Document the 120-block window next to the constant so future changes treat
    it as a security-sensitive policy parameter.

Files to change

  • src/validation.cpp
    • add the sampling constants;
    • add the exact ratio helper;
    • add the recent aggregate-work burial helper; and
    • update CanSkipScriptChecks.
  • src/test/validation_chainstatemanager_tests.cpp
    • extend the synthetic block-index helper;
    • update existing assumevalid burial coverage; and
    • add mixed-lane, boundary, and fail-closed regressions.

Completion checklist

  • The generic GetBlockProofEquivalentTime helper is unchanged.
  • Full-block assumevalid burial uses aggregate recent chainwork and MTP.
  • Tip lane parity cannot move the new estimate across the threshold in the
    mixed-lane regression.
  • The two-week comparison is exact and overflow-safe.
  • Invalid or incomplete samples fail closed.
  • Witness-pruned behavior is unchanged.
  • Unit tests and Docker lint pass.
  • No migration or consensus-rule change is introduced.

Activity

  1. added
    bug
    on Jul 10, 2026
  2. changed the title [-]Fix assumevalid burial-time distortion under dual-lane proof skew[/-] [+]Implement lane-stable assumevalid burial-time calculation[/+] on Jul 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions